File tree Expand file tree Collapse file tree 2 files changed +15
-8
lines changed Expand file tree Collapse file tree 2 files changed +15
-8
lines changed Original file line number Diff line number Diff line change @@ -31,12 +31,13 @@ var (
31
31
logCtx context.Context
32
32
)
33
33
34
- func SetContext (ctx context.Context , requestID string ) {
35
- ctxRequestID , ok := ctx .Value (requestIdKey ).(string )
36
- if ! ok || len (ctxRequestID ) == 0 {
37
- ctx = context .WithValue (ctx , requestIdKey , requestID )
38
- }
34
+ //WithRequestID sets a requestID value in ctx
35
+ func WithRequestID (ctx context.Context , requestID string ) context.Context {
36
+ return context .WithValue (ctx , requestIdKey , requestID )
37
+ }
39
38
39
+ //SetContext sets context on logger
40
+ func SetContext (ctx context.Context ) {
40
41
logCtx = ctx
41
42
}
42
43
@@ -92,7 +93,7 @@ func Instance() *zap.Logger {
92
93
93
94
if logCtx != nil {
94
95
if ctxRequestID , ok := logCtx .Value (requestIdKey ).(string ); ok {
95
- logger = logger .With (zap .String ("REQUEST_ID" , ctxRequestID ))
96
+ return logger .With (zap .String ("REQUEST_ID" , ctxRequestID ))
96
97
}
97
98
}
98
99
Original file line number Diff line number Diff line change @@ -9,9 +9,15 @@ import (
9
9
10
10
//This is more of a usage example than a test
11
11
func TestSetContext (t * testing.T ) {
12
- ctx := context .Background ()
13
- logger .SetContext (ctx , "request-1234" )
14
12
logger .SetFormat (logger .FormatGoogleCloud )
15
13
14
+ ctx := context .Background ()
15
+ ctx = logger .WithRequestID (ctx , "request-1234" )
16
+ logger .SetContext (ctx )
17
+
16
18
logger .Instance ().Info ("debug message" , zap .String ("key" , "key-1" ))
19
+
20
+ ctx = logger .WithRequestID (ctx , "request-34567" )
21
+ logger .SetContext (ctx )
22
+ logger .Instance ().Info ("another debug message" , zap .String ("key" , "key-2" ))
17
23
}
You can’t perform that action at this time.
0 commit comments