]> Cypherpunks.ru repositories - gostls13.git/blob - src/log/slog/record.go
log/slog: add json struct tags to Source
[gostls13.git] / src / log / slog / record.go
1 // Copyright 2022 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 package slog
6
7 import (
8         "runtime"
9         "slices"
10         "time"
11 )
12
13 const nAttrsInline = 5
14
15 // A Record holds information about a log event.
16 // Copies of a Record share state.
17 // Do not modify a Record after handing out a copy to it.
18 // Use [Record.Clone] to create a copy with no shared state.
19 type Record struct {
20         // The time at which the output method (Log, Info, etc.) was called.
21         Time time.Time
22
23         // The log message.
24         Message string
25
26         // The level of the event.
27         Level Level
28
29         // The program counter at the time the record was constructed, as determined
30         // by runtime.Callers. If zero, no program counter is available.
31         //
32         // The only valid use for this value is as an argument to
33         // [runtime.CallersFrames]. In particular, it must not be passed to
34         // [runtime.FuncForPC].
35         PC uintptr
36
37         // Allocation optimization: an inline array sized to hold
38         // the majority of log calls (based on examination of open-source
39         // code). It holds the start of the list of Attrs.
40         front [nAttrsInline]Attr
41
42         // The number of Attrs in front.
43         nFront int
44
45         // The list of Attrs except for those in front.
46         // Invariants:
47         //   - len(back) > 0 iff nFront == len(front)
48         //   - Unused array elements are zero. Used to detect mistakes.
49         back []Attr
50 }
51
52 // NewRecord creates a Record from the given arguments.
53 // Use [Record.AddAttrs] to add attributes to the Record.
54 //
55 // NewRecord is intended for logging APIs that want to support a [Handler] as
56 // a backend.
57 func NewRecord(t time.Time, level Level, msg string, pc uintptr) Record {
58         return Record{
59                 Time:    t,
60                 Message: msg,
61                 Level:   level,
62                 PC:      pc,
63         }
64 }
65
66 // Clone returns a copy of the record with no shared state.
67 // The original record and the clone can both be modified
68 // without interfering with each other.
69 func (r Record) Clone() Record {
70         r.back = slices.Clip(r.back) // prevent append from mutating shared array
71         return r
72 }
73
74 // NumAttrs returns the number of attributes in the Record.
75 func (r Record) NumAttrs() int {
76         return r.nFront + len(r.back)
77 }
78
79 // Attrs calls f on each Attr in the Record.
80 // Iteration stops if f returns false.
81 func (r Record) Attrs(f func(Attr) bool) {
82         for i := 0; i < r.nFront; i++ {
83                 if !f(r.front[i]) {
84                         return
85                 }
86         }
87         for _, a := range r.back {
88                 if !f(a) {
89                         return
90                 }
91         }
92 }
93
94 // AddAttrs appends the given Attrs to the Record's list of Attrs.
95 func (r *Record) AddAttrs(attrs ...Attr) {
96         n := copy(r.front[r.nFront:], attrs)
97         r.nFront += n
98         // Check if a copy was modified by slicing past the end
99         // and seeing if the Attr there is non-zero.
100         if cap(r.back) > len(r.back) {
101                 end := r.back[:len(r.back)+1][len(r.back)]
102                 if !end.isEmpty() {
103                         panic("copies of a slog.Record were both modified")
104                 }
105         }
106         r.back = append(r.back, attrs[n:]...)
107 }
108
109 // Add converts the args to Attrs as described in [Logger.Log],
110 // then appends the Attrs to the Record's list of Attrs.
111 func (r *Record) Add(args ...any) {
112         var a Attr
113         for len(args) > 0 {
114                 a, args = argsToAttr(args)
115                 if r.nFront < len(r.front) {
116                         r.front[r.nFront] = a
117                         r.nFront++
118                 } else {
119                         if r.back == nil {
120                                 r.back = make([]Attr, 0, countAttrs(args))
121                         }
122                         r.back = append(r.back, a)
123                 }
124         }
125
126 }
127
128 // countAttrs returns the number of Attrs that would be created from args.
129 func countAttrs(args []any) int {
130         n := 0
131         for i := 0; i < len(args); i++ {
132                 n++
133                 if _, ok := args[i].(string); ok {
134                         i++
135                 }
136         }
137         return n
138 }
139
140 const badKey = "!BADKEY"
141
142 // argsToAttr turns a prefix of the nonempty args slice into an Attr
143 // and returns the unconsumed portion of the slice.
144 // If args[0] is an Attr, it returns it.
145 // If args[0] is a string, it treats the first two elements as
146 // a key-value pair.
147 // Otherwise, it treats args[0] as a value with a missing key.
148 func argsToAttr(args []any) (Attr, []any) {
149         switch x := args[0].(type) {
150         case string:
151                 if len(args) == 1 {
152                         return String(badKey, x), nil
153                 }
154                 return Any(x, args[1]), args[2:]
155
156         case Attr:
157                 return x, args[1:]
158
159         default:
160                 return Any(badKey, x), args[1:]
161         }
162 }
163
164 // Source describes the location of a line of source code.
165 type Source struct {
166         // Function is the package path-qualified function name containing the
167         // source line. If non-empty, this string uniquely identifies a single
168         // function in the program. This may be the empty string if not known.
169         Function string `json:"function"`
170         // File and Line are the file name and line number (1-based) of the source
171         // line. These may be the empty string and zero, respectively, if not known.
172         File string `json:"file"`
173         Line int    `json:"line"`
174 }
175
176 // attrs returns the non-zero fields of s as a slice of attrs.
177 // It is similar to a LogValue method, but we don't want Source
178 // to implement LogValuer because it would be resolved before
179 // the ReplaceAttr function was called.
180 func (s *Source) group() Value {
181         var as []Attr
182         if s.Function != "" {
183                 as = append(as, String("function", s.Function))
184         }
185         if s.File != "" {
186                 as = append(as, String("file", s.File))
187         }
188         if s.Line != 0 {
189                 as = append(as, Int("line", s.Line))
190         }
191         return GroupValue(as...)
192 }
193
194 // source returns a Source for the log event.
195 // If the Record was created without the necessary information,
196 // or if the location is unavailable, it returns a non-nil *Source
197 // with zero fields.
198 func (r Record) source() *Source {
199         fs := runtime.CallersFrames([]uintptr{r.PC})
200         f, _ := fs.Next()
201         return &Source{
202                 Function: f.Function,
203                 File:     f.File,
204                 Line:     f.Line,
205         }
206 }