forked from onrik/gorm-logrus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
61 lines (50 loc) · 1.43 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
package gorm_logrus
import (
"context"
"errors"
"time"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
gormlogger "gorm.io/gorm/logger"
"gorm.io/gorm/utils"
)
type logger struct {
SlowThreshold time.Duration
SourceField string
SkipErrRecordNotFound bool
}
func New() *logger {
return &logger{
SkipErrRecordNotFound: true,
}
}
func (l *logger) LogMode(gormlogger.LogLevel) gormlogger.Interface {
return l
}
func (l *logger) Info(ctx context.Context, s string, args ...interface{}) {
log.WithContext(ctx).Infof(s, args)
}
func (l *logger) Warn(ctx context.Context, s string, args ...interface{}) {
log.WithContext(ctx).Warnf(s, args)
}
func (l *logger) Error(ctx context.Context, s string, args ...interface{}) {
log.WithContext(ctx).Errorf(s, args)
}
func (l *logger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
elapsed := time.Since(begin)
sql, _ := fc()
fields := log.Fields{}
if l.SourceField != "" {
fields[l.SourceField] = utils.FileWithLineNum()
}
if err != nil && !(errors.Is(err, gorm.ErrRecordNotFound) && l.SkipErrRecordNotFound) {
fields[log.ErrorKey] = err
log.WithContext(ctx).WithFields(fields).Errorf("%s [%s]", sql, elapsed)
return
}
if l.SlowThreshold != 0 && elapsed > l.SlowThreshold {
log.WithContext(ctx).WithFields(fields).Warnf("%s [%s]", sql, elapsed)
return
}
log.WithContext(ctx).WithFields(fields).Debugf("%s [%s]", sql, elapsed)
}