Handle handles the Record. It converts the slog.Record into a zerolog event and writes it using the underlying zerolog.Logger.
(ctx context.Context, record slog.Record)
| 38 | // Handle handles the Record. It converts the slog.Record into a zerolog event |
| 39 | // and writes it using the underlying zerolog.Logger. |
| 40 | func (h *SlogHandler) Handle(ctx context.Context, record slog.Record) error { |
| 41 | zlevel := slogToZerologLevel(record.Level) |
| 42 | event := h.logger.WithLevel(zlevel) |
| 43 | if event == nil { |
| 44 | return nil |
| 45 | } |
| 46 | |
| 47 | // Propagate slog context to the zerolog event so that hooks |
| 48 | // relying on Event.GetCtx() (e.g. tracing) can access it. |
| 49 | if ctx != nil { |
| 50 | event = event.Ctx(ctx) |
| 51 | } |
| 52 | |
| 53 | // Add pre-attached attrs from WithAttrs |
| 54 | for _, a := range h.attrs { |
| 55 | event = appendSlogAttr(event, a, h.prefix) |
| 56 | } |
| 57 | |
| 58 | // Add attrs from the record itself |
| 59 | record.Attrs(func(a slog.Attr) bool { |
| 60 | event = appendSlogAttr(event, a, h.prefix) |
| 61 | return true |
| 62 | }) |
| 63 | |
| 64 | // Add timestamp from the slog record, but only if the logger doesn't |
| 65 | // already have a timestampHook (added via .With().Timestamp()) to |
| 66 | // avoid duplicate timestamp keys in the output. |
| 67 | if !record.Time.IsZero() && !h.hasTimestampHook() { |
| 68 | event.Time(TimestampFieldName, record.Time) |
| 69 | } |
| 70 | |
| 71 | event.Msg(record.Message) |
| 72 | return nil |
| 73 | } |
| 74 | |
| 75 | // hasTimestampHook reports whether the logger has a timestampHook installed, |
| 76 | // which would cause duplicate timestamp fields if we also emit record.Time. |