当前位置:网站首页>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
原网站

版权声明
本文为[Johns]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/04/20210410200404848S.html