aboutsummaryrefslogtreecommitdiff
path: root/go/log/handler.go
blob: 75231098de46efca14f58ba322b32b1454f208cb (plain)
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
package log

import (
	"context"
	"log/slog"
	"os"
	"runtime"

	"golang.org/x/exp/slices"
)

type gameLogHandler struct {
	h     slog.Handler
	files []string
}

func NewGameLogHandler(files []string, opts *slog.HandlerOptions) *gameLogHandler {
	return &gameLogHandler{h: slog.NewTextHandler(os.Stdout, opts), files: files}
}

func (h *gameLogHandler) Enabled(ctx context.Context, level slog.Level) bool {
	return h.h.Enabled(ctx, level)
}

func (h *gameLogHandler) Handle(ctx context.Context, r slog.Record) error {
	frames := runtime.CallersFrames([]uintptr{r.PC})
	frame, _ := frames.Next()
	if slices.Contains(h.files, frame.File) {
		return nil
	}

	return h.h.Handle(ctx, r)
}

func (h *gameLogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	return &gameLogHandler{h: h.h.WithAttrs(attrs), files: h.files}
}

func (h *gameLogHandler) WithGroup(name string) slog.Handler {
	return &gameLogHandler{h: h.h.WithGroup(name), files: h.files}
}