Skip to content

Commit 551e70a

Browse files
committed
cleaner api
1 parent 534a15e commit 551e70a

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

logger.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,13 @@ var (
3131
logCtx context.Context
3232
)
3333

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+
}
3938

39+
//SetContext sets context on logger
40+
func SetContext(ctx context.Context) {
4041
logCtx = ctx
4142
}
4243

@@ -92,7 +93,7 @@ func Instance() *zap.Logger {
9293

9394
if logCtx != nil {
9495
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))
9697
}
9798
}
9899

logger_test.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,15 @@ import (
99

1010
//This is more of a usage example than a test
1111
func TestSetContext(t *testing.T) {
12-
ctx := context.Background()
13-
logger.SetContext(ctx, "request-1234")
1412
logger.SetFormat(logger.FormatGoogleCloud)
1513

14+
ctx := context.Background()
15+
ctx = logger.WithRequestID(ctx, "request-1234")
16+
logger.SetContext(ctx)
17+
1618
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"))
1723
}

0 commit comments

Comments
 (0)