This repository has been archived by the owner on Jun 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorm.go
103 lines (91 loc) · 2.54 KB
/
gorm.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
92
93
94
95
96
97
98
99
100
101
102
103
//go:build bd_all || bd_gorm || gorm
package blackdatura
import (
"context"
"errors"
"strconv"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"gorm.io/gorm"
gl "gorm.io/gorm/logger"
)
type GormLogger struct {
log *zap.Logger
Level zapcore.Level
SlowThreshold time.Duration
SkipCallerLookup bool
IgnoreRecordNotFoundError bool
}
func Gorm(l *zap.Logger) *GormLogger {
return &GormLogger{
log: l,
Level: zap.WarnLevel,
SlowThreshold: 100 * time.Millisecond,
SkipCallerLookup: false,
IgnoreRecordNotFoundError: false,
}
}
func (l *GormLogger) LogMode(level gl.LogLevel) gl.Interface {
newLog := &GormLogger{
log: l.log,
Level: zap.DPanicLevel,
SlowThreshold: l.SlowThreshold,
SkipCallerLookup: l.SkipCallerLookup,
IgnoreRecordNotFoundError: l.IgnoreRecordNotFoundError,
}
switch level {
case gl.Error:
newLog.Level = zap.ErrorLevel
case gl.Warn:
newLog.Level = zap.WarnLevel
case gl.Info:
newLog.Level = zap.InfoLevel
}
return newLog
}
func (l *GormLogger) Info(_ context.Context, str string, args ...interface{}) {
if l.Level >= zap.InfoLevel {
l.log.Info(str, arg2ZapField(args)...)
}
}
func (l *GormLogger) Warn(_ context.Context, str string, args ...interface{}) {
if l.Level >= zap.WarnLevel {
l.log.Warn(str, arg2ZapField(args)...)
}
}
func (l *GormLogger) Error(_ context.Context, str string, args ...interface{}) {
if l.Level >= zap.ErrorLevel {
l.log.Error(str, arg2ZapField(args)...)
}
}
func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
sql, rows := fc()
elapsed := time.Since(begin)
switch {
case err != nil && l.Level >= zap.ErrorLevel &&
(!l.IgnoreRecordNotFoundError || !errors.Is(err, gorm.ErrRecordNotFound)):
l.log.Error("trace",
zap.Error(err),
zap.Duration("elapsed", elapsed),
zap.Int64("rows", rows),
zap.String("sql", sql))
case elapsed > l.SlowThreshold && l.SlowThreshold != 0 && l.Level >= zap.WarnLevel:
l.log.Warn("trace",
zap.Duration("elapsed", elapsed),
zap.Int64("rows", rows),
zap.String("sql", sql))
case l.Level == zap.InfoLevel:
l.log.Info("trace",
zap.Duration("elapsed", elapsed),
zap.Int64("rows", rows),
zap.String("sql", sql))
}
}
func arg2ZapField(args []interface{}) []zap.Field {
arr := make([]zap.Field, len(args))
for i, v := range args {
arr[i] = zap.Any(strconv.Itoa(i), v)
}
return arr
}