File: handler.go

package info (click to toggle)
golang-golang-x-net 1%3A0.24.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 8,460 kB
  • sloc: asm: 18; makefile: 12; sh: 7
file content (76 lines) | stat: -rw-r--r-- 1,731 bytes parent folder | download | duplicates (4)
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
72
73
74
75
76
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build go1.21

package qlog

import (
	"context"
	"log/slog"
)

type withAttrsHandler struct {
	attrs []slog.Attr
	h     slog.Handler
}

func withAttrs(h slog.Handler, attrs []slog.Attr) slog.Handler {
	if len(attrs) == 0 {
		return h
	}
	return &withAttrsHandler{attrs: attrs, h: h}
}

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

func (h *withAttrsHandler) Handle(ctx context.Context, r slog.Record) error {
	r.AddAttrs(h.attrs...)
	return h.h.Handle(ctx, r)
}

func (h *withAttrsHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	return withAttrs(h, attrs)
}

func (h *withAttrsHandler) WithGroup(name string) slog.Handler {
	return withGroup(h, name)
}

type withGroupHandler struct {
	name string
	h    slog.Handler
}

func withGroup(h slog.Handler, name string) slog.Handler {
	if name == "" {
		return h
	}
	return &withGroupHandler{name: name, h: h}
}

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

func (h *withGroupHandler) Handle(ctx context.Context, r slog.Record) error {
	var attrs []slog.Attr
	r.Attrs(func(a slog.Attr) bool {
		attrs = append(attrs, a)
		return true
	})
	nr := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
	nr.Add(slog.Any(h.name, slog.GroupValue(attrs...)))
	return h.h.Handle(ctx, nr)
}

func (h *withGroupHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
	return withAttrs(h, attrs)
}

func (h *withGroupHandler) WithGroup(name string) slog.Handler {
	return withGroup(h, name)
}