Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add function to add Correlation IDs to logger #37

Merged
merged 2 commits into from
Mar 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions logging/correlation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
)
}
55 changes: 55 additions & 0 deletions logging/correlation_test.go
Original file line number Diff line number Diff line change
@@ -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)])
}