-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.go
410 lines (351 loc) · 8.39 KB
/
logger.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package zipologger
import (
"encoding/base64"
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/MasterDimmy/errorcatcher"
"github.com/MasterDimmy/golang-lruexpire"
"github.com/MasterDimmy/zilorot"
"github.com/MasterDimmy/zipologger/enc"
)
type loggerMessage struct {
msg string
log *Logger
}
type Logger struct {
log *log.Logger
zlog *zilorot.Logger
waitStarted int32
m sync.Mutex
em sync.Mutex
encryptionKey *enc.KeyEncrypt
filename string
logMaxSizeInMB int
maxBackups int
maxAgeInDays int
alsoToStdout bool
logTasks sync.WaitGroup
limitedPrint *lru.Cache //printid - unixitime
logDateTime bool
logSourcePath bool
}
var (
tologCh = make(chan *loggerMessage, 1000)
alsoToStdout bool
initedLoggers *lru.Cache
newLoggerMutex sync.Mutex
panicMutex sync.Mutex
wMutex sync.Mutex
)
func init() {
initedLoggers, _ = lru.NewWithEvict(1000, func(key interface{}, value interface{}) {
log := value.(*Logger)
if log != nil && log.zlog != nil {
log.Flush()
log.zlog.Close()
}
})
go func() {
defer HandlePanic()
for elem := range tologCh {
elem.log.em.Lock()
if elem.log.log == nil {
elem.log.log, elem.log.zlog = newLogger(elem.log.filename, elem.log.logMaxSizeInMB, elem.log.maxBackups, elem.log.maxAgeInDays)
}
elem.log.em.Unlock()
str := elem.msg
for strings.HasSuffix(str, "\n") {
str = strings.TrimSuffix(str, "\n")
}
globalEncryptor.m.Lock()
elem.log.em.Lock()
enckey := elem.log.encryptionKey
if enckey == nil {
enckey = globalEncryptor.key
}
elem.log.em.Unlock()
globalEncryptor.m.Unlock()
if enckey != nil {
ret, err := enckey.EncryptString(str)
if err == nil {
str = base64.RawStdEncoding.EncodeToString(ret)
}
}
str = str + "\n"
elem.log.log.Print(str)
elem.log.logTasks.Done()
}
}()
}
// EmptyLogger is a logger that writes nowhere
var EmptyLogger = func() *Logger {
nowhere := &log.Logger{}
nowhere.SetOutput(io.Discard)
return &Logger{
log: nowhere,
filename: "",
}
}()
func (l *Logger) WriteSourcePath(b bool) *Logger {
l.m.Lock()
defer l.m.Unlock()
l.logSourcePath = b
return l
}
func (l *Logger) WriteDateTime(b bool) *Logger {
l.m.Lock()
defer l.m.Unlock()
l.logDateTime = b
return l
}
func (l *Logger) SetAlsoToStdout(b bool) *Logger {
l.m.Lock()
defer l.m.Unlock()
l.alsoToStdout = b
return l
}
func SetAlsoToStdout(b bool) {
alsoToStdout = b
}
func NewLogger(filename string, logMaxSizeInMB int, maxBackups int, maxAgeInDays int, writeFileline bool) *Logger {
newLoggerMutex.Lock()
defer newLoggerMutex.Unlock()
logger, ok := initedLoggers.Get(filename)
if ok {
initedLoggers.Add(filename, logger)
return logger.(*Logger)
}
p := filepath.Dir(filename)
os.MkdirAll(p, 0755)
l, _ := lru.New(1000)
log := &Logger{
filename: filename,
logMaxSizeInMB: logMaxSizeInMB,
maxBackups: maxBackups,
maxAgeInDays: maxAgeInDays,
logSourcePath: writeFileline,
limitedPrint: l,
logDateTime: true,
}
initedLoggers.Add(filename, log)
return log
}
func Wait() {
wMutex.Lock()
defer wMutex.Unlock()
for _, w := range initedLoggers.Keys() {
log, ok := initedLoggers.Get(w)
if ok {
logger := log.(*Logger)
logger.Wait()
}
}
}
func (l *Logger) Writer() io.Writer {
if l.log != nil {
return l.log.Writer()
}
return nil
}
func (l *Logger) Flush() {
l.Wait()
}
func (l *Logger) Wait() {
l.m.Lock()
defer l.m.Unlock()
atomic.StoreInt32(&l.waitStarted, 1)
l.logTasks.Wait()
atomic.StoreInt32(&l.waitStarted, 0)
}
var startCallerDepth int
var maxCallerDepth = 7
var additionalCallerDepthM sync.Mutex
func SetStartCallerDepth(a int) {
additionalCallerDepthM.Lock()
defer additionalCallerDepthM.Unlock()
startCallerDepth = a
}
func GetStartCallerDepth() int {
additionalCallerDepthM.Lock()
defer additionalCallerDepthM.Unlock()
return startCallerDepth
}
func SetMaxCallerDepth(a int) {
additionalCallerDepthM.Lock()
defer additionalCallerDepthM.Unlock()
maxCallerDepth = a
}
func GetMaxCallerDepth() int {
additionalCallerDepthM.Lock()
defer additionalCallerDepthM.Unlock()
return maxCallerDepth
}
func formatCaller(add int) string {
ret := ""
previous := ""
for i := GetMaxCallerDepth() + add; i >= 3+add; i-- {
_, file, line, ok := runtime.Caller(i)
if !ok {
file = "???"
line = 0
} else {
if !strings.HasSuffix(file, "src/testing/testing.go") {
if !strings.HasSuffix(file, "runtime/asm_amd64.s") && !strings.HasSuffix(file, "runtime/proc.go") {
t := strings.LastIndex(file, "/")
if t > 0 {
file = file[t+1:]
}
if len(ret) > 0 {
ret = ret + "=>"
}
if previous == file {
ret = ret + fmt.Sprintf(":%d", line)
} else {
ret = ret + fmt.Sprintf("%s", fmt.Sprintf("%s:%d", file, line))
}
previous = file
}
}
}
}
if len(ret) < 3 && add > 0 {
ret = formatCaller(0)
} else {
ret = ret + ": "
}
if len(ret) > 5 {
ret += "\n"
}
return ret
}
func (l *Logger) print(msg string) string {
if atomic.LoadInt32(&l.waitStarted) > 0 {
return msg
}
if l.logSourcePath {
msg = formatCaller(GetStartCallerDepth()) + msg
}
if l.logDateTime {
msg = time.Now().Format("2006/01/02 15:04:05 ") + msg
}
l.logTasks.Add(1)
tologCh <- &loggerMessage{
msg: msg,
log: l,
}
if alsoToStdout || l.alsoToStdout {
fmt.Println(msg)
}
return msg
}
func (l *Logger) Print(format string) string {
return l.print(format)
}
func (l *Logger) printf(format string, w1 interface{}, w2 ...interface{}) string {
w3 := append([]interface{}{w1}, w2...)
return l.print(fmt.Sprintf(format, w3...))
}
func (l *Logger) LimitedPrintf(printid string, duration time.Duration, format string, w1 interface{}, w2 ...interface{}) {
old, ok := l.limitedPrint.Get(printid)
if ok {
oldV := old.(time.Time)
if time.Since(oldV) < duration {
return
}
}
l.limitedPrint.Add(printid, time.Now())
l.printf(format, w1, w2...)
}
func (l *Logger) Printf(format string, w1 interface{}, w2 ...interface{}) string {
return l.printf(format, w1, w2...)
}
func (l *Logger) Println(w ...interface{}) string {
switch len(w) {
case 0:
return ""
case 1:
return l.printf("%v\n", w[0])
case 2:
return l.printf("%v %v\n", w[0], w[1])
default:
tail := strings.Repeat("%v ", len(w))
return l.printf(tail[:len(tail)-1]+"\n", w[0], w[1:]...)
}
}
func (l *Logger) Fatalf(format string, w1 interface{}, w2 ...interface{}) {
ret := l.printf(format, w1, w2...)
l.Flush()
panic(ret)
}
func HandlePanicLog(errLog *Logger, e interface{}) string {
panicMutex.Lock()
defer panicMutex.Unlock()
str := savePanicToFile(fmt.Sprintf("%s", e))
fmt.Printf("PANIC: %s\n", str)
if errLog != nil {
errLog.Printf("PANIC: %s\n", e)
}
return str
}
func Stack() string {
b := make([]byte, 1<<16)
written := runtime.Stack(b, true)
return string(b[:written])
}
func savePanicToFile(pdesc string) string {
st, _ := filepath.Abs(os.Args[0])
os.Mkdir("logs", 0777)
fn := filepath.Join(filepath.Dir(st), "logs/panic_"+filepath.Base(os.Args[0])+time.Now().Format("_2006-Jan-02_15")+".log")
f, e := os.Create(fn)
if e == nil {
defer f.Close()
_, file, line, _ := runtime.Caller(1)
str := fmt.Sprintf("Panic in [%s:%d] :\n", file, line) + pdesc + "\nSTACK:\n" + Stack()
f.WriteString(str)
return str
}
return ""
}
func newLogger(name string, logMaxSizeInMB int, maxBackups int, maxAgeInDays int) (*log.Logger, *zilorot.Logger) {
e, err := os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
os.Stderr.WriteString(fmt.Sprintf("error opening file: %v", err))
os.Exit(1)
}
logg := log.New(e, "", 0)
var output *zilorot.Logger
if logg != nil {
output = &zilorot.Logger{
Filename: name,
MaxSize: logMaxSizeInMB,
MaxBackups: maxBackups,
MaxAge: maxAgeInDays,
}
logg.SetOutput(output)
}
return logg, output
}
var ErrorCatcher *errorcatcher.System
func HandlePanic() {
if e := recover(); e != nil {
p := fmt.Sprintf("%v", e)
fmt.Printf(p)
sp := savePanicToFile(p)
if ErrorCatcher != nil {
ErrorCatcher.Send(sp)
time.Sleep(100 * time.Millisecond)
ErrorCatcher.Wait()
}
}
}
func GetLoggerBySuffix(suffix string, name string, logMaxSizeInMB int, maxBackups int, maxAgeInDays int, writeSource bool) *Logger {
return NewLogger(name+suffix, logMaxSizeInMB, maxBackups, maxAgeInDays, writeSource)
}