Skip to content

Instantly share code, notes, and snippets.

@yurishkuro
Created May 30, 2018 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yurishkuro/ef8fe7707967d37f692cfdfeba8c2080 to your computer and use it in GitHub Desktop.
Save yurishkuro/ef8fe7707967d37f692cfdfeba8c2080 to your computer and use it in GitHub Desktop.
Contextual logger
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