zap.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package logger
  4. import (
  5. "strings"
  6. "time"
  7. "go.uber.org/zap"
  8. "go.uber.org/zap/zapcore"
  9. "gopkg.in/natefinch/lumberjack.v2"
  10. )
  11. // zapConfig 用于对zap进行配置的参数
  12. type zapConfig struct {
  13. Level zap.AtomicLevel `json:"level" yaml:"level"`
  14. Development bool `json:"development" yaml:"development"`
  15. DisableCaller bool `json:"disableCaller" yaml:"disableCaller"`
  16. DisableStacktrace bool `json:"disableStacktrace" yaml:"disableStacktrace"`
  17. Encoding string `json:"encoding" yaml:"encoding"`
  18. OutputPath string `json:"outputPath" yaml:"outputPath"`
  19. }
  20. // New 创建logger
  21. func (zc *zapConfig) New(maxSize, maxBackups, maxAge int) *zap.Logger {
  22. // if nil, default the values
  23. if maxSize == 0 {
  24. maxSize = 100
  25. }
  26. if maxBackups == 0 {
  27. maxBackups = 7
  28. }
  29. if maxAge == 0 {
  30. maxAge = 30
  31. }
  32. hook := lumberjack.Logger{
  33. Filename: zc.OutputPath,
  34. MaxSize: maxSize, // megabytes
  35. MaxBackups: maxBackups, // backups number
  36. MaxAge: maxAge, // days
  37. Compress: true, // disabled by default
  38. }
  39. fileWriter := zapcore.AddSync(&hook)
  40. var encoderConfig zapcore.EncoderConfig
  41. if zc.Development {
  42. encoderConfig = zap.NewDevelopmentEncoderConfig()
  43. } else {
  44. encoderConfig = zap.NewProductionEncoderConfig()
  45. }
  46. // 自定义
  47. encoderConfig.EncodeTime = CustomTimeEncoder
  48. var encoder zapcore.Encoder
  49. if strings.ToLower(zc.Encoding) == "console" {
  50. encoder = zapcore.NewConsoleEncoder(encoderConfig)
  51. } else {
  52. encoder = zapcore.NewJSONEncoder(encoderConfig)
  53. }
  54. core := zapcore.NewCore(encoder, fileWriter, zc.Level)
  55. opts := zc.buildOptions(fileWriter)
  56. return zap.New(core, opts...)
  57. }
  58. func (zc *zapConfig) buildOptions(fileWriter zapcore.WriteSyncer) []zap.Option {
  59. opts := []zap.Option{zap.ErrorOutput(fileWriter)}
  60. if !zc.DisableCaller {
  61. opts = append(opts, zap.AddCaller())
  62. }
  63. if !zc.DisableStacktrace {
  64. stackLevel := zap.ErrorLevel
  65. if zc.Development {
  66. stackLevel = zap.WarnLevel
  67. }
  68. opts = append(opts, zap.AddStacktrace(stackLevel))
  69. }
  70. return opts
  71. }
  72. // 自定义时间格式
  73. func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
  74. enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
  75. }