/
logger.go
193 lines (160 loc) · 4.5 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
package zerologgorm
import (
"context"
"errors"
"fmt"
"github.com/rs/zerolog"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/utils"
"time"
)
type GormLogger struct {
// SlowThreshold is the delay which define the query as slow
SlowThreshold time.Duration
// IgnoreRecordNotFoundError is to ignore when the record is not found
IgnoreRecordNotFoundError bool
// FieldsOrder defines the order of fields in output.
FieldsOrder []string
// FieldsExclude defines contextual fields to not display in output.
FieldsExclude []string
}
var (
// TimestampFieldName is the field name used for the timestamp field.
TimestampFieldName = zerolog.TimestampFieldName
// DurationFieldName is the field name used for the duration field.
DurationFieldName = "elapsed"
// FileFieldName is the field name used for the file field.
FileFieldName = "file"
// SqlFieldName is the field name used for the sql field.
SqlFieldName = "sql"
// RowsFieldName is the field name used for the rows field.
RowsFieldName = "rows"
)
// GormLogger implements the logger.Interface
var _ logger.Interface = &GormLogger{}
// NewGormLogger creates and initializes a new GormLogger.
func NewGormLogger() *GormLogger {
l := &GormLogger{
FieldsOrder: gormDefaultFieldsOrder(),
}
return l
}
// gormDefaultFieldsOrder defines the default order of fields
func gormDefaultFieldsOrder() []string {
return []string{
TimestampFieldName,
DurationFieldName,
FileFieldName,
SqlFieldName,
RowsFieldName,
}
}
// isExcluded check if a field is excluded from the output
func (l GormLogger) isExcluded(field string) bool {
if l.FieldsExclude == nil {
return false
}
for _, f := range l.FieldsExclude {
if f == field {
return true
}
}
return false
}
// LogMode log mode
func (l *GormLogger) LogMode(level logger.LogLevel) logger.Interface {
return l
}
// Info print info
func (l GormLogger) Info(ctx context.Context, msg string, data ...interface{}) {
zerolog.Ctx(ctx).Info().Msg(fmt.Sprintf(msg, data...))
}
// Warn print warn messages
func (l GormLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
zerolog.Ctx(ctx).Warn().Msg(fmt.Sprintf(msg, data...))
}
// Error print error messages
func (l GormLogger) Error(ctx context.Context, msg string, data ...interface{}) {
zerolog.Ctx(ctx).Error().Msg(fmt.Sprintf(msg, data...))
}
// Trace print sql message
func (l GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
// get zerolog from context
z := zerolog.Ctx(ctx)
// return if zerolog is disabled
if z.GetLevel() == zerolog.Disabled {
return
}
if l.FieldsOrder == nil {
l.FieldsOrder = gormDefaultFieldsOrder()
}
elapsed := time.Since(begin)
sql, rows := fc()
var event *zerolog.Event
var eventError bool
var eventWarn bool
// set message level
if err != nil && !(l.IgnoreRecordNotFoundError && errors.Is(err, gorm.ErrRecordNotFound)) {
eventError = true
event = z.Error()
} else if l.SlowThreshold != 0 && elapsed > l.SlowThreshold {
eventWarn = true
event = z.Warn()
} else {
event = z.Trace()
}
// add fields
for _, f := range l.FieldsOrder {
// add time field
if f == TimestampFieldName && !l.isExcluded(f) {
event.Time(TimestampFieldName, begin)
}
// add duration field
if f == DurationFieldName && !l.isExcluded(f) {
var durationFieldName string
switch zerolog.DurationFieldUnit {
case time.Nanosecond:
durationFieldName = DurationFieldName + "_ns"
case time.Microsecond:
durationFieldName = DurationFieldName + "_us"
case time.Millisecond:
durationFieldName = DurationFieldName + "_ms"
case time.Second:
durationFieldName = DurationFieldName
case time.Minute:
durationFieldName = DurationFieldName + "_min"
case time.Hour:
durationFieldName = DurationFieldName + "_hr"
default:
z.Error().Interface("zerolog.DurationFieldUnit", zerolog.DurationFieldUnit).Msg("unknown value for DurationFieldUnit")
durationFieldName = DurationFieldName
}
event.Dur(durationFieldName, elapsed)
}
// add file field
if f == FileFieldName && !l.isExcluded(f) {
event.Str("file", utils.FileWithLineNum())
}
// add sql field
if f == SqlFieldName && !l.isExcluded(f) {
if sql != "" {
event.Str("sql", sql)
}
}
// add rows field
if f == RowsFieldName && !l.isExcluded(f) {
if rows > -1 {
event.Int64("rows", rows)
}
}
}
// post the message
if eventError {
event.Msg("SQL error")
} else if eventWarn {
event.Msg("SQL slow query")
} else {
event.Msg("SQL")
}
}