-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbunzap.go
69 lines (58 loc) · 1.48 KB
/
bunzap.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
package bunzap
import (
"context"
"time"
"github.com/uptrace/bun"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// Field names
const (
OperationFieldName = "operation"
OperationTimeFieldName = "operation_time_ms"
)
// QueryHook defines the
// structure of our query hook
// it implements the bun.QueryHook
// interface
type QueryHook struct {
bun.QueryHook
logger *zap.Logger
slowDuration time.Duration
}
// QueryHookOptions defines the
// available options for a new
// query hook.
type QueryHookOptions struct {
Logger *zap.Logger
SlowDuration time.Duration
}
// NewQueryHook returns a new query hook for use with
// uptrace/bun.
func NewQueryHook(options QueryHookOptions) QueryHook {
return QueryHook{
logger: options.Logger,
slowDuration: options.SlowDuration,
}
}
func (qh QueryHook) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context {
return ctx
}
func (qh QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) {
queryDuration := time.Since(event.StartTime)
fields := []zapcore.Field{
zap.String(OperationFieldName, event.Operation()),
zap.Int64(OperationTimeFieldName, queryDuration.Milliseconds()),
}
// Errors will always be logged
if event.Err != nil {
fields = append(fields, zap.Error(event.Err))
qh.logger.Error(event.Query, fields...)
return
}
// Queries over a slow time duration
// will be logged as debug
if queryDuration >= qh.slowDuration {
qh.logger.Debug(event.Query, fields...)
}
}