-
-
Notifications
You must be signed in to change notification settings - Fork 344
Expand file tree
/
Copy pathlogging.go
More file actions
53 lines (41 loc) 路 1.27 KB
/
Copy pathlogging.go
File metadata and controls
53 lines (41 loc) 路 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package mercure
import (
"context"
"fmt"
"log/slog"
)
// INTERNAL: NewSlogHandler returns a log/slog.Handler that automatically appends "update" and "subscriber"
// context, if applicable.
//
// This function will be removed when https://github.com/caddyserver/caddy/pull/7346 will be available.
//
//nolint:godoclint
func NewSlogHandler(handler slog.Handler) slog.Handler {
return &mercureHandler{handler}
}
type mercureHandler struct {
innerHandler slog.Handler
}
func (m mercureHandler) Enabled(ctx context.Context, level slog.Level) bool {
return m.innerHandler.Enabled(ctx, level)
}
func (m mercureHandler) Handle(ctx context.Context, record slog.Record) error {
var attrs []slog.Attr
if u, ok := ctx.Value(UpdateContextKey).(*Update); ok {
attrs = append(attrs, slog.Any("update", u))
}
if s, ok := ctx.Value(SubscriberContextKey).(*Subscriber); ok {
attrs = append(attrs, slog.Any("subscriber", s))
}
record.AddAttrs(attrs...)
if err := m.innerHandler.Handle(ctx, record); err != nil {
return fmt.Errorf("error while logging: %w", err)
}
return nil
}
func (m mercureHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return m.innerHandler.WithAttrs(attrs)
}
func (m mercureHandler) WithGroup(name string) slog.Handler {
return m.innerHandler.WithGroup(name)
}