/
hooks.go
43 lines (37 loc) · 943 Bytes
/
hooks.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
package postgres
import (
"context"
"github.com/tron-us/go-common/v2/log"
"github.com/go-pg/pg/v9"
"go.uber.org/zap"
)
type dbQueryLoggerHook struct {
beforeEnabled bool
afterEnabled bool
}
func (d dbQueryLoggerHook) BeforeQuery(ctx context.Context, q *pg.QueryEvent) (context.Context, error) {
if !d.beforeEnabled {
return ctx, nil
}
qs, err := q.FormattedQuery()
if err != nil {
log.HandlerDebug(ctx, "BeforeQueryLog: Unable to log raw query")
return ctx, err
} else {
log.HandlerDebug(ctx, "BeforeQueryLog: Raw query", zap.String("q", qs))
return ctx, nil
}
}
func (d dbQueryLoggerHook) AfterQuery(ctx context.Context, q *pg.QueryEvent) error {
if !d.afterEnabled {
return nil
}
qs, err := q.FormattedQuery()
if err != nil {
log.HandlerDebug(ctx, "AfterQueryLog: Unable to log raw query")
return err
} else {
log.HandlerDebug(ctx, "AfterQueryLog: Raw query", zap.String("q", qs))
return nil
}
}