zap.go 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package config
  2. import (
  3. "go.uber.org/zap/zapcore"
  4. "strings"
  5. )
  6. type Zap struct {
  7. TagName string `mapstructure:"tag_name" json:"tag_name" yaml:"tag_name"` // 日志名
  8. Level string `mapstructure:"level" json:"level" yaml:"level"` // 级别
  9. Prefix string `mapstructure:"prefix" json:"prefix" yaml:"prefix"` // 日志前缀
  10. Format string `mapstructure:"format" json:"format" yaml:"format"` // 输出类型 json
  11. Director string `mapstructure:"director" json:"director" yaml:"director"` // 日志文件夹
  12. EncodeLevel string `mapstructure:"encode_level" json:"encode_level" yaml:"encode_level"` // 编码级
  13. StacktraceKey string `mapstructure:"stacktrace_key" json:"stacktrace_key" yaml:"stacktrace_key"` // 堆栈跟踪关键字
  14. MaxAge int `mapstructure:"max_age" json:"max_age" yaml:"max_age"` // 日志最大保留(天)
  15. RotationSize int64 `mapstructure:"rotation_size" json:"rotation_size" yaml:"rotation_size"` // 单个日志文件大小:M
  16. RotationCount uint `mapstructure:"rotation_count" json:"rotation_count" yaml:"rotation_count"` // 保存日志份数
  17. ShowLine bool `mapstructure:"show_line" json:"show_line" yaml:"show_line"` // 显示行
  18. LogInConsole bool `mapstructure:"log_in_console" json:"log_in_console" yaml:"log_in_console"` // 输出控制台
  19. LogOutputFile bool `mapstructure:"log_output_file" json:"log_output_file" yaml:"log_output_file"` // 输出到文件
  20. }
  21. func (z *Zap) LogSaveCount() uint {
  22. if z.RotationCount < 3 {
  23. return uint(3)
  24. }
  25. return z.RotationCount
  26. }
  27. func (z *Zap) LogSignSize() int64 {
  28. if z.RotationSize < 100 {
  29. return int64(100)
  30. }
  31. return z.RotationSize
  32. }
  33. func (z *Zap) ZapEncodeLevel() zapcore.LevelEncoder {
  34. switch {
  35. case z.EncodeLevel == "LowercaseLevelEncoder": // 小写编码器(默认)
  36. return zapcore.LowercaseLevelEncoder
  37. case z.EncodeLevel == "LowercaseColorLevelEncoder": // 小写编码器带颜色
  38. return zapcore.LowercaseColorLevelEncoder
  39. case z.EncodeLevel == "CapitalLevelEncoder": // 大写编码器
  40. return zapcore.CapitalLevelEncoder
  41. case z.EncodeLevel == "CapitalColorLevelEncoder": // 大写编码器带颜色
  42. return zapcore.CapitalColorLevelEncoder
  43. default:
  44. return zapcore.LowercaseLevelEncoder
  45. }
  46. }
  47. func (z *Zap) TransportLevel() zapcore.Level {
  48. z.Level = strings.ToLower(z.Level)
  49. switch z.Level {
  50. case "debug":
  51. return zapcore.DebugLevel
  52. case "info":
  53. return zapcore.InfoLevel
  54. case "warn":
  55. return zapcore.WarnLevel
  56. case "error":
  57. return zapcore.WarnLevel
  58. case "dpanic":
  59. return zapcore.DPanicLevel
  60. case "panic":
  61. return zapcore.PanicLevel
  62. case "fatal":
  63. return zapcore.FatalLevel
  64. default:
  65. return zapcore.DebugLevel
  66. }
  67. }