Skip to content

Commit 534a15e

Browse files
committed
Add ability to add request ids to logs
1 parent 4a36d2a commit 534a15e

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

logger.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package logger
22

33
import (
4+
"context"
45
"go.uber.org/zap"
56
"go.uber.org/zap/zapcore"
67
)
@@ -14,15 +15,31 @@ const (
1415
FormatGoogleCloud
1516
)
1617

18+
type correlationIdType int
19+
20+
const (
21+
requestIdKey correlationIdType = iota
22+
)
23+
1724
// Default format is format lines
1825
var (
1926
logger *zap.Logger
2027
isInitialized = false
2128

2229
currentFormat = FormatLines
2330
debugLogging = false
31+
logCtx context.Context
2432
)
2533

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+
2643
// SetFormat sets the log output format
2744
func SetFormat(format Format) {
2845
if isInitialized {
@@ -72,6 +89,13 @@ func Instance() *zap.Logger {
7289
logger, _ = cfg.Build()
7390
isInitialized = true
7491
}
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+
7599
return logger
76100
}
77101

logger_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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+
}

0 commit comments

Comments
 (0)