/
handler.go
53 lines (46 loc) · 1015 Bytes
/
handler.go
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 inithandler
import (
"context"
"fmt"
"io"
"log/slog"
"os"
)
// Handler only logs very basic error messages for use when logging
// intialization fails or there's otherwise an issue with startup.
type Handler struct {
w io.Writer
}
func New() *Handler {
return &Handler{os.Stderr}
}
func (*Handler) Enabled(_ context.Context, lvl slog.Level) bool {
return lvl == slog.LevelError
}
// implements Handler.Handle.
func (h *Handler) Handle(_ context.Context, r slog.Record) error {
var errVal error
r.Attrs(func(a slog.Attr) bool {
switch {
case a.Key == "err":
errVal = a.Value.Any().(error)
default:
return true
}
return true
})
h.w.Write([]byte(r.Message))
if errVal != nil {
h.w.Write([]byte(fmt.Sprintf(" - %v", errVal)))
}
h.w.Write([]byte{'\n'})
return nil
}
// WithAttrs implements slog.Handler
func (h *Handler) WithAttrs([]slog.Attr) slog.Handler {
return h
}
// WithGroup implements slog.Handler
func (h *Handler) WithGroup(string) slog.Handler {
return h
}