@@ -92,7 +92,23 @@ func Test_logger_LogMode(t *testing.T) {
92
92
}
93
93
94
94
func Test_logger (t * testing.T ) {
95
- receiver , gormLogger := getReceiverAndLogger ([]Option {WithContextValue ("attrKey" , "ctxKey" )})
95
+ receiver , gormLogger := getReceiverAndLogger ([]Option {
96
+ WithContextValue ("attrKeyViaValue" , "ctxKey" ),
97
+ WithContextFunc ("attrKeyViaFunc1" , func (ctx context.Context ) (slog.Value , bool ) {
98
+ v , ok := ctx .Value (ctxKey1 ).(string )
99
+ if ! ok {
100
+ return slog.Value {}, false
101
+ }
102
+ return slog .StringValue (v ), true
103
+ }),
104
+ WithContextFunc ("attrKeyViaFunc2" , func (ctx context.Context ) (slog.Value , bool ) {
105
+ v , ok := ctx .Value (ctxKey2 ).(time.Duration )
106
+ if ! ok {
107
+ return slog.Value {}, false
108
+ }
109
+ return slog .DurationValue (v ), true
110
+ }),
111
+ })
96
112
expectedMsg := "awesome message"
97
113
98
114
tests := []struct {
@@ -111,6 +127,24 @@ func Test_logger(t *testing.T) {
111
127
wantMsg : expectedMsg ,
112
128
wantLevel : slog .LevelInfo ,
113
129
},
130
+ {
131
+ name : "with context value and func" ,
132
+ ctx : context .WithValue (
133
+ context .WithValue (
134
+ context .WithValue (context .Background (), "ctxKey" , "ctxVal" ),
135
+ ctxKey1 , "ctxValFunc1" ,
136
+ ),
137
+ ctxKey2 , time .Second ,
138
+ ),
139
+ function : gormLogger .Info ,
140
+ wantMsg : expectedMsg ,
141
+ wantAttributes : map [string ]slog.Attr {
142
+ "attrKeyViaValue" : slog .Any ("attrKeyViaValue" , "ctxVal" ),
143
+ "attrKeyViaFunc1" : slog .String ("attrKeyViaFunc1" , "ctxValFunc1" ),
144
+ "attrKeyViaFunc2" : slog .Duration ("attrKeyViaFunc2" , time .Second ),
145
+ },
146
+ wantLevel : slog .LevelInfo ,
147
+ },
114
148
{
115
149
name : "Warn" ,
116
150
ctx : context .Background (),
@@ -130,7 +164,7 @@ func Test_logger(t *testing.T) {
130
164
ctx : context .WithValue (context .Background (), "ctxKey" , "ctxVal" ),
131
165
function : gormLogger .Error ,
132
166
wantMsg : expectedMsg ,
133
- wantAttributes : map [string ]slog.Attr {"attrKey " : slog .Any ("attrKey " , "ctxVal" )},
167
+ wantAttributes : map [string ]slog.Attr {"attrKeyViaValue " : slog .Any ("attrKeyViaValue " , "ctxVal" )},
134
168
wantLevel : slog .LevelError ,
135
169
},
136
170
}
@@ -389,7 +423,7 @@ func Test_logger_Trace(t *testing.T) {
389
423
}
390
424
}
391
425
392
- // private functions
426
+ // private helpers
393
427
394
428
func getReceiverAndLogger (options []Option ) (* DummyHandler , * logger ) {
395
429
receiver := NewDummyHandler ()
@@ -398,6 +432,13 @@ func getReceiverAndLogger(options []Option) (*DummyHandler, *logger) {
398
432
return receiver , New (options ... )
399
433
}
400
434
435
+ type ctxKey int
436
+
437
+ const (
438
+ ctxKey1 ctxKey = iota
439
+ ctxKey2
440
+ )
441
+
401
442
// Mock
402
443
403
444
func NewDummyHandler () * DummyHandler {
0 commit comments