-
Notifications
You must be signed in to change notification settings - Fork 5
/
logrusbun.go
229 lines (203 loc) · 4.78 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package logrusbun
import (
"bytes"
"context"
"database/sql"
"fmt"
"os"
"strings"
"text/template"
"time"
"github.com/sirupsen/logrus"
"github.com/uptrace/bun"
)
type Option func(hook *QueryHook)
// WithEnabled enables/disables this hook
func WithEnabled(on bool) Option {
return func(h *QueryHook) {
h.enabled = on
}
}
// WithVerbose configures the hook to log all queries
// (by default, only failed queries are logged)
func WithVerbose(on bool) Option {
return func(h *QueryHook) {
h.verbose = on
}
}
// FromEnv configures the hook using the environment variable value.
// For example, WithEnv("BUNDEBUG"):
// - BUNDEBUG=0 - disables the hook.
// - BUNDEBUG=1 - enables the hook.
// - BUNDEBUG=2 - enables the hook and verbose mode.
func FromEnv(keys ...string) Option {
if len(keys) == 0 {
keys = []string{"BUNDEBUG"}
}
return func(h *QueryHook) {
for _, key := range keys {
if env, ok := os.LookupEnv(key); ok {
h.enabled = env != "" && env != "0"
h.verbose = env == "2"
break
}
}
}
}
// WithQueryHookOptions allows setting the initial logging options
// for logrus
func WithQueryHookOptions(opts QueryHookOptions) Option {
return func(h *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
h.opts = &opts
}
}
// 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 {
enabled bool
verbose bool
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(options ...Option) *QueryHook {
h := new(QueryHook)
for _, opt := range options {
opt(h)
}
if h.opts == nil {
panic("logrus settings not set.")
}
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) {
if !h.enabled {
return
}
if !h.verbose {
switch event.Err {
case nil, sql.ErrNoRows, sql.ErrTxDone:
return
}
}
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(event.Query)
}
// taken from bun
func queryOperation(name string) string {
if idx := strings.Index(name, " "); idx > 0 {
name = name[:idx]
}
if len(name) > 16 {
name = name[:16]
}
return string(name)
}