/
zaploki.go
214 lines (179 loc) · 4.51 KB
/
zaploki.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
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
package zaploki
import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type ZapLoki interface {
Hook(e zapcore.Entry) error
Sink(u *url.URL) (zap.Sink, error)
Stop()
WithCreateLogger(zap.Config) (*zap.Logger, error)
}
type Config struct {
// Url of the loki server including http:// or https://
Url string
// BatchMaxSize is the maximum number of log lines that are sent in one request
BatchMaxSize int
// BatchMaxWait is the maximum time to wait before sending a request
BatchMaxWait time.Duration
// Labels that are added to all log lines
Labels map[string]string
Username string
Password string
}
type lokiPusher struct {
config *Config
ctx context.Context
client *http.Client
quit chan struct{}
entries chan logEntry
waitGroup sync.WaitGroup
}
type lokiPushRequest struct {
Streams []stream `json:"streams"`
}
type stream struct {
Stream map[string]string `json:"stream"`
Values [][2]string `json:"values"`
}
type logEntry struct {
Level string `json:"level"`
Timestamp float64 `json:"ts"`
Message string `json:"msg"`
Caller string `json:"caller"`
raw string
}
func New(ctx context.Context, cfg Config) ZapLoki {
c := &http.Client{}
cfg.Url = strings.TrimSuffix(cfg.Url, "/")
cfg.Url = fmt.Sprintf("%s/loki/api/v1/push", cfg.Url)
pusher := &lokiPusher{
config: &cfg,
ctx: ctx,
client: c,
quit: make(chan struct{}),
entries: make(chan logEntry),
}
pusher.waitGroup.Add(1)
go pusher.run()
return pusher
}
// Hook is a function that can be used as a zap hook to write log lines to loki
func (lp *lokiPusher) Hook(e zapcore.Entry) error {
lp.entries <- logEntry{
Level: e.Level.String(),
Timestamp: float64(e.Time.UnixMilli()),
Message: e.Message,
Caller: e.Caller.TrimmedPath(),
}
return nil
}
// Sink returns a new loki zap sink
func (lp *lokiPusher) Sink(_ *url.URL) (zap.Sink, error) {
return newSink(lp), nil
}
// Stop stops the loki pusher
func (lp *lokiPusher) Stop() {
close(lp.quit)
lp.waitGroup.Wait()
}
// WithCreateLogger creates a new zap logger with a loki sink from a zap config
func (lp *lokiPusher) WithCreateLogger(cfg zap.Config) (*zap.Logger, error) {
err := zap.RegisterSink(lokiSinkKey, lp.Sink)
if err != nil {
log.Fatal(err)
}
fullSinkKey := fmt.Sprintf("%s://", lokiSinkKey)
if cfg.OutputPaths == nil {
cfg.OutputPaths = []string{fullSinkKey}
} else {
cfg.OutputPaths = append(cfg.OutputPaths, fullSinkKey)
}
return cfg.Build()
}
func (lp *lokiPusher) run() {
var batch []logEntry
ticker := time.NewTimer(lp.config.BatchMaxWait)
defer func() {
if len(batch) > 0 {
lp.send(batch)
}
lp.waitGroup.Done()
}()
for {
select {
case <-lp.ctx.Done():
return
case <-lp.quit:
return
case entry := <-lp.entries:
batch = append(batch, entry)
if len(batch) >= lp.config.BatchMaxSize {
lp.send(batch)
batch = make([]logEntry, 0)
ticker.Reset(lp.config.BatchMaxWait)
}
case <-ticker.C:
if len(batch) > 0 {
lp.send(batch)
batch = make([]logEntry, 0)
}
ticker.Reset(lp.config.BatchMaxWait)
}
}
}
func (lp *lokiPusher) send(batch []logEntry) error {
data := lokiPushRequest{}
var logs [][2]string
for _, entry := range batch {
ts := time.Unix(int64(entry.Timestamp), 0)
v := [2]string{strconv.FormatInt(ts.UnixNano(), 10), entry.raw}
logs = append(logs, v)
}
data.Streams = append(data.Streams, stream{
Stream: lp.config.Labels,
Values: logs,
})
msg, err := json.Marshal(data)
if err != nil {
return fmt.Errorf("failed to marshal json: %w", err)
}
var buf bytes.Buffer
g := gzip.NewWriter(&buf)
if _, err := g.Write(msg); err != nil {
return fmt.Errorf("failed to gzip json: %w", err)
}
if err := g.Close(); err != nil {
return fmt.Errorf("failed to close gzip writer: %w", err)
}
req, err := http.NewRequest("POST", lp.config.Url, &buf)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Encoding", "gzip")
if lp.config.Username != "" && lp.config.Password != "" {
req.SetBasicAuth(lp.config.Username, lp.config.Password)
}
resp, err := lp.client.Do(req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("recieved unexpected response code from Loki: %s", resp.Status)
}
return nil
}