forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloki.go
183 lines (170 loc) · 4.34 KB
/
loki.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main
import (
"bytes"
"fmt"
"os"
"sort"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/grafana/loki/pkg/promtail/client"
jsoniter "github.com/json-iterator/go"
"github.com/prometheus/common/model"
"github.com/weaveworks/common/logging"
)
type loki struct {
cfg *config
client client.Client
logger log.Logger
}
func newPlugin(cfg *config, logger log.Logger) (*loki, error) {
client, err := client.New(cfg.clientConfig, logger)
if err != nil {
return nil, err
}
return &loki{
cfg: cfg,
client: client,
logger: logger,
}, nil
}
// sendRecord send fluentbit records to loki as an entry.
func (l *loki) sendRecord(r map[interface{}]interface{}, ts time.Time) error {
records := toStringMap(r)
level.Debug(l.logger).Log("msg", "processing records", "records", fmt.Sprintf("%+v", records))
lbs := model.LabelSet{}
if l.cfg.labeMap != nil {
mapLabels(records, l.cfg.labeMap, lbs)
} else {
lbs = extractLabels(records, l.cfg.labelKeys)
}
removeKeys(records, append(l.cfg.labelKeys, l.cfg.removeKeys...))
if len(records) == 0 {
return nil
}
if l.cfg.dropSingleKey && len(records) == 1 {
for _, v := range records {
return l.client.Handle(lbs, ts, fmt.Sprintf("%v", v))
}
}
line, err := createLine(records, l.cfg.lineFormat)
if err != nil {
level.Error(l.logger).Log("msg", "error creating line", "error", err)
return nil
}
return l.client.Handle(lbs, ts, line)
}
func toStringMap(record map[interface{}]interface{}) map[string]interface{} {
m := make(map[string]interface{})
for k, v := range record {
key, ok := k.(string)
if !ok {
continue
}
switch t := v.(type) {
case []byte:
// prevent encoding to base64
m[key] = string(t)
default:
m[key] = v
}
}
return m
}
func extractLabels(records map[string]interface{}, keys []string) model.LabelSet {
res := model.LabelSet{}
for _, k := range keys {
v, ok := records[k]
if !ok {
continue
}
ln := model.LabelName(k)
// skips invalid name and values
if !ln.IsValid() {
continue
}
lv := model.LabelValue(fmt.Sprintf("%v", v))
if !lv.IsValid() {
continue
}
res[ln] = lv
}
return res
}
// mapLabels convert records into labels using a json map[string]interface{} mapping
func mapLabels(records map[string]interface{}, mapping map[string]interface{}, res model.LabelSet) {
for k, v := range mapping {
switch nextKey := v.(type) {
// if the next level is a map we are expecting we need to move deeper in the tree
case map[string]interface{}:
if nextValue, ok := records[k].(map[interface{}]interface{}); ok {
recordsMap := toStringMap(nextValue)
// recursively search through the next level map.
mapLabels(recordsMap, nextKey, res)
}
// we found a value in the mapping meaning we need to save the corresponding record value for the given key.
case string:
if value, ok := getRecordValue(k, records); ok {
lName := model.LabelName(nextKey)
lValue := model.LabelValue(value)
if lValue.IsValid() && lName.IsValid() {
res[lName] = lValue
}
}
}
}
}
func getRecordValue(key string, records map[string]interface{}) (string, bool) {
if value, ok := records[key]; ok {
switch typedVal := value.(type) {
case string:
return typedVal, true
case []byte:
return string(typedVal), true
default:
return fmt.Sprintf("%v", typedVal), true
}
}
return "", false
}
func removeKeys(records map[string]interface{}, keys []string) {
for _, k := range keys {
delete(records, k)
}
}
func createLine(records map[string]interface{}, f format) (string, error) {
switch f {
case jsonFormat:
js, err := jsoniter.Marshal(records)
if err != nil {
return "", err
}
return string(js), nil
case kvPairFormat:
buff := &bytes.Buffer{}
var keys []string
for k := range records {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
_, err := fmt.Fprintf(buff, "%s=%v ", k, records[k])
if err != nil {
return "", err
}
}
res := buff.String()
if len(records) > 0 {
return res[:len(res)-1], nil
}
return res, nil
default:
return "", fmt.Errorf("invalid line format: %v", f)
}
}
func newLogger(logLevel logging.Level) log.Logger {
logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
logger = level.NewFilter(logger, logLevel.Gokit)
logger = log.With(logger, "caller", log.Caller(3))
return logger
}