-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlog.go
More file actions
340 lines (287 loc) · 7.97 KB
/
log.go
File metadata and controls
340 lines (287 loc) · 7.97 KB
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
// ---------------------------------------------------------------------------
//
// log.go
//
// Copyright (c) 2015, Jared Chavez.
// All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//
// -----------
package srvApp
import (
"fmt"
"sort"
"sync"
"time"
"github.com/xaevman/crash"
"github.com/xaevman/log"
"github.com/xaevman/log/flog"
"github.com/xaevman/trace"
)
// logShutdownChan is used to signal the log rotator goroutine
// to exit cleanly.
var logShutdownChan = make(chan chan interface{}, 0)
var logRotateChan = make(chan interface{}, 0)
// LogService represents a named collection of related LogNotify objects
// within a SrvLog and maintains the enabled flag for that named log.
type LogService struct {
enabled bool
notifiers []log.LogNotify
}
// SrvLog contains helper functions which distribute log messages
// between separate debug, info, and error log objects.
type SrvLog struct {
lock sync.RWMutex
subs map[string]*LogService
fields map[string]interface{}
}
// NewSrvLog returns a new instance of a SrvLog object.
func NewSrvLog() *SrvLog {
obj := &SrvLog{
subs: make(map[string]*LogService),
fields: make(map[string]interface{}),
}
obj.AddLog("debug", logBuffer)
obj.AddLog("error", logBuffer)
obj.AddLog("info", logBuffer)
fileLog := flog.New("all", logDir, flog.BufferedFile)
obj.AddLog("debug", fileLog)
obj.AddLog("error", fileLog)
obj.AddLog("info", fileLog)
return obj
}
// AddLog
func (this *SrvLog) AddLog(name string, newLog log.LogNotify) {
this.lock.Lock()
defer this.lock.Unlock()
logger, exists := this.subs[name]
if !exists {
logger = &LogService{
enabled: true,
notifiers: make([]log.LogNotify, 0, 1),
}
this.subs[name] = logger
}
logger.notifiers = append(logger.notifiers, newLog)
}
// Close closes the debug, err, and info flog instances.
func (this *SrvLog) Close() {
this.lock.RLock()
defer this.lock.RUnlock()
for k := range this.subs {
for i := range this.subs[k].notifiers {
l, isLogCloser := this.subs[k].notifiers[i].(log.LogCloser)
if isLogCloser {
l.Close()
}
}
}
}
// FileLogBufferSizeB returns the current capacity of the underlying memory
// buffer set aside for the file log
func (this *SrvLog) FileLogBufferCap() int {
this.lock.RLock()
defer this.lock.RUnlock()
totalCap := 0
logBuffers := make(map[*flog.BufferedLog]interface{})
for k := range this.subs {
for i := range this.subs[k].notifiers {
l, isBufferedLog := this.subs[k].notifiers[i].(*flog.BufferedLog)
if isBufferedLog {
_, exists := logBuffers[l]
if exists {
continue
}
logBuffers[l] = nil
totalCap += l.BufferCap()
}
}
}
return totalCap
}
// Debug is a proxy which passes its arguments along to the underlying
// debug flog instance.
func (this *SrvLog) Debug(format string, v ...interface{}) {
this.LogTo(false, "debug", format, v...)
}
// Error is a proxy which passes its arguments along to the underlying
// error flog instance.
func (this *SrvLog) Error(format string, v ...interface{}) {
this.LogTo(false, "error", format, v...)
}
// Info is a proxy which passes its arguments along to the underlying
// info flog instance.
func (this *SrvLog) Info(format string, v ...interface{}) {
this.LogTo(false, "info", format, v...)
}
// Debug is a proxy which passes its arguments along to the underlying
// debug flog instance.
func (this *SrvLog) DebugLocal(format string, v ...interface{}) {
this.LogTo(true, "debug", format, v...)
}
// Error is a proxy which passes its arguments along to the underlying
// error flog instance.
func (this *SrvLog) ErrorLocal(format string, v ...interface{}) {
this.LogTo(true, "error", format, v...)
}
// Info is a proxy which passes its arguments along to the underlying
// info flog instance.
func (this *SrvLog) InfoLocal(format string, v ...interface{}) {
this.LogTo(true, "info", format, v...)
}
// LogTo logs to the registered loggers with the specified key, using
// the supplied formatting string and arguments.
func (this *SrvLog) LogTo(local bool, name, format string, v ...interface{}) {
msg := log.NewLogMsg(name, format, 3, v...)
this.lock.RLock()
defer this.lock.RUnlock()
logs, exists := this.subs[name]
if !exists {
srvLog.Error("Couldn't log to %s logs. Loggers missing.", name)
return
}
if !logs.enabled {
return
}
// append fields to the message
fieldCount := len(this.fields)
if fieldCount > 0 {
keys := make([]string, 0, fieldCount)
for key := range this.fields {
keys = append(keys, key)
}
sort.Strings(keys)
for index, key := range keys {
if index > 0 {
msg.Message += ","
}
msg.Message += fmt.Sprintf(" %s=%+v", key, this.fields[key])
}
}
for i := range logs.notifiers {
logs.notifiers[i].Print(msg)
}
}
// Rotate runs flog.Rotate() on underlying BufferedLog instances
func (this *SrvLog) Rotate() error {
this.lock.Lock()
defer this.lock.Unlock()
rotated := make(map[*flog.BufferedLog]*flog.BufferedLog)
for k := range this.subs {
for i := range this.subs[k].notifiers {
oldLog, isBuffered := this.subs[k].notifiers[i].(*flog.BufferedLog)
if isBuffered {
newLog, alreadyRotated := rotated[oldLog]
if alreadyRotated {
this.subs[k].notifiers[i] = newLog
} else {
tmp, ok := flog.Rotate(oldLog).(*flog.BufferedLog)
if !ok {
return fmt.Errorf(
"failed to rotate log %s.%d. Unexpected type: %#v",
k,
i,
tmp,
)
}
this.subs[k].notifiers[i] = tmp
rotated[oldLog] = tmp
}
}
}
}
return nil
}
// SetDebugFlushIntervalSec sets the flush interval for the named log.
func (this *SrvLog) SetFlushIntervalSec(name string, interval int32) {
this.lock.RLock()
defer this.lock.RUnlock()
logs, exists := this.subs[name]
if !exists {
srvLog.Error(
"Couldn't change flush interval on %s logs. Loggers missing",
name,
)
return
}
for i := range logs.notifiers {
dbgLog, isBuffered := logs.notifiers[i].(*flog.BufferedLog)
if isBuffered {
dbgLog.SetFlushIntervalSec(interval)
}
}
}
// SetDebugLogs enables or disables named logs.
func (this *SrvLog) SetLogsEnabled(name string, val bool) {
this.lock.RLock()
defer this.lock.RUnlock()
logs, exists := this.subs[name]
if !exists {
srvLog.Error(
"Couldn't set enabled (%t) on %s logs. Loggers missing",
val,
name,
)
return
}
logs.enabled = val
}
// WithField stores a key, value pair in the logger that will be included in all subsquent logs.
func (this *SrvLog) WithField(key string, value interface{}) *SrvLog {
return this.WithFields(map[string]interface{}{
key: value,
})
}
// WithFields stores all the given key, value pairs in the logger that will be includeded in all subsequent logs.
func (this *SrvLog) WithFields(fields map[string]interface{}) *SrvLog {
this.lock.RLock()
defer this.lock.RUnlock()
newSubs := make(map[string]*LogService)
for key, val := range this.subs {
newSubs[key] = val
}
newFields := make(map[string]interface{})
for key, val := range this.fields {
newFields[key] = val
}
for key, val := range fields {
newFields[key] = val
}
derived := &SrvLog{
subs: newSubs,
fields: newFields,
}
return derived
}
// closeLogs signals the log loop to cleanly close log files and exit
func closeLogs() {
shutdownComplete := make(chan interface{}, 0)
logShutdownChan <- shutdownComplete
<-shutdownComplete
}
// initLogs runs a continuous loop, handling log initialization on startup,
// and then rotating logs once per day. The loop is broken once a shutdown
// signal is received on the logShutdownChan channel.
func initLogs() {
logBuffer = log.NewLogBuffer(DefaultHttpLogBuffers)
srvLog = NewSrvLog()
trace.DebugLogger = srvLog
trace.ErrorLogger = srvLog
go func() {
defer crash.HandleAll()
for {
select {
case shutdownComplete := <-logShutdownChan:
srvLog.Close()
shutdownComplete <- nil
return
case <-time.After(24 * time.Hour):
srvLog.Rotate()
case <-logRotateChan:
srvLog.Rotate()
}
}
}()
}