-
Notifications
You must be signed in to change notification settings - Fork 0
/
logdeb.go
387 lines (344 loc) · 10.2 KB
/
logdeb.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
377
378
379
380
381
382
383
384
385
386
387
// Copyright 2014 Massimo Fidanza.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package logdeb
import (
"bytes"
"encoding/json"
"fmt"
"strings"
"sync"
"time"
)
const cPckName = "logdeb"
// Log severity - type tSeverity
const (
SEVFATAL = iota + 1 // fatal
SEVERROR // error
SEVWARN // warning
SEVINFO // information
SEVDEBUG // debug
)
// Debug level - type tDebLevel
const (
DLB = iota + 1 // base
DLE // extended
DLV // verbose
DLVV // very verbose
DLVVV // even more verbose
)
type tSeverity int8
type tDebLevel int8
type tFncName string
// Basic write rule
type sBaseRule struct {
Severity tSeverity `json:"sev"`
DebugLevel tDebLevel `json:"dlev"`
}
// Write rules generic and with func granularity
type sWriteRules struct {
sBaseRule
FncRules map[tFncName]sBaseRule
}
// Log message details
type SLogMsg struct {
fnc tFncName
msg string
sev tSeverity
debLev tDebLevel
}
// Writer interface
type ILogWriter interface {
Init(logger *SLogger, config map[string]interface{}) error
Write(msg SLogMsg) error
Destroy()
Flush()
}
// Writer + write rules
type SLogWriter struct {
writer ILogWriter
writeRules sWriteRules
}
type tLogWriter func() ILogWriter
var logWriters = make(map[string]tLogWriter)
// SLogger is the basic struct of deblog
type SLogger struct {
lock sync.Mutex // ensures atomic writes; protects the following fields
wg sync.WaitGroup // wait until all channels are drained
msgChan chan *SLogMsg // Channels that will dispatch the log messages
writers map[string]SLogWriter // Log writers
buf bytes.Buffer // for accumulating text to write
sBaseRule // Log Severity & DebugLevel
maxSeverity tSeverity // Maximum severity defined for writers
maxDebLev tDebLevel // Maximum debug level used by writers. Used to discard message immediately
UseFncRules bool // Define if write function rules must be used
sessionId string // Log session Id
}
// Get timestamp
func GetTsStr() string {
var t time.Time
t = time.Now()
year, month, day := t.Date()
hour, min, sec := t.Clock()
msec := t.Nanosecond() / 1e6
return fmt.Sprintf("%d%02d%02d%02d%02d%02d%03d", year, month, day, hour, min, sec, msec)
}
func getConfig(config map[string]interface{}) (confout map[string]interface{}) {
const FNAME = "getConfig"
prDeb(FNAME, "config:", config)
if len(config) > 0 {
confout = make(map[string]interface{}, len(config))
for k, v := range config {
prDeb(FNAME, "k:", k, "v:", v, "strings.Title(k):", strings.Title(k))
confout[k] = v
}
}
return
}
// Extract write rules from json config
func getWriteRules(config map[string]interface{}) sWriteRules {
prDeb("getWriteRules", "config:", config)
wr := new(sWriteRules)
wr.extract(config)
for k, v := range config {
prDeb("getWriteRules", "k:", k, "v:", v, "strings.Title(k):", strings.Title(k))
if strings.ToLower(k) == "fncrules" {
wr.FncRules = make(map[tFncName]sBaseRule)
rules := v.(map[string]interface{})
for fnc, rc := range rules {
fnc := tFncName(fnc)
r := new(sBaseRule)
r.extract(rc.(map[string]interface{}))
wr.FncRules[fnc] = *r
}
}
}
prDeb("getWriteRules", "WriteRules:", *wr)
return *wr
}
// NewLogDeb start configured writers and returns a new SLogger
// - bufferSize: is the size of channel that hold messages before sending to writers
// - config: is the configuration in JSON format. Like {"console":{"Severity":5, "DebugLevel":3}}
func NewLogDeb(bufferSize int64, config string) *SLogger {
const cFncName = cPckName + ".NewLogDeb"
l := new(SLogger)
l.SetSeverity(SEVERROR)
l.SetDebugLevel(DLB)
l.SetSessionId("GEN" + GetTsStr())
l.msgChan = make(chan *SLogMsg, bufferSize)
l.writers = make(map[string]SLogWriter)
l.wg.Add(1)
go l.StartWriter()
// Read writers and their configuration from config
var writersConf map[string]json.RawMessage
err := json.Unmarshal([]byte(config), &writersConf)
if err != nil {
panic(fmt.Sprintf("Error extracting writer config from json. ERR: %s", err))
}
l.lock.Lock()
defer l.lock.Unlock()
for wr, c := range writersConf {
if wr == "main" {
json.Unmarshal(c, &l)
if l.Severity == 0 {
l.SetSeverity(SEVERROR)
} else {
l.setMaxSeverity(l.Severity)
}
if l.DebugLevel == 0 {
l.SetDebugLevel(DLB)
} else {
l.setMaxDebugLevel(l.DebugLevel)
}
prDeb(cFncName, *l)
} else {
if logWriter, ok := logWriters[wr]; ok {
lw := logWriter()
var ci interface{}
json.Unmarshal(c, &ci)
cm := ci.(map[string]interface{})
lw.Init(l, cm)
l.writers[wr] = SLogWriter{writer: lw, writeRules: getWriteRules(cm)}
l.setMaxSeverity(l.writers[wr].writeRules.Severity)
l.setMaxDebugLevel(l.writers[wr].writeRules.DebugLevel)
} else {
panic(fmt.Sprintf("logdeb: unknown writer %q (forgotten Register?)", wr))
}
}
}
if len(l.writers) == 0 {
panic("No writer configured")
}
return l
}
// CreateWriter register a writer adapter
func CreateWriter(name string, writer tLogWriter) {
const cFncName = cPckName + ".CreateWriter"
if writer == nil {
panic(fmt.Sprintf("%s: writer %s can not be nil", cFncName, name))
}
if _, dup := logWriters[name]; dup {
panic(fmt.Sprintf("%s: writer %s already exists", cFncName, name))
}
logWriters[name] = writer
}
// SetSessionId set the log session unique identification
func (l *SLogger) SetSessionId(sessionId string) {
l.sessionId = sessionId
}
func (l *SLogger) setMaxSeverity(sev tSeverity) {
prDeb("setMaxSeverity", "sev:", sev, "maxSev:", l.maxSeverity)
if sev > l.maxSeverity {
l.maxSeverity = sev
}
}
func (l *SLogger) SetSeverity(sev tSeverity) {
l.Severity = sev
l.setMaxSeverity(sev)
}
func (l *SLogger) setMaxDebugLevel(debLev tDebLevel) {
prDeb("setMaxDebugLevel", "debLev:", debLev, "maxDebLev:", l.maxDebLev)
if debLev > l.maxDebLev {
l.maxDebLev = debLev
}
prDeb("setMaxDebugLevel", "debLev:", debLev, "maxDebLev:", l.maxDebLev)
}
func (l *SLogger) SetDebugLevel(debLev tDebLevel) {
l.DebugLevel = debLev
l.setMaxDebugLevel(debLev)
prDeb("SetDebugLevel", "debLev:", debLev, "maxDebLev:", l.maxDebLev)
}
// extract: extract base rule value from config
func (r *sBaseRule) extract(config map[string]interface{}) {
for k, v := range config {
prDeb("extract", "k:", k, "v:", v)
if strings.ToLower(k) == "sev" {
prDeb("extract", "Set Severity:", v)
r.Severity = tSeverity(v.(float64))
} else if strings.ToLower(k) == "dlev" {
prDeb("extract", "Set Debuglevel:", v)
r.DebugLevel = tDebLevel(v.(float64))
}
}
}
// get: get rule or parent rule when rule value is null
func (r sBaseRule) get(parentRule sBaseRule) sBaseRule {
if r.Severity == 0 {
r.Severity = parentRule.Severity
}
if r.DebugLevel == 0 {
r.DebugLevel = parentRule.DebugLevel
}
return r
}
// eval: evaluate the write rule and return true if the message
// is to be written
func (r sBaseRule) eval(msg SLogMsg, parentRule sBaseRule) bool {
r = r.get(parentRule)
return ((msg.sev < SEVDEBUG && msg.sev <= r.Severity) || (r.Severity == SEVDEBUG && msg.debLev <= r.DebugLevel))
}
func (l *SLogger) MustWrite(writerName string, msg SLogMsg) bool {
prDeb("MustWrite")
if l.UseFncRules && len(l.writers[writerName].writeRules.FncRules) > 0 {
// Search inside FncRules for function name matching
// or plartial matching
for {
if len(msg.fnc) == 0 {
return false
}
if rule, ok := l.writers[writerName].writeRules.FncRules[msg.fnc]; ok {
return rule.eval(msg, l.writers[writerName].writeRules.get(sBaseRule{l.Severity, l.DebugLevel}))
}
msg.fnc = msg.fnc[:len(msg.fnc)-1]
}
} else {
prDeb("MustWrite", "BaseRule", l.writers[writerName].writeRules)
return l.writers[writerName].writeRules.eval(msg, sBaseRule{l.Severity, l.DebugLevel}) // l.evalRule(msg, sBaseRule())
}
return false
}
func (l *SLogger) StartWriter() {
prDeb("StartWriter", "run")
defer l.wg.Done()
for lm := range l.msgChan {
for _, lw := range l.writers {
prDeb("StartWriter", "lw:", lw, ":: lm:", *lm)
lw.writer.Write(*lm)
}
}
}
func (l *SLogger) logw(fnc tFncName, msg string, sev tSeverity, debLev tDebLevel) error {
const cFncName = cPckName + ".logw"
prDeb(cFncName, "sev:", sev, ":: maxSeverity:", l.maxSeverity, ":: UseFncRules:", l.UseFncRules)
if !l.UseFncRules && sev > l.maxSeverity {
prDeb(cFncName, "EXIT")
return nil
}
prDeb(cFncName, "WRITE:", msg)
lm := &SLogMsg{fnc: fnc, msg: msg, sev: sev, debLev: debLev}
l.msgChan <- lm
return nil
}
func (l *SLogger) Fatal(fnc tFncName, msg string) {
l.logw(fnc, msg, SEVFATAL, 0)
}
func (l *SLogger) Err(fnc tFncName, msg string) {
l.logw(fnc, msg, SEVERROR, 0)
}
func (l *SLogger) Warn(fnc tFncName, msg string) {
l.logw(fnc, msg, SEVWARN, 0)
}
func (l *SLogger) Info(fnc tFncName, msg string) {
l.logw(fnc, msg, SEVINFO, 0)
}
// Deb: log message with severity debug
func (l *SLogger) Deb(fnc tFncName, msg string) {
l.logw(fnc, msg, SEVDEBUG, DLB)
}
// Debl: log message with severity debug and input debug level
func (l *SLogger) Debl(fnc tFncName, msg string, debLev tDebLevel) {
if debLev <= l.maxDebLev {
l.logw(fnc, msg, SEVDEBUG, debLev)
}
}
// Flush all chan data
func (l *SLogger) Flush() {
for _, lw := range l.writers {
lw.writer.Flush()
}
}
// Destroy logger, flush all chan data and destroy all writers.
func (l *SLogger) Destroy() {
close(l.msgChan)
l.wg.Wait()
for _, lw := range l.writers {
lw.writer.Flush()
lw.writer.Destroy()
}
}
func (sev tSeverity) String() string {
switch sev {
case SEVDEBUG:
return "D"
case SEVINFO:
return "I"
case SEVWARN:
return "W"
case SEVERROR:
return "E"
case SEVFATAL:
return "F"
default:
return "Unknown severity: " + string(sev)
}
}