/
logger.go
95 lines (76 loc) · 1.94 KB
/
logger.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
package logger
//noinspection SpellCheckingInspection
import (
"encoding/json"
"fmt"
"os"
"github.com/sirupsen/logrus"
)
const (
timestampFormat = "2006-01-02T15:04:05.999Z"
fieldBuildHash = "buildHash"
// FieldCtx is a key of logged context
FieldCtx = "ctx"
)
// reservedFields defines all fields keys which cannot be used when
// we logging additional fields with YaaS formatter
var reservedFields = map[string]struct{}{
"hop": {},
"requestId": {},
"time": {},
"message": {},
"requestOrg": {},
"requestUser": {},
}
// Formatter is a log formatter
type Formatter struct{}
// Format formats log entry to adhere to YaaS specs
func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) {
data := make(logrus.Fields, len(entry.Data)+3)
for k, v := range entry.Data {
if shouldSkipThisField(k) {
continue
}
switch v := v.(type) {
case error:
data[k] = v.Error()
default:
data[k] = v
}
}
data["time"] = entry.Time.Format(timestampFormat)
data["message"] = entry.Message
logEntry := map[string]interface{}{
"log": data,
"level": entry.Level.String(),
}
serialized, err := json.Marshal(logEntry)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
func shouldSkipThisField(name string) bool {
// skips because is should be process by another function
if name == FieldCtx {
return true
}
// skip because this fields are reserved
_, found := reservedFields[name]
return found
}
// New creates new instance of logging apparatus.
// Logrus.Entry is returned as it's always decorated with fields.
func New(cfg *Config) *logrus.Entry {
lgr := &logrus.Logger{
Out: os.Stdout,
Formatter: new(Formatter),
Hooks: make(logrus.LevelHooks),
Level: logrus.Level(cfg.Level),
}
fields := logrus.Fields{}
if cfg.BuildHash != "" {
fields[fieldBuildHash] = cfg.BuildHash
}
return lgr.WithFields(fields)
}