当前位置:网站首页>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
边栏推荐
- The mystery of redis data migration capacity
- Load MySQL table data consumption quick installation configuration through kafka/flink
- A survey on dynamic neural networks for natural language processing, University of California
- Funny! Pictures and texts give you a comprehensive understanding of the effects of dynamics and mass
- A solution for building live video based on open source real-time audio and video webrtc architecture
- Inter thread communication of embedded development foundation
- National standard gb28181 protocol video platform easygbs alarm reporting function adds video alarm reporting and video recording
- Transpose convolution explanation
- Druid architecture and Implementation
- Virtual machine virtual disk recovery case tutorial
猜你喜欢

Some adventurer hybrid versions with potential safety hazards will be recalled
MySQL Advanced Series: Locks - Locks in InnoDB
Advanced programmers must know and master. This article explains in detail the principle of MySQL master-slave synchronization

Ps\ai and other design software pondering notes

Applet wxss

A survey on dynamic neural networks for natural language processing, University of California
![[leetcode108] convert an ordered array into a binary search tree (medium order traversal)](/img/e1/0fac59a531040d74fd7531e2840eb5.jpg)
[leetcode108] convert an ordered array into a binary search tree (medium order traversal)
![[go] concurrent programming channel](/img/6a/d62678467bbc6dfb6a50ae42bacc96.jpg)
[go] concurrent programming channel

Ui- first lesson

C. Three displays codeforces round 485 (Div. 2)
随机推荐
Some adventurer hybrid versions with potential safety hazards will be recalled
Kubernetes popular series: getting started with container Foundation
National standard gb28181 protocol video platform easygbs alarm reporting function adds video alarm reporting and video recording
ThinkPHP vulnerability exploitation tool
中金证券靠谱吗?是否合法?开股票账户安全吗?
Applet - use of template
Percona Toolkit series - Pt deadlock logger
Cloud + community [play with Tencent cloud] video solicitation activity winners announced
AI structured intelligent security video monitoring technology, supporting the protective umbrella of the reserve / wild animals
Funny! Pictures and texts give you a comprehensive understanding of the effects of dynamics and mass
MySQL timestamp format conversion date format string
Activeindex selection and redirection in the menu bar on the right of easycvs
Object store signature generation
How to collect and define project requirements in the early stage of EDI project implementation?
Little red book, hovering on the edge of listing
Tencent blue whale container management platform was officially released!
Teach you to write a classic dodge game
A troubleshooting of golang memory leak
MySQL Advanced Series: Locks - Locks in InnoDB
How do HPE servers make RAID5 arrays? Teach you step by step today!