-
Notifications
You must be signed in to change notification settings - Fork 0
/
log.go
62 lines (53 loc) · 1.19 KB
/
log.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
package db
import (
"context"
"time"
"github.com/msw-x/moon/ulog"
"github.com/msw-x/moon/utime"
"github.com/uptrace/bun"
)
type log struct {
log *ulog.Log
onlyErrors bool
longQueriesTime time.Duration
warnLongQueries bool
}
func newLog(ul *ulog.Log, onlyErrors bool) *log {
return &log{
log: ul,
onlyErrors: onlyErrors,
}
}
func (o *log) WithQueriesTime(t time.Duration, warn bool) *log {
o.longQueriesTime = t
o.warnLongQueries = warn
return o
}
func (o *log) Printf(format string, v ...any) {
o.log.Infof(format, v...)
}
func (o *log) BeforeQuery(c context.Context, q *bun.QueryEvent) context.Context {
return c
}
func (o *log) AfterQuery(c context.Context, q *bun.QueryEvent) {
if q.Err == nil {
if o.longQueriesTime == 0 {
if !o.onlyErrors {
o.log.Debug(queryTime(q), q.Query)
}
} else {
if time.Since(q.StartTime) > o.longQueriesTime {
if o.warnLongQueries {
o.log.Warning(queryTime(q), q.Query)
} else {
o.log.Debug(queryTime(q), q.Query)
}
}
}
} else {
o.log.Error(queryTime(q), q.Query, q.Err)
}
}
func queryTime(q *bun.QueryEvent) time.Duration {
return utime.PrettyTruncate(time.Since(q.StartTime))
}