Created
May 30, 2018 14:49
-
-
Save yurishkuro/ef8fe7707967d37f692cfdfeba8c2080 to your computer and use it in GitHub Desktop.
Contextual logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type traceLogger { | |
span opentracing.Span | |
zl *zap.Logger | |
l *Logger | |
} | |
func (l *Logger) Trace(ctx context.Context) (*zap.Logger, context.Context) { | |
span := opentracing.SpanFromContext(ctx) | |
if span == nil { | |
return l.NoTrace(), ctx | |
} | |
traceLogger := ctx.Value("traceLogger").(*traceLogger) | |
if traceLogger != nil && tracerLogger.span == span && traceLogger.l == l { | |
return traceLogger.zl, ctx | |
} | |
traceLogger = &traceLogger{ | |
span: span, | |
l: l, | |
zl: l.NoTrace().With(zapfx.Trace(ctx)) | |
} | |
return traceLogger.zl, ctx.With("traceLogger", traceLogger) | |
} | |
// If some top-level function calls this once | |
zl, ctx := l.Trace(ctx) | |
// and then passes the new `ctx` to other functions, then the cached logger will be reused for all subsequent l.Trace(ctx) calls. | |
// It makes a reasonable assumption that you usually use the same Logger instance within the flow of a single request, and allows | |
// you to retrieve the same zap.Logger as long as the context has the same span. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment