-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzerobun.go
65 lines (51 loc) · 1.44 KB
/
zerobun.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
package zerobun
import (
"context"
"time"
"github.com/rs/zerolog"
"github.com/uptrace/bun"
)
const (
BunInfoFieldName = "bun_info"
OperationFieldName = "operation"
OperationQueryName = "query"
OperationTimeFieldName = "operation_time_ms"
)
type QueryHook struct {
bun.QueryHook
logger *zerolog.Logger
slowDuration time.Duration
}
type QueryHookOptions struct {
Logger *zerolog.Logger
SlowDuration time.Duration
}
// NewQueryHook returns a new bun.QueryHook that outputs database transactions using an instance of zerolog.Logger
func NewQueryHook(options QueryHookOptions) QueryHook {
return QueryHook{
logger: options.Logger,
slowDuration: options.SlowDuration,
}
}
// BeforeQuery called before a database transaction but currently does nothing
func (qh QueryHook) BeforeQuery(ctx context.Context, _ *bun.QueryEvent) context.Context {
return ctx
}
// AfterQuery logs an entry after a database transaction
func (qh QueryHook) AfterQuery(_ context.Context, event *bun.QueryEvent) {
queryDuration := time.Since(event.StartTime)
fields := map[string]interface{}{
OperationQueryName: event.Query,
OperationFieldName: event.Operation(),
OperationTimeFieldName: queryDuration.Milliseconds(),
}
bunLogger := qh.logger.With().Dict(
BunInfoFieldName,
zerolog.Dict().Fields(fields),
).Logger()
if event.Err != nil {
bunLogger.Error().Err(event.Err).Msg("")
return
}
bunLogger.Debug().Msg("")
}