forked from onrik/gorm-logrus
-
Notifications
You must be signed in to change notification settings - Fork 1
/
logger.go
91 lines (75 loc) · 2.2 KB
/
logger.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package gormloggerlogrus
import (
"context"
"errors"
"time"
"github.com/sirupsen/logrus"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"gorm.io/gorm/utils"
)
type Options struct {
Logger *logrus.Entry
LogLevel gormlogger.LogLevel
IgnoreRecordNotFoundError bool
SlowThreshold time.Duration
FileWithLineNumField string
}
type Logger struct {
Options
}
func New(opts Options) *Logger {
l := &Logger{Options: opts}
if l.Logger == nil {
l.Logger = logrus.NewEntry(logrus.New())
}
if l.LogLevel == 0 {
l.LogLevel = gormlogger.Silent
}
return l
}
func (l *Logger) LogMode(level gormlogger.LogLevel) gormlogger.Interface {
newlogger := *l
newlogger.LogLevel = level
return &newlogger
}
func (l *Logger) Info(ctx context.Context, s string, args ...interface{}) {
if l.LogLevel >= gormlogger.Info {
l.Logger.WithContext(ctx).Infof(s, args...)
}
}
func (l *Logger) Warn(ctx context.Context, s string, args ...interface{}) {
if l.LogLevel >= gormlogger.Warn {
l.Logger.WithContext(ctx).Warnf(s, args...)
}
}
func (l *Logger) Error(ctx context.Context, s string, args ...interface{}) {
if l.LogLevel >= gormlogger.Error {
l.Logger.WithContext(ctx).Errorf(s, args...)
}
}
func (l *Logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
if l.LogLevel <= gormlogger.Silent {
return
}
fields := logrus.Fields{}
if l.FileWithLineNumField != "" {
fields[l.FileWithLineNumField] = utils.FileWithLineNum()
}
sql, rows := fc()
if rows == -1 {
fields["rows_affected"] = "-"
} else {
fields["rows_affected"] = rows
}
elapsed := time.Since(begin)
fields["elapsed"] = elapsed
switch {
case err != nil && (!errors.Is(err, gorm.ErrRecordNotFound) || !l.IgnoreRecordNotFoundError) && l.LogLevel >= gormlogger.Error:
l.Logger.WithContext(ctx).WithFields(fields).Errorf("%s [%s]", sql, elapsed)
case l.SlowThreshold != 0 && elapsed > l.SlowThreshold && l.LogLevel >= gormlogger.Warn:
l.Logger.WithContext(ctx).WithFields(fields).Warnf("SLOW SQL >= %v, l.SlowThreshold %s [%s]", l.SlowThreshold, sql, elapsed)
case l.LogLevel == gormlogger.Info:
l.Logger.WithContext(ctx).WithFields(fields).Infof("%s [%s]", sql, elapsed)
}
}