logger.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. package log
  2. import (
  3. "fmt"
  4. "github.com/natefinch/lumberjack"
  5. "go.uber.org/zap"
  6. "go.uber.org/zap/zapcore"
  7. "os"
  8. )
  9. var (
  10. defaultLog *SLogger
  11. defLevel = zapcore.InfoLevel
  12. defMaxSize = 10
  13. defMaxAge = 30
  14. defMaxBackups = 360
  15. defCompressing = true
  16. levelMap = map[string]zapcore.Level{
  17. "trace": zapcore.DebugLevel,
  18. "debug": zapcore.DebugLevel,
  19. "info": zapcore.InfoLevel,
  20. "warning": zapcore.WarnLevel,
  21. "error": zapcore.ErrorLevel,
  22. "panic": zapcore.PanicLevel,
  23. "fatal": zapcore.FatalLevel,
  24. }
  25. )
  26. type SLoggerOption func(*SLogger)
  27. func WithSinks(sinks ...zap.Sink) SLoggerOption {
  28. return func(l *SLogger) {
  29. l.sinks = sinks
  30. }
  31. }
  32. func WithConsole(console bool) SLoggerOption {
  33. return func(l *SLogger) {
  34. l.console = console
  35. }
  36. }
  37. func WithCompress(compress bool) SLoggerOption {
  38. return func(l *SLogger) {
  39. l.settings.Compress = compress
  40. }
  41. }
  42. func WithMaxSizeSingleFile(maxsize int) SLoggerOption {
  43. return func(l *SLogger) {
  44. if maxsize < 1 {
  45. maxsize = defMaxSize
  46. }
  47. l.settings.MaxSize = maxsize
  48. }
  49. }
  50. func WithMaxAge(maxage int) SLoggerOption {
  51. return func(l *SLogger) {
  52. if maxage < 1 {
  53. maxage = defMaxAge
  54. }
  55. l.settings.MaxAge = maxage
  56. }
  57. }
  58. func WithMaxBackups(maxbackups int) SLoggerOption {
  59. return func(l *SLogger) {
  60. if maxbackups < 1 {
  61. maxbackups = defMaxBackups
  62. }
  63. l.settings.MaxBackups = maxbackups
  64. }
  65. }
  66. /// means log in a single file
  67. /// 默认配置:
  68. /// json 格式
  69. /// 单文件最大 10 m
  70. /// 最多保留1个月
  71. /// 压缩备份
  72. type SLogger struct {
  73. f string
  74. lg *zap.Logger
  75. settings lumberjack.Logger
  76. console bool
  77. sinks []zap.Sink
  78. }
  79. // @console: 是否输出到 console
  80. // @path: 路径
  81. // @level: 日志等级
  82. // @sinks: 日志额外的输出
  83. func NewSLogger(path string, level string, options ...SLoggerOption) *SLogger {
  84. slogger := &SLogger{
  85. f: path,
  86. lg: nil,
  87. settings: lumberjack.Logger{
  88. Filename: path,
  89. MaxSize: defMaxSize, //M
  90. MaxAge: defMaxAge, //d
  91. MaxBackups: defMaxBackups, //numbers
  92. Compress: true,
  93. },
  94. console: true,
  95. }
  96. for _, opt := range options {
  97. opt(slogger)
  98. }
  99. encoderConf := zapcore.EncoderConfig{
  100. MessageKey: "msg",
  101. LevelKey: "level",
  102. TimeKey: "ts",
  103. NameKey: "logger",
  104. CallerKey: "caller",
  105. StacktraceKey: "trace",
  106. LineEnding: zapcore.DefaultLineEnding,
  107. EncodeLevel: zapcore.LowercaseLevelEncoder,
  108. EncodeTime: zapcore.ISO8601TimeEncoder,
  109. EncodeDuration: zapcore.SecondsDurationEncoder,
  110. EncodeCaller: zapcore.ShortCallerEncoder,
  111. }
  112. // level
  113. corelevel, ok := levelMap[level]
  114. if !ok {
  115. fmt.Println("Warning: invalid log level: ", level)
  116. corelevel = defLevel
  117. }
  118. atom := zap.NewAtomicLevelAt(corelevel)
  119. wss := []zapcore.WriteSyncer{zapcore.AddSync(&slogger.settings)}
  120. if slogger.console {
  121. wss = append(wss, zapcore.AddSync(os.Stdout))
  122. }
  123. for _, sink := range slogger.sinks {
  124. wss = append(wss, zapcore.AddSync(sink))
  125. }
  126. // writeSyncer
  127. ws := zapcore.NewMultiWriteSyncer(wss...)
  128. // core
  129. core := zapcore.NewCore(zapcore.NewJSONEncoder(encoderConf), ws, atom)
  130. caller := zap.AddCaller()
  131. callerSkip := zap.AddCallerSkip(2)
  132. dev := zap.Development()
  133. stack := zap.AddStacktrace(zapcore.ErrorLevel)
  134. slogger.lg = zap.New(core, caller, callerSkip, dev, stack)
  135. return slogger
  136. }
  137. func (self *SLogger) Debug(msg string, fields ...zap.Field) {
  138. self.lg.Debug(msg, fields...)
  139. }
  140. func (self *SLogger) Info(msg string, fields ...zap.Field) {
  141. self.lg.Info(msg, fields...)
  142. }
  143. func (self *SLogger) Warn(msg string, fields ...zap.Field) {
  144. self.lg.Warn(msg, fields...)
  145. }
  146. func (self *SLogger) Error(msg string, fields ...zap.Field) {
  147. self.lg.Error(msg, fields...)
  148. }
  149. func (self *SLogger) Panic(msg string, fields ...zap.Field) {
  150. self.lg.Panic(msg, fields...)
  151. }
  152. func (self *SLogger) Fatal(msg string, fields ...zap.Field) {
  153. self.lg.Fatal(msg, fields...)
  154. }
  155. func (self *SLogger) Sync() {
  156. _ = self.lg.Sync()
  157. }
  158. func SetDefaultLogger(logger *SLogger) {
  159. defaultLog = logger
  160. }
  161. func Debug(msg string, fields ...zap.Field) {
  162. defaultLog.Debug(msg, fields...)
  163. }
  164. func Info(msg string, fields ...zap.Field) {
  165. defaultLog.Info(msg, fields...)
  166. }
  167. func Warn(msg string, fields ...zap.Field) {
  168. defaultLog.Warn(msg, fields...)
  169. }
  170. func Error(msg string, fields ...zap.Field) {
  171. defaultLog.Error(msg, fields...)
  172. }
  173. func Panic(msg string, fields ...zap.Field) {
  174. defaultLog.Panic(msg, fields...)
  175. }
  176. func Fatal(msg string, fields ...zap.Field) {
  177. defaultLog.Fatal(msg, fields...)
  178. }
  179. func Sync() {
  180. defaultLog.Sync()
  181. }