-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhandler.go
More file actions
54 lines (44 loc) · 1.29 KB
/
handler.go
File metadata and controls
54 lines (44 loc) · 1.29 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
package logger
import (
"context"
"io"
"log/slog"
"strings"
"sync"
)
// RawHandler is an [slog.Handler] that outputs only the log message followed by
// a newline. Structured attributes and groups are discarded. This is used for
// the "raw" logger mode where callers want plain, undecorated output.
type RawHandler struct {
w io.Writer
level slog.Leveler
mu sync.Mutex
}
// NewRawHandler returns a [RawHandler] writing to w. Only records at or above
// the given level are emitted.
func NewRawHandler(w io.Writer, level slog.Leveler) *RawHandler {
return &RawHandler{
w: w,
level: level,
}
}
func (h *RawHandler) Enabled(_ context.Context, level slog.Level) bool {
return level >= h.level.Level()
}
func (h *RawHandler) Handle(_ context.Context, r slog.Record) error {
h.mu.Lock()
defer h.mu.Unlock()
if _, err := io.WriteString(h.w, r.Message); err != nil {
return err
}
if !strings.HasSuffix(r.Message, "\n") {
if _, err := io.WriteString(h.w, "\n"); err != nil {
return err
}
}
return nil
}
// WithAttrs returns the same handler — raw mode discards attributes.
func (h *RawHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
// WithGroup returns the same handler — raw mode discards groups.
func (h *RawHandler) WithGroup(string) slog.Handler { return h }