-
Notifications
You must be signed in to change notification settings - Fork 0
/
ctxhook.go
41 lines (33 loc) · 1 KB
/
ctxhook.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
// Package sqllog provides a logging hook for go-mssqldb that turns mssqldb
// errors into proper logging using logrus. See README.md.
package sqllogging
import (
"context"
mssql "github.com/denisenkom/go-mssqldb"
"github.com/denisenkom/go-mssqldb/msdsn"
)
type contextKey int
const ckLogger contextKey = iota
// WithLogger attaches an mssql.ContextLogger to ctx. This is the basic
// hook and you may use this directly to override the SQL logger per call.
func WithLogger(ctx context.Context, logger mssql.ContextLogger) context.Context {
return context.WithValue(ctx, ckLogger, logger)
}
func LoggerOrNil(ctx context.Context) mssql.ContextLogger {
val := ctx.Value(ckLogger)
if val == nil {
return nil
}
return val.(mssql.ContextLogger)
}
type mssqlLogHook struct{}
func InstallMssql() {
mssql.SetContextLogger(mssqlLogHook{})
}
func (m mssqlLogHook) Log(ctx context.Context, category msdsn.Log, msg string) {
logger := LoggerOrNil(ctx)
if logger == nil {
return
}
logger.Log(ctx, category, msg)
}