-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloki.go
More file actions
290 lines (218 loc) · 6.01 KB
/
loki.go
File metadata and controls
290 lines (218 loc) · 6.01 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package logpush
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"strconv"
"time"
)
type LokiStream struct {
Stream map[string]string `json:"stream"`
Values []LokiStreamValue `json:"values"`
}
type LokiStreamValue struct {
Sequence int64
Timestamp time.Time
LogLine string
StructuredMetadata map[string]string
}
func (this LokiStreamValue) MarshalJSON() ([]byte, error) {
line := []any{
strconv.FormatInt(this.Timestamp.UnixNano()+this.Sequence, 10),
this.LogLine,
}
if len(this.StructuredMetadata) > 0 {
line = append(line, this.StructuredMetadata)
}
return json.Marshal(line)
}
type LokiLabelTransformer func(val string) (newKey string, newValue string)
func lokiRenameLabel(newKey string) LokiLabelTransformer {
return func(val string) (string, string) {
return newKey, val
}
}
func NewLokiWriter(lokiUrl string) (*lokiWriter, error) {
baseURL, err := url.Parse(lokiUrl)
if err != nil {
return nil, err
}
if baseURL.Host == "" {
return nil, fmt.Errorf("url host is not defined")
}
switch baseURL.Scheme {
case "":
baseURL.Scheme = "http"
case "http", "https":
break
default:
return nil, fmt.Errorf("unsupported url protocol")
}
query := baseURL.Query()
this := lokiWriter{
baseURL: url.URL{
Scheme: baseURL.Scheme,
Host: baseURL.Host,
User: baseURL.User,
},
UseStructMeta: query.Get("labels") == "struct",
ExtractLabels: map[string]LokiLabelTransformer{
"level": nil,
"ip": nil,
"remote_addr": lokiRenameLabel("ip"),
"client_ip": lokiRenameLabel("ip"),
"rid": nil,
"request_id": lokiRenameLabel("rid"),
"org": nil,
"app": nil,
"env": nil,
"environment": lokiRenameLabel("env"),
"service": nil,
"scope": nil,
},
}
if err := this.Ping(); err != nil {
return nil, fmt.Errorf("unable to connect: %s", err.Error())
}
return &this, err
}
type lokiWriter struct {
baseURL url.URL
// Use structured metadata
UseStructMeta bool
// Extract these labels when structured metadata is enabled
ExtractLabels map[string]LokiLabelTransformer
}
func (this *lokiWriter) Type() string {
return "loki"
}
func (this *lokiWriter) fetch(ctx context.Context, method string, url url.URL, headers http.Header, body io.Reader) (*http.Response, error) {
const attempts = 10
const attemptDelay = 100 * time.Millisecond
var doFetch = func() (*http.Response, error) {
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return nil, err
}
for key, values := range headers {
for _, val := range values {
req.Header.Add(key, val)
}
}
return http.DefaultClient.Do(req.WithContext(ctx))
}
var isOkayStatusCode = func(val int) bool {
return val >= http.StatusOK && val <= http.StatusIMUsed
}
var doConsumeErrorResponse = func(resp *http.Response) {
defer resp.Body.Close()
switch resp.Header.Get("content-type") {
case "application/json", "text/plain":
if body, err := io.ReadAll(resp.Body); err == nil {
slog.Debug("LOKI: API error",
slog.Int("status", resp.StatusCode),
slog.String("body", string(body)),
slog.String("remote", this.baseURL.Host))
}
default:
slog.Debug("LOKI: API error",
slog.Int("status", resp.StatusCode),
slog.String("remote", this.baseURL.Host))
}
}
var lastErr error
for idx := 0; idx < attempts && ctx.Err() == nil; idx++ {
if resp, err := doFetch(); err != nil {
slog.Debug("LOKI: API call failed",
slog.String("err", err.Error()))
lastErr = fmt.Errorf("http request: %v", err)
} else if !isOkayStatusCode(resp.StatusCode) {
doConsumeErrorResponse(resp)
switch {
// retry on server errors
case resp.StatusCode >= http.StatusInternalServerError:
lastErr = fmt.Errorf("service down with status '%d'", resp.StatusCode)
// bail on client errors
default:
return nil, fmt.Errorf("unexpected status '%d'", resp.StatusCode)
}
} else {
return resp, err
}
time.Sleep(attemptDelay)
}
return nil, lastErr
}
func (this *lokiWriter) Ping() error {
const pingTimeout = 10 * time.Second
pingUrl := this.baseURL
pingUrl.Path = "/ready"
ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
defer cancel()
resp, err := this.fetch(ctx, http.MethodGet, pingUrl, nil, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
return fmt.Errorf("unexpected status '%d'", resp.StatusCode)
}
return nil
}
func (this *lokiWriter) WriteEntry(ctx context.Context, entry LogEntry) error {
return this.WriteBatch(ctx, []LogEntry{entry})
}
func (this *lokiWriter) WriteBatch(ctx context.Context, batch []LogEntry) error {
pushUrl := this.baseURL
pushUrl.Path = "/loki/api/v1/push"
var streams []LokiStream
for idx, entry := range batch {
stream := map[string]string{}
streamVal := LokiStreamValue{
Sequence: int64(idx),
Timestamp: entry.Timestamp,
LogLine: entry.Message,
}
if !this.UseStructMeta {
for key, val := range entry.Metadata {
stream[key] = val
}
} else {
streamVal.StructuredMetadata = map[string]string{}
for key, val := range entry.Metadata {
if transform, isLabel := this.ExtractLabels[key]; isLabel {
if transform != nil {
key, val = transform(val)
}
stream[key] = val
continue
}
streamVal.StructuredMetadata[key] = val
}
}
if entry.StreamTag != "" {
stream["service_name"] = entry.StreamTag
}
stream["level"] = entry.LogLevel.String()
stream["mws_source"] = "logpush"
streams = append(streams, LokiStream{Stream: stream, Values: []LokiStreamValue{streamVal}})
}
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(map[string]any{
"streams": streams,
}); err != nil {
return fmt.Errorf("json.Marshal: %v", err)
}
headers := http.Header{}
headers.Set("Content-Type", "application/json")
resp, err := this.fetch(ctx, http.MethodPost, pushUrl, headers, &body)
if err == nil {
defer resp.Body.Close()
}
return err
}