github.com/siglens/siglens@v0.0.0-20240328180423-f7ce9ae441ed/pkg/alerts/alertutils/logger.go (about) 1 package alertutils 2 3 import ( 4 "context" 5 "time" 6 7 "github.com/sirupsen/logrus" 8 "gorm.io/gorm" 9 "gorm.io/gorm/logger" 10 ) 11 12 // NewGormLogrusLogger returns a new gorm/logger.Interface compliant logger that uses logrus for the actual logging 13 func NewGormLogrusLogger(logger *logrus.Entry, slowLogThreshold time.Duration) logger.Interface { 14 return &gormLogger{ 15 entry: logger, 16 slowLogThreshold: slowLogThreshold, 17 } 18 } 19 20 var _ logger.Interface = &gormLogger{} 21 22 type gormLogger struct { 23 entry *logrus.Entry 24 slowLogThreshold time.Duration 25 } 26 27 func (g *gormLogger) LogMode(level logger.LogLevel) logger.Interface { 28 return g 29 } 30 31 func (g *gormLogger) Info(_ context.Context, msg string, data ...interface{}) { 32 g.entry.Info(msg, data) 33 } 34 35 func (g *gormLogger) Warn(_ context.Context, msg string, data ...interface{}) { 36 g.entry.Warn(msg, data) 37 } 38 39 func (g *gormLogger) Error(_ context.Context, msg string, data ...interface{}) { 40 g.entry.Error(msg, data) 41 } 42 43 func (g *gormLogger) Trace(_ context.Context, begin time.Time, fc func() (string, int64), err error) { 44 elapsed := time.Since(begin) 45 sql, rows := fc() 46 duration := float64(elapsed.Nanoseconds()) / 1e6 47 48 switch { 49 case err != nil: 50 // record not found is an expected error and thus not logged 51 if err == gorm.ErrRecordNotFound { 52 return 53 } 54 55 g.entry.WithFields(logrus.Fields{ 56 "error": err, 57 "rows": rows, 58 "duration": duration, 59 }).Warn(sql) 60 61 case elapsed > g.slowLogThreshold: 62 g.entry.WithFields(logrus.Fields{ 63 "rows": rows, 64 "duration": duration, 65 }).Warn(sql) 66 67 default: 68 g.entry.WithFields(logrus.Fields{ 69 "rows": rows, 70 "duration": duration, 71 // "file": utils.FileWithLineNum(), 72 }).Debug(sql) 73 } 74 }