Debian Codegraph @

processors/minsev/severity.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package minsev // import "go.opentelemetry.io/contrib/processors/minsev"
5
6 import (
7 "encoding"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "strconv"
12 "strings"
13 "sync/atomic"
14
15 "go.opentelemetry.io/otel/log"
16 )
17
18 // Severity represents a log record severity (also known as log level). Smaller
19 // numerical values correspond to less severe log records (such as debug
20 // events), larger numerical values correspond to more severe log records (such
21 // as errors and critical events).
22 type Severity int
23
24 var (
25 // Ensure Severity implements fmt.Stringer.
26 _ fmt.Stringer = Severity(0)
27 // Ensure Severity implements json.Marshaler.
28 _ json.Marshaler = Severity(0)
29 // Ensure Severity implements json.Unmarshaler.
30 _ json.Unmarshaler = (*Severity)(nil)
31 // Ensure Severity implements encoding.TextMarshaler.
32 _ encoding.TextMarshaler = Severity(0)
33 // Ensure Severity implements encoding.TextUnmarshaler.
34 _ encoding.TextUnmarshaler = (*Severity)(nil)
35 )
36
37 // Severity values defined by OpenTelemetry.
38 const (
39 // A fine-grained debugging log record. Typically disabled in default
40 // configurations.
41 SeverityTrace1 Severity = -8 // TRACE
42 SeverityTrace2 Severity = -7 // TRACE2
43 SeverityTrace3 Severity = -6 // TRACE3
44 SeverityTrace4 Severity = -5 // TRACE4
45
46 // A debugging log record.
47 SeverityDebug1 Severity = -4 // DEBUG
48 SeverityDebug2 Severity = -3 // DEBUG2
49 SeverityDebug3 Severity = -2 // DEBUG3
50 SeverityDebug4 Severity = -1 // DEBUG4
51
52 // An informational log record. Indicates that an event happened.
53 SeverityInfo1 Severity = 0 // INFO
54 SeverityInfo2 Severity = 1 // INFO2
55 SeverityInfo3 Severity = 2 // INFO3
56 SeverityInfo4 Severity = 3 // INFO4
57
58 // A warning log record. Not an error but is likely more important than an
59 // informational event.
60 SeverityWarn1 Severity = 4 // WARN
61 SeverityWarn2 Severity = 5 // WARN2
62 SeverityWarn3 Severity = 6 // WARN3
63 SeverityWarn4 Severity = 7 // WARN4
64
65 // An error log record. Something went wrong.
66 SeverityError1 Severity = 8 // ERROR
67 SeverityError2 Severity = 9 // ERROR2
68 SeverityError3 Severity = 10 // ERROR3
69 SeverityError4 Severity = 11 // ERROR4
70
71 // A fatal log record such as application or system crash.
72 SeverityFatal1 Severity = 12 // FATAL
73 SeverityFatal2 Severity = 13 // FATAL2
74 SeverityFatal3 Severity = 14 // FATAL3
75 SeverityFatal4 Severity = 15 // FATAL4
76
77 // Convenience definitions for the base severity of each level.
78 SeverityTrace = SeverityTrace1
79 SeverityDebug = SeverityDebug1
80 SeverityInfo = SeverityInfo1
81 SeverityWarn = SeverityWarn1
82 SeverityError = SeverityError1
83 SeverityFatal = SeverityFatal1
84 )
85
86 // Severity returns the receiver translated to a [log.Severity].
87 //
88 // It implements [Severitier].
89 func (s Severity) Severity() log.Severity {
90 // Clamp to the defined range of log.Severity values. This provides a
91 // closer approximation for out-of-range values instead of returning
92 // log.SeverityUndefined.
93 switch {
94 case s < SeverityTrace1:
95 return log.SeverityTrace1
96 case s > SeverityFatal4:
97 return log.SeverityFatal4
98 }
99
100 // The relative ordering and contiguous definition of both sets of
101 // severities allows a constant offset translation instead of a lookup
102 // table. Keep this in sync if either definition changes.
103 const offset = int(log.SeverityTrace1) - int(SeverityTrace1)
104 return log.Severity(int(s) + offset)
105 }
106
107 // String returns a name for the severity level. If the severity level has a
108 // name, then that name in uppercase is returned. If the severity level is
109 // outside named values, then an signed integer is appended to the uppercased
110 // name.
111 //
112 // Examples:
113 //
114 // SeverityWarn1.String() => "WARN"
115 // (SeverityInfo1+2).String() => "INFO3"
116 // (SeverityFatal4+2).String() => "FATAL+6"
117 // (SeverityTrace1-3).String() => "TRACE-3"
118 func (s Severity) String() string {
119 str := func(base string, val Severity) string {
120 switch val {
121 case 0:
122 return base
123 case 1, 2, 3:
124 // No sign for known fine-grained severity values.
125 return fmt.Sprintf("%s%d", base, val+1)
126 }
127
128 if val > 0 {
129 // Exclude zero from positive scale count.
130 val++
131 }
132 return fmt.Sprintf("%s%+d", base, val)
133 }
134
135 switch {
136 case s < SeverityDebug1:
137 return str("TRACE", s-SeverityTrace1)
138 case s < SeverityInfo1:
139 return str("DEBUG", s-SeverityDebug1)
140 case s < SeverityWarn1:
141 return str("INFO", s-SeverityInfo1)
142 case s < SeverityError1:
143 return str("WARN", s-SeverityWarn1)
144 case s < SeverityFatal1:
145 return str("ERROR", s-SeverityError1)
146 default:
147 return str("FATAL", s-SeverityFatal1)
148 }
149 }
150
151 // MarshalJSON implements [encoding/json.Marshaler] by quoting the output of
152 // [Severity.String].
153 func (s Severity) MarshalJSON() ([]byte, error) {
154 // AppendQuote is sufficient for JSON-encoding all Severity strings. They
155 // don't contain any runes that would produce invalid JSON when escaped.
156 return strconv.AppendQuote(nil, s.String()), nil
157 }
158
159 // UnmarshalJSON implements [encoding/json.Unmarshaler] It accepts any string
160 // produced by [Severity.MarshalJSON], ignoring case. It also accepts numeric
161 // offsets that would result in a different string on output. For example,
162 // "ERROR-8" will unmarshal as [SeverityInfo].
163 func (s *Severity) UnmarshalJSON(data []byte) error {
164 str, err := strconv.Unquote(string(data))
165 if err != nil {
166 return err
167 }
168 return s.parse(str)
169 }
170
171 // AppendText implements [encoding.TextAppender] by calling [Severity.String].
172 func (s Severity) AppendText(b []byte) ([]byte, error) {
173 return append(b, s.String()...), nil
174 }
175
176 // MarshalText implements [encoding.TextMarshaler] by calling
177 // [Severity.AppendText].
178 func (s Severity) MarshalText() ([]byte, error) {
179 return s.AppendText(nil)
180 }
181
182 // UnmarshalText implements [encoding.TextUnmarshaler]. It accepts any string
183 // produced by [Severity.MarshalText], ignoring case. It also accepts numeric
184 // offsets that would result in a different string on output. For example,
185 // "ERROR-8" will marshal as [SeverityInfo].
186 func (s *Severity) UnmarshalText(data []byte) error {
187 return s.parse(string(data))
188 }
189
190 // parse parses str into s.
191 //
192 // It will return an error if str is not a valid severity string.
193 //
194 // The string is expected to be in the format of "NAME[N][+/-OFFSET]", where
195 // NAME is one of the severity names ("TRACE", "DEBUG", "INFO", "WARN",
196 // "ERROR", "FATAL"), OFFSET is an optional signed integer offset, and N is an
197 // optional fine-grained severity level that modifies the base severity name.
198 //
199 // Name is parsed in a case-insensitive way. Meaning, "info", "Info",
200 // "iNfO", etc. are all equivalent to "INFO".
201 //
202 // Fine-grained severity levels are expected to be in the range of 1 to 4,
203 // where 1 is the base severity level, and 2, 3, and 4 are more fine-grained
204 // levels. However, fine-grained levels greater than 4 are also accepted, and
205 // they will be treated as an 1-based offset from the base severity level.
206 //
207 // For example, "ERROR3" will be parsed as "ERROR" with a fine-grained level of
208 // 3, which corresponds to [SeverityError3], "FATAL+2" will be parsed as
209 // "FATAL" with an offset of +2, which corresponds to [SeverityFatal2], and
210 // "INFO2+1" is parsed as INFO with a fine-grained level of 2 and an offset of
211 // +1, which corresponds to [SeverityInfo3].
212 //
213 // Fine-grained severity levels are based on counting numbers excluding zero.
214 // If a fine-grained level of 0 is provided it is treaded as equivalent to the
215 // base severity level. For example, "INFO0" is equivalent to [SeverityInfo1].
216 func (s *Severity) parse(str string) (err error) {
217 if str == "" {
218 // Handle empty str as a special case and parse it as the default
219 // SeverityInfo1.
220 //
221 // Do not parse this below in the switch statement of the name. That
222 // will allow strings like "2", "-1", "2+1", "+3", etc. to be accepted
223 // and that adds ambiguity. For example, a user may expect that "2" is
224 // parsed as SeverityInfo2 based on an implied "SeverityInfo1" prefix,
225 // but they may also expect it be parsed as SeverityInfo3 which has a
226 // numeric value of 2. Avoid this ambiguity by treating those inputs
227 // as invalid, and only accept the empty string as a special case.
228
229 *s = SeverityInfo1 // Default severity.
230 return nil
231 }
232
233 defer func() {
234 if err != nil {
235 err = fmt.Errorf("minsev: severity string %q: %w", str, err)
236 }
237 }()
238
239 name := str
240 offset := 0
241
242 // Parse +/- offset suffix, if present.
243 if i := strings.IndexAny(str, "+-"); i >= 0 {
244 name = str[:i]
245 offset, err = strconv.Atoi(str[i:])
246 if err != nil {
247 return err
248 }
249 }
250
251 // Parse fine-grained severity level suffix, if present.
252 // This supports formats like "ERROR3", "FATAL4", etc.
253 i := len(name)
254 n, multi := 0, 1
255 for ; i > 0 && str[i-1] >= '0' && str[i-1] <= '9'; i-- {
256 n += int(str[i-1]-'0') * multi
257 multi *= 10
258 }
259 if i < len(name) {
260 name = name[:i]
261 if n != 0 {
262 offset += n - 1 // Convert 1-based to 0-based.
263 }
264 }
265
266 switch strings.ToUpper(name) {
267 case "TRACE":
268 *s = SeverityTrace1
269 case "DEBUG":
270 *s = SeverityDebug1
271 case "INFO":
272 *s = SeverityInfo1
273 case "WARN":
274 *s = SeverityWarn1
275 case "ERROR":
276 *s = SeverityError1
277 case "FATAL":
278 *s = SeverityFatal1
279 default:
280 return errors.New("unknown name")
281 }
282 *s += Severity(offset)
283 return nil
284 }
285
286 // A SeverityVar is a [Severity] variable, to allow a [LogProcessor] severity
287 // to change dynamically. It implements [Severitier] as well as a Set method,
288 // and it is safe for use by multiple goroutines.
289 //
290 // The zero SeverityVar corresponds to [SeverityInfo].
291 type SeverityVar struct {
292 val atomic.Int64
293 }
294
295 var (
296 // Ensure Severity implements fmt.Stringer.
297 _ fmt.Stringer = (*SeverityVar)(nil)
298 // Ensure Severity implements encoding.TextMarshaler.
299 _ encoding.TextMarshaler = (*SeverityVar)(nil)
300 // Ensure Severity implements encoding.TextUnmarshaler.
301 _ encoding.TextUnmarshaler = (*SeverityVar)(nil)
302 )
303
304 // Severity returns v's severity.
305 func (v *SeverityVar) Severity() log.Severity {
306 return Severity(int(v.val.Load())).Severity()
307 }
308
309 // Set sets v's Severity to l.
310 func (v *SeverityVar) Set(l Severity) {
311 v.val.Store(int64(l))
312 }
313
314 // String returns a string representation of the SeverityVar.
315 func (v *SeverityVar) String() string {
316 return fmt.Sprintf("SeverityVar(%s)", Severity(int(v.val.Load())).String())
317 }
318
319 // AppendText implements [encoding.TextAppender]
320 // by calling [Severity.AppendText].
321 func (v *SeverityVar) AppendText(b []byte) ([]byte, error) {
322 return Severity(int(v.val.Load())).AppendText(b)
323 }
324
325 // MarshalText implements [encoding.TextMarshaler]
326 // by calling [SeverityVar.AppendText].
327 func (v *SeverityVar) MarshalText() ([]byte, error) {
328 return v.AppendText(nil)
329 }
330
331 // UnmarshalText implements [encoding.TextUnmarshaler]
332 // by calling [Severity.UnmarshalText].
333 func (v *SeverityVar) UnmarshalText(data []byte) error {
334 var s Severity
335 if err := s.UnmarshalText(data); err != nil {
336 return err
337 }
338 v.Set(s)
339 return nil
340 }
341
342 // A Severitier provides a [log.Severity] value.
343 type Severitier interface {
344 Severity() log.Severity
345 }