-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsyslog.go
376 lines (309 loc) · 8.43 KB
/
syslog.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package go_logger
import (
"container/list"
"crypto/tls"
"fmt"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
)
//------------------------------------------------------------------------------
const (
severityError = 3
severityWarning = 4
severityInformational = 6
severityDebug = 7
facilityUser = 1
defaultMaxMessageQueueSize = 1024
flushTimeout = 5 * time.Second
)
//------------------------------------------------------------------------------
// SysLogOptions specifies the syslog settings to use when it is created.
type SysLogOptions struct {
// Application name to use. Defaults to the binary name.
AppName string `json:"appName,omitempty"`
// Syslog server host name.
Host string `json:"host,omitempty"`
// Syslog server port. Defaults to 514, 1468 or 6514 depending on the network protocol used.
Port uint16 `json:"port,omitempty"`
// Use TCP instead of UDP.
UseTcp bool `json:"useTcp,omitempty"`
// Uses a secure connection. Implies TCP.
UseTls bool `json:"useTls,omitempty"`
// Send messages in the new RFC 5424 format instead of the original RFC 3164 specification.
UseRFC5424 bool `json:"useRFC5424,omitempty"`
// Set the maximum amount of messages to keep in memory if connection to the server is lost.
MaxMessageQueueSize uint `json:"queueSize,omitempty"`
// Set the initial logging level to use.
Level *LogLevel `json:"level,omitempty"`
// Set the initial logging level for debug output to use.
DebugLevel *uint `json:"debugLevel,omitempty"`
// TLSConfig optionally provides a TLS configuration for use.
TlsConfig *tls.Config
}
type syslogAdapter struct {
conn net.Conn
lastWasError int32
appName string
serverAddress string
useTcp bool
tlsConfig *tls.Config
useRFC5424 bool
hostname string
pid int
mtx sync.Mutex
queue *list.List
notEmptyCond *sync.Cond
maxQueueSize uint
shutdown int32
workerDoneCh chan struct{}
globals globalOptions
}
//------------------------------------------------------------------------------
func createSysLogAdapter(opts SysLogOptions, glbOpts globalOptions) (internalLogger, error) {
if len(opts.AppName) == 0 {
var err error
// If no application name was given, use the base name of the executable.
opts.AppName, err = os.Executable()
if err != nil {
return nil, err
}
opts.AppName = filepath.Base(opts.AppName)
extLen := len(filepath.Ext(opts.AppName))
if len(opts.AppName) > extLen {
opts.AppName = opts.AppName[:(len(opts.AppName) - extLen)]
}
}
// Create Syslog adapter
lg := &syslogAdapter{
appName: opts.AppName,
useTcp: opts.UseTcp,
useRFC5424: opts.UseRFC5424,
pid: os.Getpid(),
mtx: sync.Mutex{},
queue: list.New(),
maxQueueSize: opts.MaxMessageQueueSize,
workerDoneCh: make(chan struct{}),
globals: glbOpts,
}
lg.notEmptyCond = sync.NewCond(&lg.mtx)
// Set output level based on globals or overrides
if opts.Level != nil {
lg.globals.Level = *opts.Level
lg.globals.DebugLevel = 1
}
if opts.DebugLevel != nil {
lg.globals.DebugLevel = *opts.DebugLevel
}
if opts.MaxMessageQueueSize == 0 {
lg.maxQueueSize = defaultMaxMessageQueueSize
}
if opts.UseTls {
if opts.TlsConfig != nil {
lg.tlsConfig = opts.TlsConfig.Clone()
} else {
lg.tlsConfig = &tls.Config{
MinVersion: 2,
}
}
}
// Set the server host
if len(opts.Host) > 0 {
lg.serverAddress = opts.Host
} else {
lg.serverAddress = "127.0.0.1"
}
// Set the server port
port := opts.Port
if opts.Port == 0 {
if opts.UseTcp {
if opts.UseTls {
port = 6514
} else {
port = 1468
}
} else {
port = 514
}
}
lg.serverAddress += ":" + strconv.Itoa(int(port))
// Set the client host name
lg.hostname, _ = os.Hostname()
// Create a background messenger worker
go lg.messengerWorker()
// Done
return lg, nil
}
func (lg *syslogAdapter) class() string {
return "syslog"
}
func (lg *syslogAdapter) destroy() {
// Stop worker
atomic.StoreInt32(&lg.shutdown, 1)
lg.notEmptyCond.Broadcast()
// Wait until exited
<-lg.workerDoneCh
close(lg.workerDoneCh)
// Flush queued messages
lg.flushQueue()
// Disconnect from the network
lg.disconnect()
}
func (lg *syslogAdapter) setLevel(level LogLevel, debugLevel uint) {
lg.globals.Level = level
lg.globals.DebugLevel = debugLevel
}
func (lg *syslogAdapter) logError(now time.Time, msg string, raw bool) {
if lg.globals.Level >= LogLevelError {
lg.writeString(facilityUser, severityError, now, msg, raw)
}
}
func (lg *syslogAdapter) logWarning(now time.Time, msg string, raw bool) {
if lg.globals.Level >= LogLevelWarning {
lg.writeString(facilityUser, severityWarning, now, msg, raw)
}
}
func (lg *syslogAdapter) logInfo(now time.Time, msg string, raw bool) {
if lg.globals.Level >= LogLevelInfo {
lg.writeString(facilityUser, severityInformational, now, msg, raw)
}
}
func (lg *syslogAdapter) logDebug(level uint, now time.Time, msg string, raw bool) {
if lg.globals.Level >= LogLevelDebug && lg.globals.DebugLevel >= level {
lg.writeString(facilityUser, severityDebug, now, msg, raw)
}
}
func (lg *syslogAdapter) writeString(facility int, severity int, now time.Time, msg string, _ bool) {
// Establish priority
priority := (facility * 8) + severity
// Remove or add new line depending on the transport protocol
if lg.useTcp {
if !strings.HasSuffix(msg, "\n") {
msg = msg + "\n"
}
} else {
msg = strings.TrimSuffix(msg, "\n")
}
// Format and queue the message
// NOTE: We don't need to care here about the message type because level and timestamp are in separate fields.
if !lg.useRFC5424 {
lg.queueMessage("<" + strconv.Itoa(priority) + ">" + now.Format("Jan _2 15:04:05") + " " +
lg.hostname + " " + msg)
} else {
lg.queueMessage("<" + strconv.Itoa(priority) + ">1 " + now.Format("2006-02-01T15:04:05Z") + " " +
lg.hostname + " " + lg.appName + " " + strconv.Itoa(lg.pid) + " - - " + msg)
}
}
func (lg *syslogAdapter) queueMessage(msg string) {
lg.mtx.Lock()
defer lg.mtx.Unlock()
if uint(lg.queue.Len()) > lg.maxQueueSize {
elem := lg.queue.Front()
if elem != nil {
lg.queue.Remove(elem)
}
}
lg.queue.PushBack(msg)
// Wake up worker if needed
lg.notEmptyCond.Signal()
}
func (lg *syslogAdapter) dequeueMessage() (string, bool) {
lg.mtx.Lock()
defer lg.mtx.Unlock()
for {
if atomic.LoadInt32(&lg.shutdown) != 0 {
return "", true
}
elem := lg.queue.Front()
if elem != nil {
lg.queue.Remove(elem)
return elem.Value.(string), false
}
lg.notEmptyCond.Wait()
}
}
// The messenger worker do actual message delivery. The intention of this goroutine, is to
// avoid halting the routine that sends the message if there are network issues.
func (lg *syslogAdapter) messengerWorker() {
for {
msg, quit := lg.dequeueMessage()
if quit {
lg.workerDoneCh <- struct {}{}
return
}
// Send message to server
err := lg.writeBytes([]byte(msg))
// Handle error
lg.handleError(err)
}
}
func (lg *syslogAdapter) flushQueue() {
deadline := time.Now().Add(flushTimeout)
for time.Now().Before(deadline) {
// Dequeue next message
elem := lg.queue.Front()
if elem == nil {
break // Reached the end
}
lg.queue.Remove(elem)
// Send message to server
err := lg.writeBytes([]byte(elem.Value.(string)))
if err != nil {
break // Stop on error
}
}
}
func (lg *syslogAdapter) handleError(err error) {
if err == nil {
atomic.StoreInt32(&lg.lastWasError, 0)
} else {
if atomic.CompareAndSwapInt32(&lg.lastWasError, 0, 1) && lg.globals.ErrorHandler != nil {
lg.globals.ErrorHandler(fmt.Sprintf("Unable to deliver notification to SysLog [%v]", err))
}
}
}
func (lg *syslogAdapter) connect() error {
var err error
lg.disconnect()
if lg.useTcp {
if lg.tlsConfig != nil {
lg.conn, err = tls.Dial("tcp", lg.serverAddress, lg.tlsConfig)
} else {
lg.conn, err = net.Dial("tcp", lg.serverAddress)
}
} else {
lg.conn, err = net.Dial("udp", lg.serverAddress)
}
return err
}
func (lg *syslogAdapter) disconnect() {
if lg.conn != nil {
_ = lg.conn.Close()
lg.conn = nil
}
}
func (lg *syslogAdapter) writeBytes(b []byte) error {
var err error
// Send the message if connected
if lg.conn != nil {
_, err = lg.conn.Write(b)
if err == nil {
return nil
}
}
// On error or if disconnected, try to connect
err = lg.connect()
if err == nil {
_, err = lg.conn.Write(b)
if err != nil {
lg.disconnect()
}
}
// Done
return err
}