Is there any way in which I can hide logging sensitive fields while using ubergo zap.
Will appreciate if somebody can show an example
You can make those fields custom type and implement Stringer interface for them printing ****
. For example:
type X string
func (x X) String() string {
return "***"
}
func main() {
x := X("aaaaa")
log.Infow("msg", "x", x)
}
will print msg {"x": "***"}
.
Or you can implement your own version of Encoder
where you would filter fields by name or their type Interface
in EncodeEntry(ent Entry, fields []Field)
function. You can take one of the two existing encoders - console or json - as a base. For example:
package main
import (
"go.uber.org/zap"
"go.uber.org/zap/buffer"
"go.uber.org/zap/zapcore"
)
type MyEncoder struct {
zapcore.Encoder
}
func (m *MyEncoder) EncodeEntry(entry zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error) {
filtered := make([]zapcore.Field, 0, len(fields))
for _, field := range fields {
if field.Key == "skip" || field.Type == zapcore.Int64Type {
continue
}
filtered = append(filtered, field)
}
return m.Encoder.EncodeEntry(entry, filtered)
}
func main() {
_ = zap.RegisterEncoder("mine", func(config zapcore.EncoderConfig) (zapcore.Encoder, error) {
encoder := zapcore.NewConsoleEncoder(config)
return &MyEncoder{encoder}, nil
})
config := zap.NewDevelopmentConfig()
config.Encoding = "mine"
log, _ := config.Build()
sugar := log.Sugar()
sugar.Infow("Some message", "skip", "skipped", "notskip", "present", "alsoskipping", int64(1))
}
This will print
2022-08-24T13:25:54.368+0200 INFO testl/main.go:33 Some message {"notskip": "present"}