-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathseverity.go
69 lines (60 loc) · 1.49 KB
/
severity.go
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
package helper
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/observiq/stanza/entry"
"github.com/observiq/stanza/errors"
)
// SeverityParser is a helper that parses severity onto an entry.
type SeverityParser struct {
ParseFrom entry.Field
Preserve bool
Mapping severityMap
}
// Parse will parse severity from a field and attach it to the entry
func (p *SeverityParser) Parse(ctx context.Context, ent *entry.Entry) error {
value, ok := ent.Get(p.ParseFrom)
if !ok {
return errors.NewError(
"log entry does not have the expected parse_from field",
"ensure that all entries forwarded to this parser contain the parse_from field",
"parse_from", p.ParseFrom.String(),
)
}
severity, err := p.Mapping.find(value)
if err != nil {
return errors.Wrap(err, "parse")
}
if severity == entry.Nil {
severity = entry.Default
}
ent.Severity = severity
if !p.Preserve {
ent.Delete(p.ParseFrom)
}
return nil
}
type severityMap map[string]entry.Severity
func (m severityMap) find(value interface{}) (entry.Severity, error) {
switch v := value.(type) {
case int:
if severity, ok := m[strconv.Itoa(v)]; ok {
return severity, nil
}
return entry.Nil, nil
case string:
if severity, ok := m[strings.ToLower(v)]; ok {
return severity, nil
}
return entry.Nil, nil
case []byte:
if severity, ok := m[strings.ToLower(string(v))]; ok {
return severity, nil
}
return entry.Nil, nil
default:
return entry.Nil, fmt.Errorf("type %T cannot be a severity", v)
}
}