4

Currently, our project's log format is like:

www.abcdef.com`3`1s

I want to use Go to rewrite project and import zap as log tool. By zap the log's format is like:

{"url": "www.abcdef.com", "attempt": 3, "backoff": "1s"}

I google its usage, but I don't find out any way that changes zap's format to above mentioned, so I want to seek some advice here.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
shinwu
  • 93
  • 1
  • 1
  • 10
  • 1
    I found out the way to record complete string format. The `zapcore` support a struct EncoderConfig. When I set matter keys empty value, zap doesn't record info of these keys. Config is like this: `cfg := zapcore.EncoderConfig{ TimeKey: "", LevelKey: "", NameKey: "", CallerKey: "", MessageKey: "M", StacktraceKey: "" }` Anyway, thank you very much for your answer! – shinwu Sep 13 '18 at 03:41

3 Answers3

3

set EncoderConfig

cfg := zapcore.EncoderConfig{ 
    TimeKey: "", 
    LevelKey: "", 
    NameKey: "", 
    CallerKey: "", 
    MessageKey: "M", 
    StacktraceKey: "",
}
shinwu
  • 93
  • 1
  • 1
  • 10
1

Example configuration here:

        config := zap.NewProductionConfig()

        config.EncoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout(time.RFC3339)

        logger, _ := config.Build()

Check EncoderConfig in the source code, to find out what you can customize:

https://github.com/uber-go/zap/blob/master/zapcore/encoder.go#L316

crazyoptimist
  • 125
  • 1
  • 14
0

Zap allows to customize encoders. In the linked article author sets a field EncodeLevel of EncoderConfig to a custom function. That way you can change encoding of logging level, timestamp, duration, caller and logger name.

You also can use zap.RegisterEncoder to add your custom encoder and then set Encoding field in config to the name of your encoder.

Keep in mind that encoder is used on every call of a logging methods, so it must have a good perfomance.

Noman
  • 11
  • 3