How to custom log format when use zap?
Asked Answered
M

3

6

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.

Malay answered 11/9, 2018 at 10:58 Comment(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!Malay
M
3

set EncoderConfig

cfg := zapcore.EncoderConfig{ 
    TimeKey: "", 
    LevelKey: "", 
    NameKey: "", 
    CallerKey: "", 
    MessageKey: "M", 
    StacktraceKey: "",
}
Malay answered 13/9, 2018 at 3:47 Comment(0)
B
2

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

Bozarth answered 1/3, 2023 at 17:43 Comment(0)
G
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.

Goldagoldarina answered 15/11, 2018 at 11:58 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.