Skip to content

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

Open
@dhermes

Description

@dhermes

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.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions