diff --git a/logging/correlation.go b/logging/correlation.go index 36d1172..eb2c767 100644 --- a/logging/correlation.go +++ b/logging/correlation.go @@ -48,3 +48,19 @@ func addCorrelationID(c *gin.Context, l *zap.SugaredLogger) { c.Next() } + +// AddCorrelationIDToLogger takes correlation ID from the request context and +// enriches the logger with them. The param logger cannot be nil. +func AddCorrelationIDToLogger(c *gin.Context, l *zap.SugaredLogger) *zap.SugaredLogger { + if c == nil { + return l + } + + // note: correlation IDs are in the request context, not in the gin context + ctx := c.Request.Context() + + return l.With( + string(CorrelationIDName), ctx.Value(CorrelationIDName), + string(IntCorrelationIDName), ctx.Value(IntCorrelationIDName), + ) +} diff --git a/logging/correlation_test.go b/logging/correlation_test.go new file mode 100644 index 0000000..6f61e0c --- /dev/null +++ b/logging/correlation_test.go @@ -0,0 +1,55 @@ +package logging + +import ( + "context" + "go.uber.org/zap/zaptest/observer" + "net/http" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "go.uber.org/zap" +) + +func makeTestContext() *gin.Context { + c, _ := gin.CreateTestContext(nil) + ctx := context.WithValue(context.Background(), IntCorrelationIDName, "anything") + request, _ := http.NewRequestWithContext(ctx, http.MethodPost, "http://something", nil) + c.Request = request + return c +} + +func Test_AddCorrelationIDToLogger_Nil_Context(t *testing.T) { + assert := assert.New(t) + + base := zap.NewExample().Sugar() + + assert.NotPanics(func() { + logger := AddCorrelationIDToLogger(nil, base) + assert.Equal(base, logger) + }) +} + +func Test_AddCorrelationIDToLogger_Nil_Logger(t *testing.T) { + assert := assert.New(t) + + c := makeTestContext() + + assert.Panics(func() { + AddCorrelationIDToLogger(c, nil) + }) +} + +func Test_AddCorrelationIDToLogger(t *testing.T) { + assert := assert.New(t) + + c := makeTestContext() + + observedZapCore, observedLogs := observer.New(zap.InfoLevel) + observedLogger := zap.New(observedZapCore) + + logger := AddCorrelationIDToLogger(c, observedLogger.Sugar()) + logger.Info("test") + + assert.Equal("anything", observedLogs.All()[0].ContextMap()[string(IntCorrelationIDName)]) +}