diff options
Diffstat (limited to 'go/log/handler.go')
| -rw-r--r-- | go/log/handler.go | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/go/log/handler.go b/go/log/handler.go new file mode 100644 index 00000000..75231098 --- /dev/null +++ b/go/log/handler.go @@ -0,0 +1,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} +} |
