-
Notifications
You must be signed in to change notification settings - Fork 0
/
logformatter.go
110 lines (85 loc) · 2.17 KB
/
logformatter.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package servicefoundation
import (
"encoding/json"
"strconv"
"strings"
"time"
"github.com/Travix-International/logger"
"github.com/pkg/errors"
)
type (
// LogFormatter formats the log entries in a LogStash-compatible JSON string
LogFormatter interface {
Format(entry *logger.Entry) (string, error)
}
logFormatterImpl struct {
}
flatLogEntry map[string]interface{}
)
var (
errLogEntryMissingLevel = errors.New("Missing level in log entry")
errLogEntryMissingEvent = errors.New("Missing event in log entry")
)
/* LogFormatter implementation */
// NewLogFormatter instatiates a new log formatter.
func NewLogFormatter() LogFormatter {
return &logFormatterImpl{}
}
func (f *logFormatterImpl) Format(entry *logger.Entry) (string, error) {
if entry == nil {
return "", nil
}
if entry.Level == "" {
return "", errLogEntryMissingLevel
}
if entry.Event == "" {
return "", errLogEntryMissingEvent
}
var logEntry flatLogEntry = make(map[string]interface{})
logEntry["level"] = entry.Level
logEntry["type"] = "v2"
logEntry["timestamp"] = time.Now().UTC().Format("2006-01-02T15:04:05.9999999Z")
logEntry["loggername"] = "go-servicefoundation"
logEntry["messagetype"] = entry.Event
logEntry["message"] = entry.Message
if statusCode := getStatusCode(entry); statusCode != nil {
logEntry["statuscode"] = statusCode
}
if len(entry.Meta) > 0 {
logEntry["meta"] = entry.Meta
}
appendMetaEntries(entry, logEntry)
log, err := json.Marshal(logEntry)
return string(log) + "\n", err
}
func appendMetaEntries(entry *logger.Entry, logEntry flatLogEntry) {
keys := make([]string, len(entry.Meta))
i := 0
for k := range entry.Meta {
keys[i] = k
i++
}
for _, key := range keys {
if !strings.HasPrefix(key, "entry.") {
continue
}
logKey := key[6:]
logEntry[logKey] = fetchMetaEntry(entry, key)
}
}
func fetchMetaEntry(entry *logger.Entry, key string) string {
value := entry.Meta[key]
delete(entry.Meta, key)
return value
}
func getStatusCode(entry *logger.Entry) *int {
statusCode := fetchMetaEntry(entry, "entry.statusCode")
if statusCode == "" {
return nil
}
code, err := strconv.Atoi(statusCode)
if err != nil {
return nil
}
return &code
}