-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
71 lines (60 loc) · 1.68 KB
/
Copy pathhandler.go
File metadata and controls
71 lines (60 loc) · 1.68 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package clog
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"github.com/ronny/clog/trace"
)
var ErrInvalidHandlerOptions = errors.New("invalid HandlerOptions")
type HandlerOptions struct {
AddSource bool
Level slog.Leveler
ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
GoogleProjectID string
}
var _ slog.Handler = (*Handler)(nil)
// Handler is a [log/slog.JSONHandler] preconfigured for Google Cloud Logging.
type Handler struct {
opts HandlerOptions
handler slog.Handler
}
func NewHandler(w io.Writer, opts HandlerOptions) (*Handler, error) {
opts.ReplaceAttr = ReplaceAttr
if opts.GoogleProjectID == "" {
return nil, fmt.Errorf("%w: missing GoogleProjectID", ErrInvalidHandlerOptions)
}
return &Handler{
opts: opts,
handler: slog.NewJSONHandler(w, &slog.HandlerOptions{
AddSource: opts.AddSource,
Level: opts.Level,
ReplaceAttr: opts.ReplaceAttr,
}),
}, nil
}
// Handle implements [log/slog.Handler].
func (h *Handler) Handle(ctx context.Context, record slog.Record) error {
record = trace.NewRecord(ctx, record, h.opts.GoogleProjectID)
record = dedupAttrs(record)
return h.handler.Handle(ctx, record)
}
// Enabled implements [log/slog.Handler].
func (h *Handler) Enabled(ctx context.Context, level slog.Level) bool {
return h.handler.Enabled(ctx, level)
}
// WithAttrs implements [log/slog.Handler].
func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
return &Handler{
opts: h.opts,
handler: h.handler.WithAttrs(attrs),
}
}
// WithGroup implements [log/slog.Handler].
func (h *Handler) WithGroup(name string) slog.Handler {
return &Handler{
opts: h.opts,
handler: h.handler.WithGroup(name),
}
}