File tree Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Expand file tree Collapse file tree 2 files changed +41
-0
lines changed Original file line number Diff line number Diff line change 1
1
package logger
2
2
3
3
import (
4
+ "context"
4
5
"go.uber.org/zap"
5
6
"go.uber.org/zap/zapcore"
6
7
)
@@ -14,15 +15,31 @@ const (
14
15
FormatGoogleCloud
15
16
)
16
17
18
+ type correlationIdType int
19
+
20
+ const (
21
+ requestIdKey correlationIdType = iota
22
+ )
23
+
17
24
// Default format is format lines
18
25
var (
19
26
logger * zap.Logger
20
27
isInitialized = false
21
28
22
29
currentFormat = FormatLines
23
30
debugLogging = false
31
+ logCtx context.Context
24
32
)
25
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
+ }
39
+
40
+ logCtx = ctx
41
+ }
42
+
26
43
// SetFormat sets the log output format
27
44
func SetFormat (format Format ) {
28
45
if isInitialized {
@@ -72,6 +89,13 @@ func Instance() *zap.Logger {
72
89
logger , _ = cfg .Build ()
73
90
isInitialized = true
74
91
}
92
+
93
+ if logCtx != nil {
94
+ if ctxRequestID , ok := logCtx .Value (requestIdKey ).(string ); ok {
95
+ logger = logger .With (zap .String ("REQUEST_ID" , ctxRequestID ))
96
+ }
97
+ }
98
+
75
99
return logger
76
100
}
77
101
Original file line number Diff line number Diff line change
1
+ package logger_test
2
+
3
+ import (
4
+ "context"
5
+ "github.com/lucidcube/logger-go"
6
+ "go.uber.org/zap"
7
+ "testing"
8
+ )
9
+
10
+ //This is more of a usage example than a test
11
+ func TestSetContext (t * testing.T ) {
12
+ ctx := context .Background ()
13
+ logger .SetContext (ctx , "request-1234" )
14
+ logger .SetFormat (logger .FormatGoogleCloud )
15
+
16
+ logger .Instance ().Info ("debug message" , zap .String ("key" , "key-1" ))
17
+ }
You can’t perform that action at this time.
0 commit comments