-
Notifications
You must be signed in to change notification settings - Fork 5
/
formatter.go
92 lines (86 loc) · 2.1 KB
/
formatter.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
package log
import (
"encoding/json"
"strconv"
"time"
)
var _beijingLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
const (
fieldKeyTime = "time"
fieldKeyLevel = "level"
fieldKeyTraceId = "request_id"
fieldKeyLocation = "location"
fieldKeyMessage = "msg"
)
var stdFieldKeys = []string{
fieldKeyTime,
fieldKeyLevel,
fieldKeyTraceId,
fieldKeyLocation,
fieldKeyMessage,
}
func fixFieldsConflict(fields map[string]interface{}, fieldKeys []string) {
for _, fieldKey := range stdFieldKeys {
fieldValue, ok := fields[fieldKey]
if !ok {
continue
}
delete(fields, fieldKey)
newKey := "field." + fieldKey
for key, i := newKey, 2; ; i++ {
if _, ok = fields[key]; !ok {
fields[key] = fieldValue
break
}
key = newKey + "." + strconv.Itoa(i)
}
}
for _, fieldKey := range fieldKeys {
fieldValue, ok := fields[fieldKey]
if !ok {
continue
}
delete(fields, fieldKey)
newKey := "field." + fieldKey
for key, i := newKey, 2; ; i++ {
if _, ok = fields[key]; !ok {
fields[key] = fieldValue
break
}
key = newKey + "." + strconv.Itoa(i)
}
}
}
func fixFieldsConflictAndHandleErrorFields(fields map[string]interface{}) {
var (
errorContextFields map[string]interface{}
errorContextKeys []string
)
for k, v := range fields {
errorValue, ok := v.(error)
if !ok {
continue
}
fields[k] = errorValue.Error()
switch vv := v.(type) {
case interface{ ErrorContextJSON() json.RawMessage }:
if errorContextFields == nil {
errorContextFields = make(map[string]interface{}, 8)
}
errorContextKey := k + "_context"
errorContextFields[errorContextKey] = vv.ErrorContextJSON()
errorContextKeys = append(errorContextKeys, errorContextKey)
case interface{ ErrorContext() string }:
if errorContextFields == nil {
errorContextFields = make(map[string]interface{}, 8)
}
errorContextKey := k + "_context"
errorContextFields[errorContextKey] = vv.ErrorContext()
errorContextKeys = append(errorContextKeys, errorContextKey)
}
}
fixFieldsConflict(fields, errorContextKeys)
for k, v := range errorContextFields {
fields[k] = v
}
}