当前位置:网站首页>How to customize the log output format of zap?
How to customize the log output format of zap?
2022-06-24 16:41:00 【Johns】
The problem background
The last article introduced how to go-kit Integrate zap Conduct log Output 《go-kit Microservices Integrate zap Log Library 》, Finally, after the integration is completed, the returned log It's a json The format is somewhat different from the project standard log format , So I want to customize zap log The output format of .
The original format :
{"level":"info","ts":1617979575129,"caller":"cmd/main.go:62","msg":"prom server start success, port 10081"}What you want output to look like
[2021-04-10 17:27:55.419] [INFO] [212fb8d8-4e30-44fd-a6f2-d0a9b9799b9d] [cmd/main.go:62] prom server start success, port 10081
Solution
Check the official zap When the output format of the zapcore.EncoderConfig Object , So we only need to modify its initialization process , among 212fb8d8-4e30-44fd-a6f2-d0a9b9799b9d Is a global request id(trace_id) We can ignore this content section first , Let's see how to change it .
const (
logTmFmtWithMS = "2006-01-02 15:04:05.000"
)
func initCore(l *Log) zapcore.Core {
opts := []zapcore.WriteSyncer{
zapcore.AddSync(&lumberjack.Logger{
Filename: filepath.Join(l.logDir, l.logFileName), // ⽇ Records ⽂ Piece path
MaxSize: l.logMaxSize, // Unit is MB, The default is 512MB
MaxAge: l.logMaxAge, // How many days can the file be saved at most
LocalTime: l.localTime, // Adopt local time
Compress: l.logCompress, // Whether to compress the log
}),
}
if l.stdout {
opts = append(opts, zapcore.AddSync(os.Stdout))
}
syncWriter := zapcore.NewMultiWriteSyncer(opts...)
// Custom time output format
customTimeEncoder := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + t.Format(logTmFmtWithMS) + "]")
}
// Customize the log level display
customLevelEncoder := func(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + level.CapitalString() + "]")
}
// Customization files : Line number output item
customCallerEncoder := func(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + l.traceId + "]")
enc.AppendString("[" + caller.TrimmedPath() + "]")
}
encoderConf := zapcore.EncoderConfig{
CallerKey: "caller_line", // Print file name and number of lines
LevelKey: "level_name",
MessageKey: "msg",
TimeKey: "ts",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeTime: customTimeEncoder, // Customize the time format
EncodeLevel: customLevelEncoder, // Lowercase encoder
EncodeCaller: customCallerEncoder, // Full path encoder
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeName: zapcore.FullNameEncoder,
}
// level Upper case coloring encoder
if l.enableColor {
encoderConf.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
// json format processing
if l.jsonFormat {
return zapcore.NewCore(zapcore.NewJSONEncoder(encoderConf),
syncWriter, zap.NewAtomicLevelAt(l.logMinLevel))
}
return zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConf),
syncWriter, zap.NewAtomicLevelAt(l.logMinLevel))
}test
[2021-04-10 18:24:34.329] [INFO] [c9c4eabb-8277-57f7-8465-6176f27d0cef] [service/service.go:52] req=a:3 b:5 multipy result=15
边栏推荐
- Transpose convolution learning notes
- A set of very good H3C and Tianrongxin Internet cutover scheme templates, with word document download
- Annual contribution! Tencent cloud middleware product upgrade conference is in hot registration!
- MySQL Advanced Series: locks - locks in InnoDB
- How to use the national standard streaming media server to view the video stream of the surveillance camera? How to correctly use UDP and TCP protocols?
- What is a reptile
- 2021 devopsdays Tokyo Station ends perfectly | coding experts are invited to share the latest technical information
- TRTC web end imitation Tencent conference microphone mute detection
- Modern finite element analysis can easily achieve accurate results
- Coding's first closed door meeting on financial technology exchange was successfully held
猜你喜欢

Daily algorithm & interview questions, 28 days of special training in large factories - the 15th day (string)

C. Three displays codeforces round 485 (Div. 2)

Applet wxss

Ui- first lesson

ZOJ - 4104 sequence in the pocket

A survey on model compression for natural language processing (NLP model compression overview)

Some adventurer hybrid versions with potential safety hazards will be recalled

A survey of training on graphs: taxonomy, methods, and Applications

Ps\ai and other design software pondering notes
MySQL Advanced Series: Locks - Locks in InnoDB
随机推荐
How to save data to the greatest extent after deleting LV by misoperation under AIX?
Edit distance (linear dp+ violence matching)
Tencent blue whale container management platform was officially released!
Development trend of CAE simulation analysis software
Embedded Software Engineer written interview guide arm system and architecture
Where is the most formal and safe account opening for speculation futures? How to open a futures account?
Introduction to koa (III) koa routing
[tke] troubleshooting tips for container problems
Modern finite element analysis can easily achieve accurate results
In those years, I insisted on learning the motivation of programming
Tencent releases the full platform version of reasoning framework TNN, and supports mobile terminal, desktop terminal and server terminal at the same time
炒期货在哪里开户最正规安全?怎么期货开户?
How to open a futures account safely? Which futures companies are more reliable?
ThinkPHP vulnerability exploitation tool
Regular expression learning artifact!
[play with Tencent cloud] & lt; trtc-room> Applet component usage
The million bonus competition is about to start, and Ti-One will be upgraded to help you win the championship!
[tke] enable CPU static management strategy
Find out the invisible assets -- use hosts collision to break through the boundary
MySQL進階系列:鎖-InnoDB中鎖的情况