/
gormzap.go
208 lines (177 loc) · 4.96 KB
/
gormzap.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
// Package gormzap provides gorm logger implementation using Uber's zap logger.
//
// Example usage:
// orm, _ := gorm.Open("postgres", dsn)
// orm.LogMode(true)
// orm.SetLogger(gormzap.New(log, gormzap.WithLevel(zap.InfoLevel))
package gormzap
import (
"database/sql/driver"
"fmt"
"reflect"
"strings"
"time"
"unicode"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Logger is a gorm logger implementation using zap.
type Logger struct {
origin *zap.Logger
level zapcore.Level
encoderFunc RecordToFields
}
// LoggerOption is an option for Logger.
type LoggerOption func(*Logger)
// WithLevel returns Logger option that sets level for gorm logs.
// It affects only general logs, e.g. those that contain SQL queries.
// Errors will be logged with error level independently of this option.
func WithLevel(level zapcore.Level) LoggerOption {
return func(l *Logger) {
l.level = level
}
}
// WithRecordToFields returns Logger option that sets RecordToFields func which
// encodes log Record to a slice of zap fields.
//
// This can be used to control field names or field values types.
func WithRecordToFields(f RecordToFields) LoggerOption {
return func(l *Logger) {
l.encoderFunc = f
}
}
// New returns a new gorm logger implemented using zap.
// By default it logs with debug level.
func New(origin *zap.Logger, opts ...LoggerOption) *Logger {
l := &Logger{
origin: origin,
level: zap.DebugLevel,
encoderFunc: DefaultRecordToFields,
}
for _, o := range opts {
o(l)
}
return l
}
// Print implements gorm's logger interface.
func (l *Logger) Print(values ...interface{}) {
rec := l.newRecord(values...)
l.origin.Check(rec.Level, rec.Message).Write(l.encoderFunc(rec)...)
}
func (l *Logger) newRecord(values ...interface{}) Record {
// See https://github.com/jinzhu/gorm/blob/master/main.go#L774
// for info how gorm logs messages.
if len(values) < 2 {
// Should this ever happen?
return Record{
Message: fmt.Sprint(values...),
Level: l.level,
}
}
// Handle https://github.com/jinzhu/gorm/blob/32455088f24d6b1e9a502fb8e40fdc16139dbea8/main.go#L716
if len(values) == 2 {
return Record{
Message: fmt.Sprintf("%v", values[1]),
Source: fmt.Sprintf("%v", values[0]),
Level: zapcore.ErrorLevel,
}
}
level := values[0]
// Handle https://github.com/jinzhu/gorm/blob/32455088f24d6b1e9a502fb8e40fdc16139dbea8/main.go#L778
if level == "log" {
// By default, assume this is a user log.
// See: https://github.com/jinzhu/gorm/blob/32455088f24d6b1e9a502fb8e40fdc16139dbea8/scope.go#L96
// If this is an error log, we set level to error.
// See: https://github.com/jinzhu/gorm/blob/32455088f24d6b1e9a502fb8e40fdc16139dbea8/main.go#L718
logLevel := l.level
if _, ok := values[2].(error); ok {
logLevel = zapcore.ErrorLevel
}
return Record{
Message: fmt.Sprint(values[2:]...),
Source: fmt.Sprintf("%v", values[1]),
Level: logLevel,
}
}
// Handle https://github.com/jinzhu/gorm/blob/32455088f24d6b1e9a502fb8e40fdc16139dbea8/main.go#L786
if level == "sql" {
return Record{
Message: "gorm query",
Source: fmt.Sprintf("%v", values[1]),
Duration: values[2].(time.Duration),
SQL: formatSQL(values[3].(string), values[4].([]interface{})),
RowsAffected: values[5].(int64),
Level: l.level,
}
}
// Should this ever happen?
return Record{
Message: fmt.Sprint(values[2:]...),
Source: fmt.Sprintf("%v", values[1]),
Level: l.level,
}
}
func formatSQL(sql string, values []interface{}) string {
size := len(values)
replacements := make([]string, size*2)
var indexFunc func(int) string
if strings.Contains(sql, "$1") {
indexFunc = formatNumbered
} else {
indexFunc = formatQuestioned
}
for i := size - 1; i >= 0; i-- {
replacements[(size-i-1)*2] = indexFunc(i)
replacements[(size-i-1)*2+1] = formatValue(values[i])
}
r := strings.NewReplacer(replacements...)
return r.Replace(sql)
}
func formatNumbered(index int) string {
return fmt.Sprintf("$%d", index+1)
}
func formatQuestioned(index int) string {
return "?"
}
func formatValue(value interface{}) string {
indirectValue := reflect.Indirect(reflect.ValueOf(value))
if !indirectValue.IsValid() {
return "NULL"
}
value = indirectValue.Interface()
switch v := value.(type) {
case time.Time:
return fmt.Sprintf("'%v'", v.Format("2006-01-02 15:04:05"))
case []byte:
s := string(v)
if isPrintable(s) {
return redactLong(fmt.Sprintf("'%s'", s))
}
return "'<binary>'"
case int, int8, int16, int32, int64,
uint, uint8, uint16, uint32, uint64:
return fmt.Sprintf("%d", v)
case driver.Valuer:
if dv, err := v.Value(); err == nil && dv != nil {
return formatValue(dv)
}
return "NULL"
default:
return redactLong(fmt.Sprintf("'%v'", value))
}
}
func isPrintable(s string) bool {
for _, r := range s {
if !unicode.IsPrint(r) {
return false
}
}
return true
}
func redactLong(s string) string {
if len(s) > maxLen {
return "'<redacted>'"
}
return s
}
const maxLen = 255