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

Synchronize access to ctxlogrus and ctxzap fields #362

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions logging/logrus/ctxlogrus/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ctxlogrus

import (
"context"
"sync"

"github.com/grpc-ecosystem/go-grpc-middleware/tags"
"github.com/sirupsen/logrus"
Expand All @@ -12,6 +13,7 @@ type ctxLoggerMarker struct{}
type ctxLogger struct {
logger *logrus.Entry
fields logrus.Fields
lock sync.Mutex
}

var (
Expand All @@ -24,9 +26,12 @@ func AddFields(ctx context.Context, fields logrus.Fields) {
if !ok || l == nil {
return
}

l.lock.Lock()
for k, v := range fields {
l.fields[k] = v
}
l.lock.Unlock()
}

// Extract takes the call-scoped logrus.Entry from ctx_logrus middleware.
Expand All @@ -48,9 +53,11 @@ func Extract(ctx context.Context) *logrus.Entry {
}

// Add logrus fields added until now.
l.lock.Lock()
for k, v := range l.fields {
fields[k] = v
}
l.lock.Unlock()

return l.logger.WithFields(fields)
}
Expand Down
9 changes: 9 additions & 0 deletions logging/zap/ctxzap/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ctxzap

import (
"context"
"sync"

"github.com/grpc-ecosystem/go-grpc-middleware/tags"
"go.uber.org/zap"
Expand All @@ -13,6 +14,7 @@ type ctxMarker struct{}
type ctxLogger struct {
logger *zap.Logger
fields []zapcore.Field
lock sync.Mutex
}

var (
Expand All @@ -26,7 +28,10 @@ func AddFields(ctx context.Context, fields ...zapcore.Field) {
if !ok || l == nil {
return
}

l.lock.Lock()
l.fields = append(l.fields, fields...)
l.lock.Unlock()
}

// Extract takes the call-scoped Logger from grpc_zap middleware.
Expand All @@ -39,8 +44,12 @@ func Extract(ctx context.Context) *zap.Logger {
}
// Add grpc_ctxtags tags metadata until now.
fields := TagsToFields(ctx)

// Add zap fields added until now.
l.lock.Lock()
fields = append(fields, l.fields...)
l.lock.Unlock()

return l.logger.With(fields...)
}

Expand Down