-
Notifications
You must be signed in to change notification settings - Fork 73
/
logger.go
99 lines (82 loc) · 2.1 KB
/
logger.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package reform
import (
"fmt"
"reflect"
"strings"
"time"
)
// Inspect returns suitable for logging representation of a query argument.
func Inspect(arg interface{}, addType bool) string {
var s string
v := reflect.ValueOf(arg)
switch v.Kind() {
case reflect.Ptr:
if v.IsNil() {
s = "<nil>"
} else {
s = Inspect(v.Elem().Interface(), false)
}
case reflect.String:
s = fmt.Sprintf("%#q", arg)
default:
s = fmt.Sprintf("%v", arg)
}
if addType {
s += fmt.Sprintf(" (%T)", arg)
}
return s
}
// Logger is responsible to log queries before and after their execution.
type Logger interface {
// Before logs query before execution.
Before(query string, args []interface{})
// After logs query after execution.
After(query string, args []interface{}, d time.Duration, err error)
}
// Printf is a (fmt.Printf|log.Printf|testing.T.Logf)-like function.
type Printf func(format string, args ...interface{})
// PrintfLogger is a simple query logger.
type PrintfLogger struct {
LogTypes bool
printf Printf
}
// NewPrintfLogger creates a new simple query logger for any Printf-like function.
func NewPrintfLogger(printf Printf) *PrintfLogger {
return &PrintfLogger{false, printf}
}
// Before logs query before execution.
func (pl *PrintfLogger) Before(query string, args []interface{}) {
// fast path
if args == nil {
pl.printf(">>> %s", query)
return
}
ss := make([]string, len(args))
for i, arg := range args {
ss[i] = Inspect(arg, pl.LogTypes)
}
pl.printf(">>> %s [%s]", query, strings.Join(ss, ", "))
}
// After logs query after execution.
func (pl *PrintfLogger) After(query string, args []interface{}, d time.Duration, err error) {
// fast path
if args == nil {
msg := fmt.Sprintf("%s %s", query, d)
if err != nil {
msg += ": " + err.Error()
}
pl.printf("<<< %s", msg)
return
}
ss := make([]string, len(args))
for i, arg := range args {
ss[i] = Inspect(arg, pl.LogTypes)
}
msg := fmt.Sprintf("%s [%s] %s", query, strings.Join(ss, ", "), d)
if err != nil {
msg += ": " + err.Error()
}
pl.printf("<<< %s", msg)
}
// check interface
var _ Logger = (*PrintfLogger)(nil)