1
0
mirror of https://github.com/rs/zerolog synced 2026-06-08 17:13:30 +00:00

1 Commits

Author SHA1 Message Date
Varun Chawla d64c9a7138 Add slog.Handler implementation for zerolog (#755)
Closes #571

I needed slog interop in a project where zerolog handles all log output, but some dependencies use `log/slog`. Rather than losing zerolog's performance by switching to slog's built-in JSON handler, this adds a `SlogHandler` that implements `slog.Handler` and routes everything through zerolog.

### What this does

`zerolog.NewSlogHandler(logger)` returns a `slog.Handler` backed by the given `zerolog.Logger`. You can use it like:

```go
zl := zerolog.New(os.Stderr).With().Timestamp().Logger()
slog.SetDefault(slog.New(zerolog.NewSlogHandler(zl)))

slog.Info("request handled", "method", "GET", "status", 200)
// Output: {"level":"info","method":"GET","status":200,"time":...,"message":"request handled"}
```

**Level mapping:**
- `slog.LevelDebug-4` and below -> `zerolog.TraceLevel`
- `slog.LevelDebug` -> `zerolog.DebugLevel`
- `slog.LevelInfo` -> `zerolog.InfoLevel`
- `slog.LevelWarn` -> `zerolog.WarnLevel`
- `slog.LevelError` -> `zerolog.ErrorLevel`

**Supported features:**
- All slog attribute types encoded with zerolog's typed methods (no reflection for primitives)
- `WithAttrs` for pre-attaching fields to child handlers
- `WithGroup` for namespacing keys with dot-separated prefixes
- Nested groups work correctly
- `LogValuer` resolution
- Level filtering respects the zerolog Logger's configured level
- Zerolog contextual fields from `With()` are preserved

**Files:**
- `slog.go` - the handler implementation (~200 lines)
- `slog_test.go` - 26 tests covering levels, all attr types, groups, filtering, LogValuer, immutability

All existing tests continue to pass (the `RandomSampler` flake in `sampler_test.go` is pre-existing).

The `go.mod` already requires Go 1.23, so `log/slog` is available without any changes.
2026-03-17 00:43:02 +00:00