forked from oiime/logrusbun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogrusbun.go
162 lines (144 loc) · 3.45 KB
/
logrusbun.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package logrusbun
import (
"bytes"
"context"
"database/sql"
"fmt"
"text/template"
"time"
"github.com/sirupsen/logrus"
"github.com/uptrace/bun"
)
// QueryHookOptions logging options
type QueryHookOptions struct {
LogSlow time.Duration
Logger logrus.FieldLogger
QueryLevel logrus.Level
SlowLevel logrus.Level
ErrorLevel logrus.Level
MessageTemplate string
ErrorTemplate string
}
// QueryHook wraps query hook
type QueryHook struct {
opts QueryHookOptions
errorTemplate *template.Template
messageTemplate *template.Template
}
// LogEntryVars variables made available t otemplate
type LogEntryVars struct {
Timestamp time.Time
Query string
Operation string
Duration time.Duration
Error error
}
// NewQueryHook returns new instance
func NewQueryHook(opts QueryHookOptions) *QueryHook {
h := new(QueryHook)
if opts.ErrorTemplate == "" {
opts.ErrorTemplate = "{{.Operation}}[{{.Duration}}]: {{.Query}}: {{.Error}}"
}
if opts.MessageTemplate == "" {
opts.MessageTemplate = "{{.Operation}}[{{.Duration}}]: {{.Query}}"
}
h.opts = opts
errorTemplate, err := template.New("ErrorTemplate").Parse(h.opts.ErrorTemplate)
if err != nil {
panic(err)
}
messageTemplate, err := template.New("MessageTemplate").Parse(h.opts.MessageTemplate)
if err != nil {
panic(err)
}
h.errorTemplate = errorTemplate
h.messageTemplate = messageTemplate
return h
}
// BeforeQuery does nothing tbh
func (h *QueryHook) BeforeQuery(ctx context.Context, event *bun.QueryEvent) context.Context {
return ctx
}
// AfterQuery convert a bun QueryEvent into a logrus message
func (h *QueryHook) AfterQuery(ctx context.Context, event *bun.QueryEvent) {
var level logrus.Level
var isError bool
var msg bytes.Buffer
now := time.Now()
dur := now.Sub(event.StartTime)
switch event.Err {
case nil, sql.ErrNoRows:
isError = false
if h.opts.LogSlow > 0 && dur >= h.opts.LogSlow {
level = h.opts.SlowLevel
} else {
level = h.opts.QueryLevel
}
default:
isError = true
level = h.opts.ErrorLevel
}
if level == 0 {
return
}
args := &LogEntryVars{
Timestamp: now,
Query: string(event.Query),
Operation: eventOperation(event),
Duration: dur,
Error: event.Err,
}
if isError {
if err := h.errorTemplate.Execute(&msg, args); err != nil {
panic(err)
}
} else {
if err := h.messageTemplate.Execute(&msg, args); err != nil {
panic(err)
}
}
switch level {
case logrus.DebugLevel:
h.opts.Logger.Debug(msg.String())
case logrus.InfoLevel:
h.opts.Logger.Info(msg.String())
case logrus.WarnLevel:
h.opts.Logger.Warn(msg.String())
case logrus.ErrorLevel:
h.opts.Logger.Error(msg.String())
case logrus.FatalLevel:
h.opts.Logger.Fatal(msg.String())
case logrus.PanicLevel:
h.opts.Logger.Panic(msg.String())
default:
panic(fmt.Errorf("Unsupported level: %v", level))
}
}
// taken from bun
func eventOperation(event *bun.QueryEvent) string {
switch event.QueryAppender.(type) {
case *bun.SelectQuery:
return "SELECT"
case *bun.InsertQuery:
return "INSERT"
case *bun.UpdateQuery:
return "UPDATE"
case *bun.DeleteQuery:
return "DELETE"
case *bun.CreateTableQuery:
return "CREATE TABLE"
case *bun.DropTableQuery:
return "DROP TABLE"
}
return queryOperation([]byte(event.Query))
}
// taken from bun
func queryOperation(name []byte) string {
if idx := bytes.IndexByte(name, ' '); idx > 0 {
name = name[:idx]
}
if len(name) > 16 {
name = name[:16]
}
return string(name)
}