Open spiderpoison opened 5 years ago
You can do something like this:
func lowerCaseLevelEncoder(
level zapcore.Level,
enc zapcore.PrimitiveArrayEncoder,
) {
if level == zap.PanicLevel || level == zap.DPanicLevel {
enc.AppendString("error")
return
}
zapcore.LowercaseLevelEncoder(level, enc)
}
func createLogger() *zap.Logger {
stdout := zapcore.AddSync(os.Stdout)
level := zap.NewAtomicLevelAt(zap.InfoLevel)
productionCfg := zap.NewProductionEncoderConfig()
productionCfg.TimeKey = "timestamp"
productionCfg.EncodeTime = zapcore.ISO8601TimeEncoder
productionCfg.EncodeLevel = lowerCaseLevelEncoder
jsonEncoder := zapcore.NewJSONEncoder(productionCfg)
core := zapcore.NewCore(jsonEncoder, stdout, level)
return zap.New(core)
}
func main() {
logger := createLogger()
defer logger.Sync()
logger.DPanic(
"this was never supposed to happen",
)
}
{"level":"error","timestamp":"2023-05-15T18:55:33.534+0100","msg":"this was never supposed to happen"}
The level is intentionally maintained, since it's useful when looking at logs (in production) to distinguish between errors and DPanic. A DPanic log in production is something that should not happen (usually indicates a code bug).
If I set Development = false, then DPanic should be log at ErrorLevel? But I found it still log at "DPANIC". like this:
{"L":"DPANIC","TS":"[2018-09-06T18:01:19.984+0800]","CALLER":"zap/zaplog.go:188:main.main.func1.1","MSG":"in go panic","url":"http://127.0.0.1","STACK":"main.main.func1.1\n\t/Users/zhangzhen/serverthreekingdom/src/vcs.taiyouxi.net/examples/log/zap/zaplog.go:188\nruntime.call32\n\t/Users/zhangzhen/.gvm/gos/go1.11/src/runtime/asm_amd64.s:522\nruntime.gopanic\n\t/Users/zhangzhen/.gvm/gos/go1.11/src/runtime/panic.go:513\nmain.main.func1\n\t/Users/zhangzhen/serverthreekingdom/src/vcs.taiyouxi.net/examples/log/zap/zaplog.go:191"}