-
Notifications
You must be signed in to change notification settings - Fork 1
/
gorm.go
75 lines (62 loc) · 1.84 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
package echotool
import (
"context"
"time"
"gorm.io/gorm"
gl "gorm.io/gorm/logger"
)
type GORMLogger struct {
Prefix string
SlowTime time.Duration
IgnoreNoRecord bool
}
var _ gl.Interface = (*GORMLogger)(nil)
func NewDefaultGORMLogger() *GORMLogger {
return &GORMLogger{
Prefix: "[gorm]",
SlowTime: time.Millisecond * 200,
IgnoreNoRecord: true,
}
}
func (l *GORMLogger) LogMode(level gl.LogLevel) gl.Interface {
return l
}
func (l *GORMLogger) Info(ctx context.Context, format string, args ...interface{}) {
ec, _ := ctx.(*Context)
CtxInfo(ec, l.addPrefix(format), args...)
}
func (l *GORMLogger) Warn(ctx context.Context, format string, args ...interface{}) {
ec, _ := ctx.(*Context)
CtxWarn(ec, l.addPrefix(format), args...)
}
func (l *GORMLogger) Error(ctx context.Context, format string, args ...interface{}) {
ec, _ := ctx.(*Context)
CtxError(ec, l.addPrefix(format), args...)
}
func (l *GORMLogger) Trace(ctx context.Context, begin time.Time, f func() (string, int64), err error) {
tns := time.Since(begin)
tms := float64(tns.Nanoseconds()) / 1e6
sql, rows := f()
switch {
case err != nil && (err != gorm.ErrRecordNotFound || !l.IgnoreNoRecord):
l.Error(ctx, "[%.3fms] [rows:%d] %s - %v", tms, rows, sql, err)
case l.SlowTime > 0 && tns > l.SlowTime:
l.Warn(ctx, "[%.3fms] [rows:%d] %s - slow sql > %v", tms, rows, sql, l.SlowTime)
default:
l.Info(ctx, "[%.3fms] [rows:%d] %s", tms, rows, sql)
}
}
func (l *GORMLogger) addPrefix(msg string) string {
return l.Prefix + " " + msg
}
// NewDefaultGORMConfig returns a default config with logger.
// Note that you should set PrepareStmt to false when using clickhouse.
func NewDefaultGORMConfig(isCached bool) *gorm.Config {
return &gorm.Config{
PrepareStmt: isCached,
Logger: NewDefaultGORMLogger(),
}
}
func AutoIncrID(id *int64) {
*id = 0
}