Skip to content

Commit

Permalink
feat: allow trace_id key to be configured
Browse files Browse the repository at this point in the history
  • Loading branch information
skyerus committed Mar 27, 2024
1 parent 31fd20c commit 79c9903
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
*.db
otelgraphql/example/graphql*
.idea
3 changes: 2 additions & 1 deletion otelzap/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ func WithExtraFields(fields ...zapcore.Field) Option {
//
// This option is only useful with backends that don't support OTLP and instead parse log
// messages to extract structured information.
func WithTraceIDField(on bool) Option {
func WithTraceIDField(on bool, key string) Option {
return func(l *Logger) {
l.withTraceID = on
l.traceIDKey = key
}
}
8 changes: 6 additions & 2 deletions otelzap/otelzap.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (

const numAttr = 5

const traceIDKey = "trace_id"

var (
logSeverityKey = attribute.Key("log.severity")
logMessageKey = attribute.Key("log.message")
Expand All @@ -33,6 +35,7 @@ type Logger struct {
skipCaller *zap.Logger

withTraceID bool
traceIDKey string

minLevel zapcore.Level
errorStatusLevel zapcore.Level
Expand All @@ -54,6 +57,7 @@ func New(logger *zap.Logger, opts ...Option) *Logger {
errorStatusLevel: zap.ErrorLevel,
caller: true,
callerDepth: 0,
traceIDKey: traceIDKey,
}
for _, opt := range opts {
opt(l)
Expand Down Expand Up @@ -168,7 +172,7 @@ func (l *Logger) logFields(

if l.withTraceID {
traceID := span.SpanContext().TraceID().String()
fields = append(fields, zap.String("trace_id", traceID))
fields = append(fields, zap.String(l.traceIDKey, traceID))
}

return fields
Expand Down Expand Up @@ -540,7 +544,7 @@ func (s *SugaredLogger) logKVs(

if s.l.withTraceID {
traceID := span.SpanContext().TraceID().String()
kvs = append(kvs, "trace_id", traceID)
kvs = append(kvs, s.l.traceIDKey, traceID)
}

return kvs
Expand Down

0 comments on commit 79c9903

Please sign in to comment.