Skip to content

Instantly share code, notes, and snippets.

@cstockton
Created May 9, 2019 14:26
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 cstockton/495d9d9ca64d80034ff3ad5cbb9038d0 to your computer and use it in GitHub Desktop.
Save cstockton/495d9d9ca64d80034ff3ad5cbb9038d0 to your computer and use it in GitHub Desktop.
type contextKey struct{}
// FromContext returns the current zap logger from the given context, or
// the default global logger (by calling zap.L()) otherwise.
func FromContext(ctx context.Context) *zap.Logger {
if v, ok := ctx.Value(contextKey{}).(*zap.Logger); ok {
return v
}
return zap.L()
}
// WithContext returns a context.Context with a Value containing the given
// zap logger.
func WithContext(ctx context.Context, l *zap.Logger) context.Context {
return context.WithValue(ctx, contextKey{}, l)
}
// Check calls zap.Check on the logger for ctx.
func Check(ctx context.Context, lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
return FromContext(ctx).Check(lvl, msg)
}
// Debug calls zap.Debug on the logger for ctx.
func Debug(ctx context.Context, msg string, fields ...zapcore.Field) {
FromContext(ctx).Debug(msg, fields...)
}
// Error calls zap.Error on the logger for ctx.
func Error(ctx context.Context, msg string, fields ...zapcore.Field) {
FromContext(ctx).Error(msg, fields...)
}
// Info calls zap.Info on the logger for ctx.
func Info(ctx context.Context, msg string, fields ...zapcore.Field) {
FromContext(ctx).Info(msg, fields...)
}
// Named calls zap.Named on the logger for ctx.
func Named(ctx context.Context, s string) context.Context {
return WithContext(ctx, FromContext(ctx).Named(s))
}
// Sync calls zap.Sync on the logger for ctx.
func Sync(ctx context.Context) error { return FromContext(ctx).Sync() }
// Warn calls zap.Warn on the logger for ctx.
func Warn(ctx context.Context, msg string, fields ...zapcore.Field) {
FromContext(ctx).Warn(msg, fields...)
}
// With calls zap.With on the logger for ctx.
func With(ctx context.Context, fields ...zapcore.Field) context.Context {
return WithContext(ctx, FromContext(ctx).With(fields...))
}
// WithOptions calls zap.WithOptions on the logger for ctx.
func WithOptions(ctx context.Context, opts ...zap.Option) context.Context {
return WithContext(ctx, FromContext(ctx).WithOptions(opts...))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment