-
Notifications
You must be signed in to change notification settings - Fork 1
/
datadog.go
276 lines (222 loc) · 7.18 KB
/
datadog.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
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
package logpet
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/sirupsen/logrus"
)
func (l *StandardLogger) SetupDataDogLogger(datadogEndpoint, datadogAPIKey, offlineLogsPath string, sendDebugLogs, localmode bool) error {
// if provided endpoint is empty we fallback to the default one
if datadogEndpoint == "" {
datadogEndpoint = DataDogDefaultEndpoint
}
if datadogAPIKey == "" && !localmode {
return fmt.Errorf("no API Key provided")
}
// initialize log channel only if it doesn't exist so we don't create multiple channels
if l.logChan == nil {
l.initChannel()
}
// offline logs path
if offlineLogsPath != "" {
l.offlineLogsPath = offlineLogsPath
l.EnableOfflineLogs(true)
}
// set debug mode with provided value
l.SetDebugMode(sendDebugLogs)
// enable local mode based on provided value
l.EnableLocalMode(localmode)
l.SetDataDogAPIKey(datadogAPIKey)
l.SetDataDogEndpoint(datadogEndpoint)
l.httpClient = &http.Client{}
// starting log routine
go l.startLogRoutineListener()
return nil
}
func (l *StandardLogger) initChannel() {
l.logChan = make(chan Log)
}
// EnableLocalMode assign the provided value to the client, if true it only prints log lines to the stdout
func (l *StandardLogger) EnableLocalMode(local bool) {
l.localMode = local
}
// SetDebugMode assign the provided value to the client, if true sends and prints to stdout debug logs
func (l *StandardLogger) SetDebugMode(debug bool) {
l.sendDebugLogs = debug
}
// SetDataDogEndpoint assign the provided datadog endpoint value to the client
func (l *StandardLogger) SetDataDogEndpoint(endpoint string) {
l.ddEndpoint = endpoint
}
// SetDataDogAPIKey assign the provided datadog API Key value to the client
func (l *StandardLogger) SetDataDogAPIKey(APIKey string) {
l.ddAPIKey = APIKey
}
// SetUpCustomHTTPClient assign the provided http client to the client
func (l *StandardLogger) SetUpCustomHTTPClient(httpClient *http.Client) error {
if httpClient != nil {
l.httpClient = httpClient
return nil
}
return errors.New("nil http client provided")
}
// SendInfoLog sends a log with info level to the log channel
func (l *StandardLogger) SendInfoLog(message string, customFields map[string]interface{}) {
go func() {
l.logChan <- Log{
Message: message,
CustomFields: customFields,
Level: logrus.InfoLevel,
}
}()
}
// SendInfofLog sends a formatted log with info level to the log channel
func (l *StandardLogger) SendInfofLog(message string, customFields map[string]interface{}, args ...interface{}) {
l.SendInfoLog(fmt.Sprintf(message, args...), customFields)
}
// SendWarnLog sends a log with warning level to the log channel
func (l *StandardLogger) SendWarnLog(message string, customFields map[string]interface{}) {
go func() {
l.logChan <- Log{
Message: message,
CustomFields: customFields,
Level: logrus.WarnLevel,
}
}()
}
// SendWarnfLog sends a formatted log with warn level to the log channel
func (l *StandardLogger) SendWarnfLog(message string, customFields map[string]interface{}, args ...interface{}) {
l.SendWarnLog(fmt.Sprintf(message, args...), customFields)
}
// SendErrLog sends a log with error level to the log channel
func (l *StandardLogger) SendErrLog(message string, customFields map[string]interface{}) {
go func() {
l.logChan <- Log{
Message: message,
CustomFields: customFields,
Level: logrus.ErrorLevel,
}
}()
}
// SendErrfLog sends a formatted log with error level to the log channel
func (l *StandardLogger) SendErrfLog(message string, customFields map[string]interface{}, args ...interface{}) {
l.SendErrLog(fmt.Sprintf(message, args...), customFields)
}
// SendDebugLog sends a log with debug level to the log channel
func (l *StandardLogger) SendDebugLog(message string, customFields map[string]interface{}) {
go func() {
l.logChan <- Log{
Message: message,
CustomFields: customFields,
Level: logrus.DebugLevel,
}
}()
}
// SendDebugfLog sends a formatted log with debug level to the log channel
func (l *StandardLogger) SendDebugfLog(message string, customFields map[string]interface{}, args ...interface{}) {
l.SendDebugLog(fmt.Sprintf(message, args...), customFields)
}
// SendFatalLog sends a log with fatal level to the log channel
func (l *StandardLogger) SendFatalLog(message string, customFields map[string]interface{}) {
func() {
l.logChan <- Log{
Message: message,
CustomFields: customFields,
Level: logrus.FatalLevel,
}
}()
}
// SendFatalfLog sends a formatted log with fatal level to the log channel
func (l *StandardLogger) SendFatalfLog(message string, customFields map[string]interface{}, args ...interface{}) {
l.SendFatalLog(fmt.Sprintf(message, args...), customFields)
}
// startLogRoutineListener handles the incoming logs
func (l *StandardLogger) startLogRoutineListener() {
var logWriter io.Writer
l.SetOutput(logWriter)
for logElem := range l.logChan {
// ignore debug log if sendDebugLog is set to false
if !l.sendDebugLogs && logElem.Level == logrus.DebugLevel {
continue
}
newLog := l.AddCustomFields()
newLog.Message = logElem.Message
newLog.Level = logElem.Level
newLog.Time = time.Now()
newLog.Data["ddsource"] = "logpet"
for key, value := range logElem.CustomFields {
newLog.Data[key] = value
}
logBytes, err := newLog.Bytes()
if err != nil {
l.SendWarnLog(fmt.Sprintf("error converting log to bytes %v", err), nil)
continue
}
// If localMode is true print the log with Println
if l.localMode {
fmt.Println(string(logBytes))
} else {
err := l.sendLogToDD(newLog, l.httpClient)
if err != nil {
log.Printf("unable to send log to DataDog, %v", err)
if l.saveOfflineLogs {
var offsaveErr error
newLog.Message = fmt.Sprintf("OFFLINE LOG at %v | %s", time.Now().String(), newLog.Message)
logBytes, offsaveErr = newLog.Bytes()
if offsaveErr != nil {
l.SendWarnLog(fmt.Sprintf("error converting log to bytes %v", offsaveErr), nil)
continue
}
offsaveErr = l.saveLogToFile(logBytes, fmt.Sprintf("log-%s.json", time.Now().Format(time.RFC3339Nano)))
if offsaveErr != nil {
fmt.Println(offsaveErr)
}
}
continue
}
}
// If it's a fatal log exit
if logElem.Level == logrus.FatalLevel {
os.Exit(1)
}
}
}
func (l *StandardLogger) sendLogToDD(log *logrus.Entry, httpClient *http.Client) error {
// obtaining byte slice from log
logBytes, err := log.Bytes()
if err != nil {
return err
}
// creating the reader from slice
body := bytes.NewReader(logBytes)
// parsing datadog endpoint URL
urlPrsd, err := url.Parse(l.ddEndpoint)
if err != nil {
return err
}
// creating new request
req, err := http.NewRequest(http.MethodPost, urlPrsd.String(), body)
if err != nil {
return err
}
// adding apikey and content type header
req.Header.Set("Content-Type", "application/json")
req.Header.Set("DD-API-KEY", l.ddAPIKey)
// doing the request
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// if not ok return an error
if resp.StatusCode != 200 {
return errors.New(fmt.Sprintf("error when sending logs to DD | Status: %s %v", resp.Status, err))
}
return nil
}