Skip to content

Instantly share code, notes, and snippets.

@MadVikingGod
Last active January 24, 2022 18:03
Show Gist options
  • Save MadVikingGod/bb04c40e654602e173934180c691d645 to your computer and use it in GitHub Desktop.
Save MadVikingGod/bb04c40e654602e173934180c691d645 to your computer and use it in GitHub Desktop.
Demonstration of MarshalLog errors
package main
import (
"fmt"
"log"
"os"
"github.com/go-logr/logr"
"github.com/go-logr/stdr"
"github.com/go-logr/zapr"
"go.uber.org/zap"
)
type testMarshler struct {
value int
}
func (m testMarshler) MarshalLog() interface{} {
return struct {
Value int
}{
Value: m.value,
}
}
func main() {
stdLogr := stdr.New(log.New(os.Stdout, "", log.Default().Flags()))
zapLogr := zapr.NewLogger(zap.NewExample())
printLogr(stdLogr)
printLogr(zapLogr)
}
func printLogr(l logr.Logger) {
x := testMarshler{1}
y := []testMarshler{{2}, {3}}
z := map[string]testMarshler{"foo": {4}, "bar": {5}}
a := struct{ Embed testMarshler }{Embed: testMarshler{6}}
fmt.Println("=====================")
l.Info("bare struct", "x", x)
l.Info("slice", "y", y)
l.Info("map", "z", z)
l.Info("object", "a", a)
}
$ go run .
=====================
2022/01/24 17:58:42 "level"=0 "msg"="bare struct" "x"={"Value":1}
2022/01/24 17:58:42 "level"=0 "msg"="slice" "y"=[{"Value":2},{"Value":3}]
2022/01/24 17:58:42 "level"=0 "msg"="map" "z"={"foo":{"Value":4},"bar":{"Value":5}}
2022/01/24 17:58:42 "level"=0 "msg"="object" "a"={"Embed":{"Value":6}}
=====================
{"level":"info","msg":"bare struct","x":{"Value":1}}
{"level":"info","msg":"slice","y":[{},{}]}
{"level":"info","msg":"map","z":{"bar":{},"foo":{}}}
{"level":"info","msg":"object","a":{"Embed":{}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment