dbLog.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package hook
  2. import (
  3. "context"
  4. "time"
  5. "go.uber.org/zap"
  6. "gorm.io/gorm/logger"
  7. )
  8. type CustomLogger struct {
  9. *zap.Logger
  10. }
  11. // LogMode 设置日志级别
  12. func (cl *CustomLogger) LogMode(level logger.LogLevel) logger.Interface {
  13. return cl
  14. }
  15. // Info 记录信息
  16. func (cl *CustomLogger) Info(ctx context.Context, msg string, data ...interface{}) {
  17. cl.Logger.Info(msg, zap.Any("data", data))
  18. }
  19. // Warn 记录警告
  20. func (cl *CustomLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
  21. cl.Logger.Warn(msg, zap.Any("data", data))
  22. }
  23. // Error 记录错误
  24. func (cl *CustomLogger) Error(ctx context.Context, msg string, data ...interface{}) {
  25. cl.Logger.Error(msg, zap.Any("data", data))
  26. }
  27. // Trace 记录跟踪信
  28. func (cl *CustomLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
  29. elapsed := time.Since(begin)
  30. sql, rows := fc() // Assign the returned values to variables
  31. fields := []zap.Field{
  32. zap.String("sql", sql),
  33. zap.Int64("rows", rows),
  34. zap.Error(err),
  35. zap.Duration("took", elapsed),
  36. }
  37. if err != nil {
  38. cl.Logger.Error("sql:", fields...)
  39. } else if elapsed > 1*time.Second {
  40. cl.Logger.Warn("sql:", fields...)
  41. } else {
  42. // cl.Logger.Info("sql:", fields...)
  43. }
  44. }