-
Notifications
You must be signed in to change notification settings - Fork 2
/
encoder.go
90 lines (73 loc) · 2.12 KB
/
encoder.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package rfc5424
import (
"io"
"reflect"
"time"
)
var TimeNow = time.Now
func Encode(ob interface{}) *Message {
mt := reflect.TypeOf(ob)
mv := reflect.ValueOf(ob)
reflection := Reflect(mt)
m := Message{}
severity := reflection.SeverityDefault
if reflection.SeverityFieldIndex >= 0 {
severity = mv.Field(reflection.SeverityFieldIndex).Interface().(Severity)
}
facility := reflection.FacilityDefault
if reflection.FacilityFieldIndex >= 0 {
facility = mv.Field(reflection.FacilityFieldIndex).Interface().(Facility)
}
m.Priority = int(severity-Emergency) | (int(facility-Kernel) << 3)
if reflection.TimestampFieldIndex >= 0 {
m.Timestamp = mv.Field(reflection.TimestampFieldIndex).Interface().(time.Time)
} else {
m.Timestamp = TimeNow().UTC()
}
if reflection.HostnameFieldIndex >= 0 {
m.Hostname = mv.Field(reflection.HostnameFieldIndex).Interface().(string)
} else {
m.Hostname = defaultHostname
}
if reflection.AppNameFieldIndex >= 0 {
m.AppName = mv.Field(reflection.AppNameFieldIndex).Interface().(string)
} else {
m.AppName = reflection.AppNameDefault
}
if reflection.ProcessIDFieldIndex >= 0 {
m.ProcessID = mv.Field(reflection.ProcessIDFieldIndex).String()
} else {
m.ProcessID = defaultProcessID
}
if reflection.MessageIDFieldIndex >= 0 {
m.MessageID = mv.Field(reflection.MessageIDFieldIndex).String()
}
if m.MessageID == "" {
m.MessageID = reflection.MessageIDDefault
}
for _, fieldReflection := range reflection.StructuredDataFieldReflections {
v := mv.Field(fieldReflection.FieldIndex)
if fieldReflection.OmitEmpty {
zeroValue := reflect.Zero(mt.Field(fieldReflection.FieldIndex).Type)
if zeroValue.Interface() == v.Interface() {
continue
}
}
m.AddDatum(fieldReflection.SdID, fieldReflection.FieldName, v.String())
}
if reflection.MessageFieldIndex >= 0 {
m.Message = mv.Field(reflection.MessageFieldIndex).Interface().([]byte)
}
return &m
}
type Encoder struct {
Writer io.Writer
}
func NewEncoder(w io.Writer) *Encoder {
return &Encoder{Writer: w}
}
func (e Encoder) Encode(ob interface{}) error {
m := Encode(ob)
_, err := m.WriteTo(e.Writer)
return err
}