上一篇介绍到如何在go-kit整合zap进行log输出《go-kit 微服务 整合zap日志库》,最后整合完毕后发现返回的log是一个json格式和项目标准的日志格式有一些不一样,所以想自定义zap log的输出格式。
原来的格式:
{"level":"info","ts":1617979575129,"caller":"cmd/main.go:62","msg":"prom server start success, port 10081"}
希望输出的样子
[2021-04-10 17:27:55.419] [INFO] [212fb8d8-4e30-44fd-a6f2-d0a9b9799b9d] [cmd/main.go:62] prom server start success, port 10081
查阅了一下官方zap的输出格式时通过zapcore.EncoderConfig
对象进行配置的, 所以我们也只需要修改它的一个初始化过程便可, 其中212fb8d8-4e30-44fd-a6f2-d0a9b9799b9d是一个全局的请求id(trace_id)我们可以先忽略这个内容部分,先看怎么改。
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), // ⽇志⽂件路径
MaxSize: l.logMaxSize, // 单位为MB,默认为512MB
MaxAge: l.logMaxAge, // 文件最多保存多少天
LocalTime: l.localTime, // 采用本地时间
Compress: l.logCompress, // 是否压缩日志
}),
}
if l.stdout {
opts = append(opts, zapcore.AddSync(os.Stdout))
}
syncWriter := zapcore.NewMultiWriteSyncer(opts...)
// 自定义时间输出格式
customTimeEncoder := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + t.Format(logTmFmtWithMS) + "]")
}
// 自定义日志级别显示
customLevelEncoder := func(level zapcore.Level, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + level.CapitalString() + "]")
}
// 自定义文件:行号输出项
customCallerEncoder := func(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString("[" + l.traceId + "]")
enc.AppendString("[" + caller.TrimmedPath() + "]")
}
encoderConf := zapcore.EncoderConfig{
CallerKey: "caller_line", // 打印文件名和行数
LevelKey: "level_name",
MessageKey: "msg",
TimeKey: "ts",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeTime: customTimeEncoder, // 自定义时间格式
EncodeLevel: customLevelEncoder, // 小写编码器
EncodeCaller: customCallerEncoder, // 全路径编码器
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeName: zapcore.FullNameEncoder,
}
// level大写染色编码器
if l.enableColor {
encoderConf.EncodeLevel = zapcore.CapitalColorLevelEncoder
}
// json 格式化处理
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))
}
[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
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有