golang.org/x/net@v0.25.1-0.20240516223405-c87a5b62e243/quic/qlog/handler.go (about) 1 // Copyright 2023 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build go1.21 6 7 package qlog 8 9 import ( 10 "context" 11 "log/slog" 12 ) 13 14 type withAttrsHandler struct { 15 attrs []slog.Attr 16 h slog.Handler 17 } 18 19 func withAttrs(h slog.Handler, attrs []slog.Attr) slog.Handler { 20 if len(attrs) == 0 { 21 return h 22 } 23 return &withAttrsHandler{attrs: attrs, h: h} 24 } 25 26 func (h *withAttrsHandler) Enabled(ctx context.Context, level slog.Level) bool { 27 return h.h.Enabled(ctx, level) 28 } 29 30 func (h *withAttrsHandler) Handle(ctx context.Context, r slog.Record) error { 31 r.AddAttrs(h.attrs...) 32 return h.h.Handle(ctx, r) 33 } 34 35 func (h *withAttrsHandler) WithAttrs(attrs []slog.Attr) slog.Handler { 36 return withAttrs(h, attrs) 37 } 38 39 func (h *withAttrsHandler) WithGroup(name string) slog.Handler { 40 return withGroup(h, name) 41 } 42 43 type withGroupHandler struct { 44 name string 45 h slog.Handler 46 } 47 48 func withGroup(h slog.Handler, name string) slog.Handler { 49 if name == "" { 50 return h 51 } 52 return &withGroupHandler{name: name, h: h} 53 } 54 55 func (h *withGroupHandler) Enabled(ctx context.Context, level slog.Level) bool { 56 return h.h.Enabled(ctx, level) 57 } 58 59 func (h *withGroupHandler) Handle(ctx context.Context, r slog.Record) error { 60 var attrs []slog.Attr 61 r.Attrs(func(a slog.Attr) bool { 62 attrs = append(attrs, a) 63 return true 64 }) 65 nr := slog.NewRecord(r.Time, r.Level, r.Message, r.PC) 66 nr.Add(slog.Any(h.name, slog.GroupValue(attrs...))) 67 return h.h.Handle(ctx, nr) 68 } 69 70 func (h *withGroupHandler) WithAttrs(attrs []slog.Attr) slog.Handler { 71 return withAttrs(h, attrs) 72 } 73 74 func (h *withGroupHandler) WithGroup(name string) slog.Handler { 75 return withGroup(h, name) 76 }