@@ -13,11 +13,16 @@ import (
13
13
"gopkg.in/DataDog/dd-trace-go.v1/internal/log"
14
14
)
15
15
16
+ // groupOrAttrs holds either a group name or a list of slog.Attrs.
17
+ type groupOrAttrs struct {
18
+ group string // group name if non-empty
19
+ attrs []slog.Attr // attrs if non-empty
20
+ }
21
+
16
22
// slogHandler implements the slog.Handler interface to dispatch messages to our
17
23
// internal logger.
18
24
type slogHandler struct {
19
- attrs []string
20
- groups []string
25
+ goas []groupOrAttrs
21
26
}
22
27
23
28
func (h slogHandler ) Enabled (ctx context.Context , lvl slog.Level ) bool {
@@ -30,10 +35,30 @@ func (h slogHandler) Enabled(ctx context.Context, lvl slog.Level) bool {
30
35
}
31
36
32
37
func (h slogHandler ) Handle (ctx context.Context , r slog.Record ) error {
33
- parts := make ([]string , 0 , len (h .attrs )+ r .NumAttrs ())
34
- parts = append (parts , h .attrs ... )
38
+ goas := h .goas
39
+
40
+ if r .NumAttrs () == 0 {
41
+ // If the record has no Attrs, remove groups at the end of the list; they are empty.
42
+ for len (goas ) > 0 && goas [len (goas )- 1 ].group != "" {
43
+ goas = goas [:len (goas )- 1 ]
44
+ }
45
+ }
46
+
47
+ parts := make ([]string , 0 , len (goas )+ r .NumAttrs ())
48
+ formatGroup := ""
49
+
50
+ for _ , goa := range goas {
51
+ if goa .group != "" {
52
+ formatGroup += goa .group + "."
53
+ } else {
54
+ for _ , a := range goa .attrs {
55
+ parts = append (parts , formatGroup + a .String ())
56
+ }
57
+ }
58
+ }
59
+
35
60
r .Attrs (func (a slog.Attr ) bool {
36
- parts = append (parts , formatAttr ( a , h . groups ))
61
+ parts = append (parts , formatGroup + a . String ( ))
37
62
return true
38
63
})
39
64
@@ -51,18 +76,25 @@ func (h slogHandler) Handle(ctx context.Context, r slog.Record) error {
51
76
return nil
52
77
}
53
78
54
- func (h slogHandler ) WithAttrs (attrs []slog.Attr ) slog.Handler {
55
- for _ , a := range attrs {
56
- h .attrs = append (h .attrs , formatAttr (a , h .groups ))
57
- }
79
+ func (h slogHandler ) withGroupOrAttrs (goa groupOrAttrs ) slogHandler {
80
+ h .goas = append (h .goas , goa )
58
81
return h
59
82
}
60
83
84
+ // WithGroup returns a new Handler whose group consist of
85
+ // both the receiver's groups and the arguments.
61
86
func (h slogHandler ) WithGroup (name string ) slog.Handler {
62
- h .groups = append (h .groups , name )
63
- return h
87
+ if name == "" {
88
+ return h
89
+ }
90
+ return h .withGroupOrAttrs (groupOrAttrs {group : name })
64
91
}
65
92
66
- func formatAttr (a slog.Attr , groups []string ) string {
67
- return strings .Join (append (groups , a .String ()), "." )
93
+ // WithAttrs returns a new Handler whose attributes consist of
94
+ // both the receiver's attributes and the arguments.
95
+ func (h slogHandler ) WithAttrs (attrs []slog.Attr ) slog.Handler {
96
+ if len (attrs ) == 0 {
97
+ return h
98
+ }
99
+ return h .withGroupOrAttrs (groupOrAttrs {attrs : attrs })
68
100
}
0 commit comments