-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloki.go
144 lines (121 loc) · 3.13 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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"github.com/nerdswords/yet-another-cloudwatch-exporter/pkg/promutil"
)
type lokiEmitter struct {
URL string `json:"url"`
OrgID string `json:"org_id"`
}
type lokiLogRow struct {
Stream map[string]string `json:"stream"`
Values [][2]string `json:"values"`
}
type lokiPayload struct {
Streams []lokiLogRow `json:"streams"`
}
func (lokiEmitter) new(options map[string]interface{}) (emitter, error) {
config := lokiEmitter{}
err := configToStruct(options, &config)
if err != nil {
return nil, err
}
// validate configuration
if config.URL == "" {
return nil, errors.New("must set a loki URL to send logs to")
}
if config.OrgID == "" {
fmt.Println("warning: no loki org id set")
}
return config, nil
}
func (s lokiEmitter) processLogBatch(batch logBatch) error {
payload := logBatchToLokiPayload(batch)
err := s.pushPayloadToLoki(payload)
if err != nil {
return err
}
return nil
}
func (s lokiEmitter) setEnvVars(config *Config) {
lokiURL := os.Getenv("LOKI_URL")
if lokiURL != "" {
config.Logging.Logger = "loki"
if config.Logging.Options == nil {
config.Logging.Options = map[string]interface{}{
"url": lokiURL,
}
} else {
config.Logging.Options["url"] = lokiURL
}
}
lokiOrgID := os.Getenv("LOKI_ORG_ID")
if lokiOrgID != "" {
config.Logging.Logger = "loki"
if config.Logging.Options == nil {
config.Logging.Options = map[string]interface{}{
"org_id": lokiOrgID,
}
} else {
config.Logging.Options["org_id"] = lokiOrgID
}
}
}
func logBatchToLokiPayload(batch logBatch) lokiPayload {
labels := map[string]string{
"aws_account": batch.accountID,
"role_arn": batch.roleARN,
"aws_region": batch.region,
"ecs_cluster": batch.cluster,
"service_name": batch.service.name,
}
// use promutil from yace to ensure tag naming consistency
for _, tag := range batch.service.tags {
_, key := promutil.PromStringTag(fmt.Sprintf("tag_%v", *tag.Key), true)
labels[key] = *tag.Value
}
var values [][2]string
for _, msg := range batch.logs {
values = append(values, [2]string{strconv.FormatInt(msg.timestamp.UnixNano(), 10), msg.msg})
}
var payloadStreams []lokiLogRow
payloadStreams = append(payloadStreams, lokiLogRow{labels, values})
return lokiPayload{payloadStreams}
}
func (s lokiEmitter) pushPayloadToLoki(payload lokiPayload) error {
jsonData, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequest("POST", s.URL, bytes.NewBuffer(jsonData))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if s.OrgID != "" {
req.Header.Set("X-Scope-OrgID", s.OrgID)
}
// Add Basic Auth credentials
//req.SetBasicAuth("username", "password")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return fmt.Errorf("error: recieved response status: %v\n%v", resp.Status, string(body))
}
return nil
}