@@ -14,19 +14,33 @@ import (
14
14
sqldblogger "github.com/simukti/sqldb-logger"
15
15
)
16
16
17
+ var _ zerolog.Hook = (* Hook )(nil )
18
+
17
19
type logContent struct {
18
20
Level string `json:"level"`
19
21
Time int64 `json:"time"`
20
22
Duration float64 `json:"duration"`
21
23
Query string `json:"query"`
22
24
Args []interface {} `json:"args"`
23
25
Error string `json:"error"`
26
+ CtxValue string `json:"ctxValue"`
27
+ }
28
+
29
+ type ctxKey struct {}
30
+
31
+ type Hook struct {}
32
+
33
+ func (h Hook ) Run (e * zerolog.Event , _ zerolog.Level , _ string ) {
34
+ ctx := e .GetCtx ()
35
+ if value , ok := ctx .Value (ctxKey {}).(string ); ok {
36
+ e .Str ("ctxValue" , value )
37
+ }
24
38
}
25
39
26
40
func TestZerologAdapter_Log (t * testing.T ) {
27
41
now := time .Now ()
28
42
wr := & bytes.Buffer {}
29
- lg := New (zerolog .New (wr ))
43
+ lg := New (zerolog .New (wr ). Hook ( Hook {}) )
30
44
lvls := map [sqldblogger.Level ]string {
31
45
sqldblogger .LevelError : "error" ,
32
46
sqldblogger .LevelInfo : "info" ,
@@ -47,7 +61,7 @@ func TestZerologAdapter_Log(t *testing.T) {
47
61
data ["error" ] = fmt .Errorf ("dummy error" ).Error ()
48
62
}
49
63
50
- lg .Log (context .TODO (), lvl , "query" , data )
64
+ lg .Log (context .WithValue ( context . TODO (), ctxKey {}, "context value" ), lvl , "query" , data )
51
65
52
66
var content logContent
53
67
@@ -57,6 +71,7 @@ func TestZerologAdapter_Log(t *testing.T) {
57
71
assert .True (t , content .Duration > 0 )
58
72
assert .Equal (t , lvlStr , content .Level )
59
73
assert .Equal (t , "SELECT at.* FROM a_table AS at WHERE a.id = ? LIMIT 1" , content .Query )
74
+ assert .Equal (t , "context value" , content .CtxValue )
60
75
if lvl == sqldblogger .LevelError {
61
76
assert .Equal (t , "dummy error" , content .Error )
62
77
}
0 commit comments