simple_zap.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package simple_zap
  2. import (
  3. "context"
  4. "go.uber.org/zap"
  5. "go.uber.org/zap/zapcore"
  6. "gopkg.in/natefinch/lumberjack.v2"
  7. )
  8. const loggerCtxKey = "baozhida"
  9. var Logger *zap.Logger
  10. func init() {
  11. hook := lumberjack.Logger{
  12. Filename: "./log/app.log",
  13. MaxSize: 1,
  14. Compress: true,
  15. MaxAge: 30,
  16. MaxBackups: 7,
  17. LocalTime: true,
  18. }
  19. encoder_config := zapcore.EncoderConfig{
  20. MessageKey: "message",
  21. LevelKey: "level",
  22. TimeKey: "time",
  23. CallerKey: "lineNum",
  24. FunctionKey: "func",
  25. LineEnding: zapcore.DefaultLineEnding, // 回车符换行
  26. EncodeLevel: zapcore.LowercaseLevelEncoder, // level小写: info,debug,warn等 而不是 Info, Debug,Warn等
  27. EncodeTime: zapcore.ISO8601TimeEncoder, // 时间格式: "2006-01-02T15:04:05.000Z0700"
  28. EncodeDuration: zapcore.SecondsDurationEncoder, // 时间戳用float64型,更加准确, 另一种是NanosDurationEncoder int64
  29. EncodeCaller: zapcore.ShortCallerEncoder, // 产生日志文件的路径格式: 包名/文件名:行号
  30. }
  31. caller := zap.AddCaller() //日志打印输出 文件名, 行号, 函数名
  32. development := zap.Development() // 可输出 dpanic, panic 级别的日志
  33. field := zap.Fields() // 负责给日志生成一个个 k-v 对
  34. var syncers []zapcore.WriteSyncer // io writer
  35. syncers = append(syncers, zapcore.AddSync(&hook))
  36. atomic_level := zap.NewAtomicLevel() // 设置日志 level
  37. atomic_level.SetLevel(zap.DebugLevel) // 打印 debug, info, warn,eror, depanic,panic,fetal 全部级别日志
  38. core := zapcore.NewCore(zapcore.NewJSONEncoder(encoder_config), zapcore.NewMultiWriteSyncer(syncers...), atomic_level)
  39. Logger = zap.New(core, caller, development, field)
  40. }
  41. // NewCtx 给 ctx 注入一个 looger, logger 中包含Field(内含日志打印的 k-v对)
  42. func NewCtx(ctx context.Context, fields ...zapcore.Field) context.Context {
  43. return context.WithValue(ctx, loggerCtxKey, WithCtx(ctx).With(fields...))
  44. }
  45. // WithCtx 尝试从 context 中获取带有 traceId Field的 logge
  46. func WithCtx(ctx context.Context) *zap.Logger {
  47. if ctx == nil {
  48. return Logger
  49. }
  50. ctx_logger, ok := ctx.Value(loggerCtxKey).(*zap.Logger)
  51. if ok {
  52. return ctx_logger
  53. }
  54. return Logger
  55. }