-
Notifications
You must be signed in to change notification settings - Fork 1
/
BaseLogger.go
304 lines (260 loc) · 6.63 KB
/
BaseLogger.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
// © 2016-2024 Graylog, Inc.
package logger
import (
"bytes"
"compress/zlib"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/asaskevich/govalidator"
)
type baseLogger struct {
agent string
enableable bool
enabled bool
host string
queue []string
skipCompression bool
skipSubmission bool
submitFailures int64
submitSuccesses int64
url string
urlParsed *url.URL
version string
bundleSize int
msgQueue chan string
submitQueue chan strings.Builder
wg sync.WaitGroup
stop chan bool
}
// BaseLogger constructor
func newBaseLogger(_agent string, _url string, _enabled interface{}, _queue []string) *baseLogger {
usageLoggers, _ := GetUsageLoggers()
_enabled = (_enabled == nil) || (_enabled.(bool))
if _queue == nil && _url == "" {
_url = usageLoggers.UrlByDefault()
if _url == "" {
_enabled = false
}
}
var _urlParsed *url.URL
var parsingError error
//validate url when present
if _url != "" {
_urlParsed, parsingError = url.ParseRequestURI(_url)
isUrl := govalidator.IsURL(_url)
if parsingError != nil || !isUrl {
_url = ""
_urlParsed = nil
_enabled = false
}
}
_enableable := _url != "" || _queue != nil
config := usageLoggers.ConfigByDefault()
constructedBaseLogger := &baseLogger{
agent: _agent,
enableable: _enableable,
enabled: _enabled.(bool),
host: hostLookup(),
queue: _queue,
skipCompression: false,
skipSubmission: false,
submitFailures: 0,
submitSuccesses: 0,
url: _url,
urlParsed: _urlParsed,
version: versionLookup(),
bundleSize: config["BUNDLE_SIZE"],
msgQueue: make(chan string, config["MESSAGE_QUEUE_SIZE"]),
submitQueue: make(chan strings.Builder, config["BUNDLE_QUEUE_SIZE"]),
stop: make(chan bool, 1),
}
constructedBaseLogger.wg.Add(1)
go constructedBaseLogger.dispatcher()
return constructedBaseLogger
}
func (logger *baseLogger) Enable() {
logger.enabled = logger.enableable
}
func (logger *baseLogger) Disable() {
logger.enabled = false
}
func (logger *baseLogger) worker() {
defer logger.wg.Done()
work:
for {
submission, open := <-logger.submitQueue
if submission.Len() > 0 {
bundle := submission.String()
logger.submit(bundle)
}
if !open {
break work
}
}
}
func (logger *baseLogger) dispatcher() {
defer logger.wg.Done()
buffer := strings.Builder{}
autoFlush := time.NewTicker(time.Second)
logger.wg.Add(1)
go logger.worker()
dispatch:
for {
select {
case msg := <-logger.msgQueue:
if msg != "" {
if buffer.Len() < logger.bundleSize {
buffer.WriteString(msg + "\n")
} else {
buffer.WriteString(msg)
logger.submitQueue <- buffer
buffer = strings.Builder{}
}
}
case flush := <-logger.stop:
if flush {
select {
case msg, open := <-logger.msgQueue:
buffer.WriteString(msg + "\n")
if !open {
for msg := range logger.msgQueue {
buffer.WriteString(msg + "\n")
}
}
default:
}
}
if buffer.Len() != 0 {
logger.submitQueue <- buffer
}
close(logger.submitQueue)
break dispatch
case <-autoFlush.C:
if buffer.Len() != 0 {
logger.submitQueue <- buffer
buffer = strings.Builder{}
}
}
}
}
func (logger *baseLogger) ndjsonHandler(msg string) {
if msg == "" || logger.skipSubmission || !logger.Enabled() {
//do nothing
} else if logger.queue != nil {
logger.queue = append(logger.queue, msg)
atomic.AddInt64(&logger.submitSuccesses, 1)
return
} else {
logger.msgQueue <- msg
}
}
/**
* Submits JSON message to intended destination.
*/
func (logger *baseLogger) submit(msg string) {
var submitRequest *http.Request
var reqError error
if !logger.skipCompression { // Compression will not be skipped
var body bytes.Buffer
zWriter := zlib.NewWriter(&body)
b, err := zWriter.Write([]byte(msg))
if err != nil || b != len([]byte(msg)) {
log.Println("error compressing log: ", err)
atomic.AddInt64(&logger.submitFailures, 1)
return
}
err = zWriter.Close()
if err != nil {
log.Println("error closing compression writer: ", err)
atomic.AddInt64(&logger.submitFailures, 1)
return
}
submitRequest, reqError = http.NewRequest("POST", logger.url, &body)
if reqError != nil {
fmt.Printf("Error creating submit request: %s", reqError.Error())
log.Println("Error making submit request...")
atomic.AddInt64(&logger.submitFailures, 1)
return
}
submitRequest.Header.Set("Content-Encoding", "deflated")
submitRequest.Header.Set("Content-Type", "application/ndjson; charset=UTF-8")
submitRequest.Header.Set("User-Agent", "Resurface/"+logger.version+" ("+logger.agent+")")
} else { // Compression will be skipped
submitRequest, reqError = http.NewRequest("POST", logger.url, bytes.NewBuffer([]byte(msg)))
if reqError != nil {
fmt.Printf("Error creating submit request: %s", reqError.Error())
atomic.AddInt64(&logger.submitFailures, 1)
return
}
submitRequest.Header.Set("Content-Type", "application/ndjson; charset=UTF-8")
submitRequest.Header.Set("User-Agent", "Resurface/"+logger.version+" ("+logger.agent+")")
}
submitResponse, err := httpLoggerClient.Do(submitRequest)
if err != nil {
log.Println(err)
atomic.AddInt64(&logger.submitFailures, 1)
return
}
if submitResponse != nil && submitResponse.StatusCode == 204 {
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Println(err)
}
}(submitResponse.Body)
_, err := io.ReadAll(submitResponse.Body)
if err != nil {
log.Println(err)
}
atomic.AddInt64(&logger.submitSuccesses, 1)
return
} else {
if submitResponse == nil {
log.Println("Response is nil")
} else {
log.Println("Response from fluke:", submitResponse.StatusCode)
}
log.Println("An unknown error occurred")
atomic.AddInt64(&logger.submitFailures, 1)
return
}
}
func (logger *baseLogger) stopDispatcher() {
logger.Disable()
logger.stop <- true
logger.wg.Wait()
}
/**
* Returns host identifier.
* These are utility functions that can be static if this wasn't Go
*/
func hostLookup() string {
dyno, dynoIsPresent := os.LookupEnv("DYNO")
if dynoIsPresent && dyno != "" {
return dyno
}
hostName, err := os.Hostname()
if err != nil {
return "unknown"
}
return hostName
}
func versionLookup() string {
version := "3.4.0"
return version
}
func (logger *baseLogger) Enabled() bool {
usageLoggers, _ := GetUsageLoggers()
return logger.enabled && usageLoggers.IsEnabled()
}
func (logger *baseLogger) Queue() []string {
return logger.queue
}