logger.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. package fslog
  2. import (
  3. "fmt"
  4. "go.uber.org/zap"
  5. "go.uber.org/zap/zapcore"
  6. "gopkg.in/natefinch/lumberjack.v2"
  7. "io"
  8. "sync"
  9. )
  10. // 默认配置,准备了控制台、json文件两种输出方式
  11. var consoleEncoder zapcore.Encoder
  12. var jsonEncoder zapcore.Encoder
  13. var consoleSync zapcore.WriteSyncer
  14. var outputSync zapcore.WriteSyncer
  15. type outFileConfig struct {
  16. filename string
  17. maxSize int
  18. maxAge int
  19. maxBackups int
  20. localTime bool
  21. Compress bool
  22. }
  23. type Logger struct {
  24. // 互斥量
  25. // 用于内部不可并发逻辑使用
  26. lock sync.Mutex
  27. // 日志打印用
  28. logger zap.SugaredLogger
  29. // 当前日志打印级别
  30. // 借助zap内部级别设置机制,该机制
  31. // 内部使用乐观锁,协程安全
  32. lv zap.AtomicLevel
  33. // zapcore.Core 映射,存储不同来源/用途的core创建
  34. cores map[coreType][]zapcore.Core
  35. }
  36. func NewLogger() *Logger {
  37. logger := new(Logger)
  38. logger.lv = zap.NewAtomicLevelAt(zap.DebugLevel)
  39. logger.setCore(console, zapcore.NewCore(consoleEncoder, consoleSync, logger.lv))
  40. logger.setCore(output, zapcore.NewCore(jsonEncoder, outputSync, logger.lv))
  41. logger.flush()
  42. return logger
  43. }
  44. // With 拼接自定义信息
  45. // 主要用于打印当前环境快照信息(变量或其他自定义信息)
  46. // 打印后,该信息会跟随日志一起打印
  47. func (l *Logger) With(k string, v any) *Logger {
  48. defer l.logger.Sync()
  49. l.logger = *l.logger.With(zap.Any(k, v))
  50. return l
  51. }
  52. // Debug 格式化打印调试级别日志
  53. // 不同于zap内部可变参数逻辑,该可变参数是用于,字符串格式化的
  54. func (l *Logger) Debug(msg string, vs ...any) {
  55. defer l.logger.Sync()
  56. if len(vs) == 0 {
  57. l.logger.Debug(msg)
  58. return
  59. }
  60. l.logger.Debugf(fmt.Sprintf(msg, vs...))
  61. }
  62. // Info 格式化打印信息级别日志
  63. // 不同于zap内部可变参数逻辑,该可变参数是用于,字符串格式化的
  64. func (l *Logger) Info(msg string, vs ...any) {
  65. defer l.logger.Sync()
  66. if len(vs) == 0 {
  67. l.logger.Info(msg)
  68. return
  69. }
  70. l.logger.Infof(msg, vs...)
  71. }
  72. // Warn 格式化打印警告级别日志
  73. // 不同于zap内部可变参数逻辑,该可变参数是用于,字符串格式化的
  74. func (l *Logger) Warn(msg string, vs ...any) {
  75. defer l.logger.Sync()
  76. if len(vs) == 0 {
  77. l.logger.Warn(msg)
  78. return
  79. }
  80. l.logger.Warnf(msg, vs...)
  81. }
  82. // Error 打印错误级别日志
  83. // 该方法具有两种传参形式:
  84. // 1. error类型:会直接格式化打印%+v日志
  85. // 2. 信息(格式化)
  86. // 3. error+格式化信息:error会作为 With 格式存在,且依旧以%+v格式输出
  87. func (l *Logger) Error(vs ...any) {
  88. if len(vs) == 0 {
  89. return
  90. }
  91. defer l.logger.Sync()
  92. err, ok := vs[0].(error)
  93. if ok {
  94. if len(vs) == 1 {
  95. l.logger.Errorf("%+v", err)
  96. return
  97. }
  98. withed := l.logger.With(zap.String("err", fmt.Sprintf("%+v", err)))
  99. msg, ok := vs[1].(string)
  100. if ok {
  101. withed.Errorf(msg, vs[2:])
  102. return
  103. }
  104. withed.Error(vs[1:])
  105. return
  106. }
  107. msg, ok := vs[0].(string)
  108. if ok {
  109. if len(vs) > 1 {
  110. l.logger.Errorf(msg, vs[1:]...)
  111. return
  112. }
  113. if len(vs) == 1 {
  114. l.logger.Error(vs[0])
  115. return
  116. }
  117. }
  118. }
  119. // Lv 获取当前日志打印级别
  120. func (l *Logger) Lv() zap.AtomicLevel {
  121. return l.lv
  122. }
  123. // SetLv 设置当前日志打印级别
  124. func (l *Logger) SetLv(lv Level) {
  125. l.lv.SetLevel(lv.zap())
  126. }
  127. func (l *Logger) NewFileOutput(opts ...FileOutputOpt) {
  128. cfg := new(outFileConfig)
  129. for _, opt := range opts {
  130. opt(cfg)
  131. }
  132. l.newFileOut(*cfg)
  133. }
  134. func (l *Logger) NewOutput(writer io.Writer) {
  135. l.newOut(writer)
  136. }
  137. func (l *Logger) SetCore(core ...zapcore.Core) {
  138. l.setCore(third, core...)
  139. l.flush()
  140. }
  141. func (l *Logger) Flush() {
  142. err := l.logger.Sync()
  143. if err != nil {
  144. Warn("flush log error: %s", err.Error())
  145. }
  146. }
  147. func (l *Logger) newFileOut(cfg outFileConfig) {
  148. l.newOut(&lumberjack.Logger{
  149. Filename: cfg.filename,
  150. MaxSize: cfg.maxSize,
  151. MaxAge: cfg.maxAge,
  152. MaxBackups: cfg.maxBackups,
  153. LocalTime: cfg.localTime,
  154. Compress: cfg.Compress,
  155. })
  156. }
  157. func (l *Logger) newOut(writer io.Writer) {
  158. l.setCore(output, zapcore.NewCore(jsonEncoder, zapcore.AddSync(writer), l.lv))
  159. l.flush()
  160. }
  161. // 保存内部core(不负责刷新 logger)
  162. func (l *Logger) setCore(ct coreType, core ...zapcore.Core) {
  163. if l.cores == nil {
  164. l.cores = make(map[coreType][]zapcore.Core)
  165. }
  166. l.cores[ct] = append(l.cores[ct], core...)
  167. }
  168. // 刷新内部 logger
  169. // 刷新互斥,触发刷新后,刷新完成前依旧按照旧的配置执行
  170. func (l *Logger) flush() {
  171. l.lock.Lock()
  172. defer l.lock.Unlock()
  173. cores := make([]zapcore.Core, 0, len(l.cores))
  174. for _, core := range l.cores {
  175. cores = append(cores, core...)
  176. }
  177. l.logger = *zap.New(
  178. zapcore.NewTee(cores...),
  179. zap.AddCaller(),
  180. ).Sugar()
  181. }