You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

167 lines
5.4 KiB

  1. package initialize
  2. import (
  3. "context"
  4. "fmt"
  5. "gin-vue-admin/global"
  6. "go.uber.org/zap"
  7. "gorm.io/gorm/logger"
  8. "gorm.io/gorm/utils"
  9. "io/ioutil"
  10. "log"
  11. "os"
  12. "time"
  13. )
  14. var (
  15. Discard = New(log.New(ioutil.Discard, "", log.LstdFlags), log.New(ioutil.Discard, "", log.LstdFlags), GormConfig{})
  16. Default = New(log.New(os.Stdout, "\r\n", log.LstdFlags), log.New(os.Stdout, "\r\n", log.LstdFlags), GormConfig{
  17. SlowThreshold: 200 * time.Millisecond,
  18. LogLevel: logger.Warn,
  19. Colorful: true,
  20. })
  21. Recorder = traceRecorder{Interface: Default, BeginAt: time.Now()}
  22. )
  23. type traceRecorder struct {
  24. logger.Interface
  25. BeginAt time.Time
  26. SQL string
  27. RowsAffected int64
  28. Err error
  29. }
  30. func New(writer Writer, gormWriter logger.Writer, config GormConfig) logger.Interface {
  31. var (
  32. infoStr = "%s\n[info] "
  33. warnStr = "%s\n[warn] "
  34. errStr = "%s\n[error] "
  35. traceStr = "%s\n[%.3fms] [rows:%v] %s"
  36. traceWarnStr = "%s %s\n[%.3fms] [rows:%v] %s"
  37. traceErrStr = "%s %s\n[%.3fms] [rows:%v] %s"
  38. )
  39. if config.Colorful {
  40. infoStr = logger.Green + "%s\n" + logger.Reset + logger.Green + "[info] " + logger.Reset
  41. warnStr = logger.BlueBold + "%s\n" + logger.Reset + logger.Magenta + "[warn] " + logger.Reset
  42. errStr = logger.Magenta + "%s\n" + logger.Reset + logger.Red + "[error] " + logger.Reset
  43. traceStr = logger.Green + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s"
  44. traceWarnStr = logger.Green + "%s " + logger.Yellow + "%s\n" + logger.Reset + logger.RedBold + "[%.3fms] " + logger.Yellow + "[rows:%v]" + logger.Magenta + " %s" + logger.Reset
  45. traceErrStr = logger.RedBold + "%s " + logger.MagentaBold + "%s\n" + logger.Reset + logger.Yellow + "[%.3fms] " + logger.BlueBold + "[rows:%v]" + logger.Reset + " %s"
  46. }
  47. return &GormLogger{
  48. Writer: writer,
  49. gormWriter: gormWriter,
  50. GormConfig: config,
  51. infoStr: infoStr,
  52. warnStr: warnStr,
  53. errStr: errStr,
  54. traceStr: traceStr,
  55. traceWarnStr: traceWarnStr,
  56. traceErrStr: traceErrStr,
  57. }
  58. }
  59. // Writer log writer interface
  60. type Writer interface {
  61. Printf(string, ...interface{})
  62. }
  63. type GormConfig struct {
  64. SlowThreshold time.Duration
  65. Colorful bool
  66. LogLevel logger.LogLevel
  67. }
  68. type GormLogger struct {
  69. Writer
  70. gormWriter logger.Writer
  71. GormConfig
  72. infoStr, warnStr, errStr string
  73. traceStr, traceErrStr, traceWarnStr string
  74. }
  75. func (g *GormLogger) LogMode(level logger.LogLevel) logger.Interface {
  76. newLogger := *g
  77. newLogger.LogLevel = level
  78. return &newLogger
  79. }
  80. func (g *GormLogger) Info(ctx context.Context, message string, data ...interface{}) {
  81. if g.LogLevel >= logger.Info {
  82. g.Printf(g.infoStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
  83. }
  84. }
  85. func (g *GormLogger) Warn(ctx context.Context, message string, data ...interface{}) {
  86. if g.LogLevel >= logger.Warn {
  87. g.Printf(g.warnStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
  88. }
  89. }
  90. func (g *GormLogger) Error(ctx context.Context, message string, data ...interface{}) {
  91. if g.LogLevel >= logger.Error {
  92. g.Printf(g.errStr+message, append([]interface{}{utils.FileWithLineNum()}, data...)...)
  93. }
  94. }
  95. func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
  96. if g.LogLevel > 0 {
  97. elapsed := time.Since(begin)
  98. switch {
  99. case err != nil && g.LogLevel >= logger.Error:
  100. sql, rows := fc()
  101. if rows == -1 {
  102. g.Printf(g.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, "-", sql)
  103. } else {
  104. g.Printf(g.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
  105. }
  106. case elapsed > g.SlowThreshold && g.SlowThreshold != 0 && g.LogLevel >= logger.Warn:
  107. sql, rows := fc()
  108. slowLog := fmt.Sprintf("SLOW SQL >= %v", g.SlowThreshold)
  109. if rows == -1 {
  110. g.Printf(g.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, "-", sql)
  111. } else {
  112. g.Printf(g.traceWarnStr, utils.FileWithLineNum(), slowLog, float64(elapsed.Nanoseconds())/1e6, rows, sql)
  113. }
  114. case g.LogLevel >= logger.Info:
  115. sql, rows := fc()
  116. if rows == -1 {
  117. g.Printf(g.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, "-", sql)
  118. } else {
  119. g.Printf(g.traceStr, utils.FileWithLineNum(), float64(elapsed.Nanoseconds())/1e6, rows, sql)
  120. }
  121. }
  122. }
  123. }
  124. func (g *GormLogger) Printf(message string, data ...interface{}) {
  125. if global.GVA_CONFIG.Mysql.LogZap == "Info" && !global.GVA_CONFIG.Mysql.LogMode {
  126. switch len(data) {
  127. case 0:
  128. global.GVA_LOG.Info(message)
  129. case 1:
  130. global.GVA_LOG.Info("gorm", zap.Any("src", data[0]))
  131. case 2:
  132. global.GVA_LOG.Info("gorm", zap.Any("src", data[0]), zap.Any("duration", data[1]))
  133. case 3:
  134. global.GVA_LOG.Info("gorm", zap.Any("src", data[0]), zap.Any("duration", data[1]), zap.Any("rows", data[2]))
  135. case 4:
  136. global.GVA_LOG.Info("gorm", zap.Any("src", data[0]), zap.Any("duration", data[1]), zap.Any("rows", data[2]), zap.Any("sql", data[3]))
  137. }
  138. return
  139. }
  140. switch len(data) {
  141. case 0:
  142. g.gormWriter.Printf(message, "")
  143. case 1:
  144. g.gormWriter.Printf(message, data[0].(string))
  145. case 2:
  146. g.gormWriter.Printf(message, data[0].(string), data[1].(float64))
  147. case 3:
  148. g.gormWriter.Printf(message, data[0].(string), data[1].(float64), data[2].(string))
  149. case 4:
  150. g.gormWriter.Printf(message, data[0].(string), data[1].(float64), data[2].(string), data[3].(string))
  151. }
  152. }