Debian Codegraph @

json_handler.go

raw symbols SCIP
1 package humanlog
2
3 import (
4 "encoding/json"
5 "fmt"
6 "math"
7 "strings"
8 "time"
9
10 "github.com/humanlogio/humanlog/internal/pkg/model"
11 )
12
13 // JSONHandler can handle logs emitted by logrus.TextFormatter loggers.
14 type JSONHandler struct {
15 Opts *HandlerOptions
16
17 Level string
18 Time time.Time
19 Message string
20 Fields map[string]string
21 }
22
23 // searchJSON searches a document for a key using the found func to determine if the value is accepted.
24 // kvs is the deserialized json document.
25 // fieldList is a list of field names that should be searched. Sub-documents can be searched by using the dot (.). For example, to search {"data"{"message": "<this field>"}} the item would be data.message
26 func searchJSON(kvs map[string]interface{}, fieldList []string, found func(key string, value interface{}) bool) bool {
27 for _, field := range fieldList {
28 splits := strings.SplitN(field, ".", 2)
29 if len(splits) > 1 {
30 name, fieldKey := splits[0], splits[1]
31 val, ok := kvs[name]
32 if !ok {
33 // the key does not exist in the document
34 continue
35 }
36 if m, ok := val.(map[string]interface{}); ok {
37 // its value is JSON and was unmarshaled to map[string]interface{} so search the sub document
38 return searchJSON(m, []string{fieldKey}, found)
39 }
40 } else {
41 // this is not a sub-document search, so search the root
42 for k, v := range kvs {
43 if field == k && found(k, v) {
44 return true
45 }
46 }
47 }
48 }
49 return false
50 }
51
52 func checkEachUntilFound(fieldList []string, found func(string) bool) bool {
53 for _, field := range fieldList {
54 if found(field) {
55 return true
56 }
57 }
58 return false
59 }
60
61 func (h *JSONHandler) clear() {
62 h.Level = ""
63 h.Time = time.Time{}
64 h.Message = ""
65 h.Fields = make(map[string]string)
66 }
67
68 // TryHandle tells if this line was handled by this handler.
69 func (h *JSONHandler) TryHandle(d []byte, out *model.Structured) bool {
70 h.clear()
71 if !h.UnmarshalJSON(d) {
72 return false
73 }
74 out.Time = h.Time
75 out.Msg = h.Message
76 out.Level = h.Level
77 for k, v := range h.Fields {
78 out.KVs = append(out.KVs, model.KV{Key: k, Value: v})
79 }
80 return true
81 }
82
83 func deleteJSONKey(key string, jsonData map[string]interface{}) {
84 if _, ok := jsonData[key]; ok {
85 // found the key at the root
86 delete(jsonData, key)
87 return
88 }
89
90 splits := strings.SplitN(key, ".", 2)
91 if len(splits) < 2 {
92 // invalid selector
93 return
94 }
95 k, v := splits[0], splits[1]
96 ifce, ok := jsonData[k]
97 if !ok {
98 return // the key doesn't exist
99 }
100 if m, ok := ifce.(map[string]interface{}); ok {
101 deleteJSONKey(v, m)
102 }
103 }
104
105 // UnmarshalJSON sets the fields of the handler.
106 func (h *JSONHandler) UnmarshalJSON(data []byte) bool {
107 raw := make(map[string]interface{})
108 err := json.Unmarshal(data, &raw)
109 if err != nil {
110 return false
111 }
112
113 searchJSON(raw, h.Opts.TimeFields, func(field string, value interface{}) bool {
114 var ok bool
115 h.Time, ok = tryParseTime(value)
116 if ok {
117 deleteJSONKey(field, raw)
118 }
119 return ok
120 })
121
122 searchJSON(raw, h.Opts.MessageFields, func(field string, value interface{}) bool {
123 var ok bool
124 h.Message, ok = value.(string)
125 if ok {
126 deleteJSONKey(field, raw)
127 }
128 return ok
129 })
130
131 searchJSON(raw, h.Opts.LevelFields, func(field string, value interface{}) bool {
132 if strLvl, ok := value.(string); ok {
133 h.Level = strLvl
134 deleteJSONKey(field, raw)
135 } else if flLvl, ok := value.(float64); ok {
136 h.Level = convertBunyanLogLevel(flLvl)
137 deleteJSONKey(field, raw)
138 } else {
139 h.Level = "???"
140 }
141 return true
142 })
143
144 if h.Fields == nil {
145 h.Fields = make(map[string]string)
146 }
147
148 for key, val := range raw {
149 switch v := val.(type) {
150 case float64:
151 if v-math.Floor(v) < 0.000001 && v < 1e9 {
152 // looks like an integer that's not too large
153 h.Fields[key] = fmt.Sprintf("%d", int(v))
154 } else {
155 h.Fields[key] = fmt.Sprintf("%g", v)
156 }
157 case string:
158 h.Fields[key] = fmt.Sprintf("%q", v)
159 default:
160 h.Fields[key] = fmt.Sprintf("%v", v)
161 }
162 }
163
164 return true
165 }
166
167 // convertBunyanLogLevel returns a human readable log level given a numerical bunyan level
168 // https://github.com/trentm/node-bunyan#levels
169 func convertBunyanLogLevel(level float64) string {
170 switch level {
171 case 10:
172 return "trace"
173 case 20:
174 return "debug"
175 case 30:
176 return "info"
177 case 40:
178 return "warn"
179 case 50:
180 return "error"
181 case 60:
182 return "fatal"
183 default:
184 return "???"
185 }
186 }