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

Allow usage of zerolog.Ctx(ctx) in Enabled() and Handle() methods #3

Open
dhermes opened this issue Dec 14, 2023 · 0 comments
Open

Comments

@dhermes
Copy link

dhermes commented Dec 14, 2023

It's possible to attach a zerolog logger to a root context

logger := zerolog.New(...)
ctx = logger.WithContext(ctx)

and then later access it via zerolog.Ctx(ctx).

This is a fairly common pattern (attaching a logger to + reading a logger from a context). An example implementation of Enabled() with it could be:

// Enabled checks if the given level is enabled for the logger.
func (*ZerologHandler) Enabled(ctx context.Context, level slog.Level) bool {
	zl := zerolog.Ctx(ctx)
	switch level {
	case slog.LevelDebug:
		return zl.Debug().Enabled()
	case slog.LevelInfo:
		return zl.Info().Enabled()
	case slog.LevelWarn:
		return zl.Warn().Enabled()
	case slog.LevelError:
		return zl.Error().Enabled()
	default:
		return false
	}
}

(The above is not intended to cover fallbacks / overrides / alternative resolution methods, just a particular way to use zerolog.Ctx(ctx). Note also you could use zerolog.Ctx(ctx).GetLevel() if the above implementation is not adequate.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant