]>
Commit | Line | Data |
---|---|---|
15c0b25d AP |
1 | package plugin |
2 | ||
3 | import ( | |
4 | "encoding/json" | |
5 | "time" | |
6 | ) | |
7 | ||
8 | // logEntry is the JSON payload that gets sent to Stderr from the plugin to the host | |
9 | type logEntry struct { | |
10 | Message string `json:"@message"` | |
11 | Level string `json:"@level"` | |
12 | Timestamp time.Time `json:"timestamp"` | |
13 | KVPairs []*logEntryKV `json:"kv_pairs"` | |
14 | } | |
15 | ||
16 | // logEntryKV is a key value pair within the Output payload | |
17 | type logEntryKV struct { | |
18 | Key string `json:"key"` | |
19 | Value interface{} `json:"value"` | |
20 | } | |
21 | ||
22 | // flattenKVPairs is used to flatten KVPair slice into []interface{} | |
23 | // for hclog consumption. | |
24 | func flattenKVPairs(kvs []*logEntryKV) []interface{} { | |
25 | var result []interface{} | |
26 | for _, kv := range kvs { | |
27 | result = append(result, kv.Key) | |
28 | result = append(result, kv.Value) | |
29 | } | |
30 | ||
31 | return result | |
32 | } | |
33 | ||
34 | // parseJSON handles parsing JSON output | |
107c1cdb | 35 | func parseJSON(input []byte) (*logEntry, error) { |
15c0b25d AP |
36 | var raw map[string]interface{} |
37 | entry := &logEntry{} | |
38 | ||
107c1cdb | 39 | err := json.Unmarshal(input, &raw) |
15c0b25d AP |
40 | if err != nil { |
41 | return nil, err | |
42 | } | |
43 | ||
44 | // Parse hclog-specific objects | |
45 | if v, ok := raw["@message"]; ok { | |
46 | entry.Message = v.(string) | |
47 | delete(raw, "@message") | |
48 | } | |
49 | ||
50 | if v, ok := raw["@level"]; ok { | |
51 | entry.Level = v.(string) | |
52 | delete(raw, "@level") | |
53 | } | |
54 | ||
55 | if v, ok := raw["@timestamp"]; ok { | |
56 | t, err := time.Parse("2006-01-02T15:04:05.000000Z07:00", v.(string)) | |
57 | if err != nil { | |
58 | return nil, err | |
59 | } | |
60 | entry.Timestamp = t | |
61 | delete(raw, "@timestamp") | |
62 | } | |
63 | ||
64 | // Parse dynamic KV args from the hclog payload. | |
65 | for k, v := range raw { | |
66 | entry.KVPairs = append(entry.KVPairs, &logEntryKV{ | |
67 | Key: k, | |
68 | Value: v, | |
69 | }) | |
70 | } | |
71 | ||
72 | return entry, nil | |
73 | } |