shinwu
shinwu

Reputation: 113

How to custom log format when use zap?

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.

Upvotes: 6

Views: 21978

Answers (3)

crazyoptimist
crazyoptimist

Reputation: 434

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

Upvotes: 3

shinwu
shinwu

Reputation: 113

set EncoderConfig

cfg := zapcore.EncoderConfig{ 
    TimeKey: "", 
    LevelKey: "", 
    NameKey: "", 
    CallerKey: "", 
    MessageKey: "M", 
    StacktraceKey: "",
}

Upvotes: 3

Noman
Noman

Reputation: 21

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.

Upvotes: 0

Related Questions