-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdebug.go
54 lines (46 loc) · 1.3 KB
/
debug.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
package lorm
import (
"fmt"
"path"
"runtime"
"sync/atomic"
"time"
"github.com/tada-team/lorm/op"
)
type (
beforeQueryHandler func(tx *Tx, qNum int64, q string, v op.Args)
afterQueryHandler func(tx *Tx, qNum int64, q string, v op.Args, dur time.Duration)
cacheUsedHandler func(name string)
)
var (
qNum int64
beforeQueryHandlers []beforeQueryHandler
afterQueryHandlers []afterQueryHandler
cacheUsedHandlers []cacheUsedHandler
)
func QueryCounter() int64 { return atomic.LoadInt64(&qNum) }
func BeforeQuery(fn beforeQueryHandler) { beforeQueryHandlers = append(beforeQueryHandlers, fn) }
func AfterQuery(fn afterQueryHandler) { afterQueryHandlers = append(afterQueryHandlers, fn) }
func OnCacheUsed(fn cacheUsedHandler) { cacheUsedHandlers = append(cacheUsedHandlers, fn) }
func CacheUsed(name string) {
for _, fn := range cacheUsedHandlers {
fn(name)
}
}
func trackQuery(tx *Tx, q string, v op.Args) func() {
num := atomic.AddInt64(&qNum, 1)
for _, fn := range beforeQueryHandlers {
fn(tx, num, q, v)
}
start := time.Now()
return func() {
dur := time.Since(start)
for _, fn := range afterQueryHandlers {
fn(tx, num, q, v, dur)
}
}
}
func breadcrumb() string {
_, file, no, _ := runtime.Caller(2)
return fmt.Sprintf("%s:%d", path.Base(file), no)
}