-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlog.go
453 lines (391 loc) · 9.04 KB
/
log.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package rlog
import (
"bytes"
"fmt"
"io"
"os"
"runtime"
"strconv"
"strings"
"sync"
"time"
)
const (
EMEGR = iota
ALERT
CRIT
ERROR
WARN
NOTICE
INFO
DEBUG
TRACE
)
const (
APP_SYS = 0 << 3
APP_ADMIN = 1 << 3
APP_SEC = 13 << 3
APP_APP = 16 << 3
APP_DB = 17 << 3
APP_GAME = 18 << 3
APP_USER = 19 << 3
)
type Outputer int
const (
STD = iota
FILE
)
const (
CONSOLE = 1 << iota
LOCAL
REMOTE
)
type logger struct {
logFd *os.File
starLev int
buf []byte
path string
baseName string
logName string
debugOutputer Outputer
debugSwitch bool
callDepth int
fullPath string
lastHour int
lastDate string
IsShowConsole bool
logChan chan string
saveFlags int // Decide if save or send to remote logger centor
remoteLog *rclient
msgQueue []string
msgQueueMutex sync.Mutex
}
var gLogger *logger
var DBLogger = &gLogger
var once sync.Once
func LoggerInit(level int, saveFlag int) {
gLogger = newLogger("./logs", "", "Log4Golang", level, saveFlag)
gLogger.setCallDepth(3)
gLogger.start()
}
func EnableRemoteLog(ident string, addr string) {
if nil == gLogger {
panic("init log first")
} else {
gLogger.saveFlags |= REMOTE
if gLogger.remoteLog != nil {
gLogger.remoteLog.start(ident, addr)
} else {
gLogger.remoteLog = newRemote()
gLogger.remoteLog.start(ident, addr)
}
}
}
func newLogger(path, baseName, logName string, level int, saveFlags int) *logger {
logger := &logger{path: path, baseName: baseName, logName: logName, starLev: level}
logger.debugSwitch = true
logger.debugOutputer = STD
logger.callDepth = 3
logger.logChan = make(chan string, 8096)
logger.saveFlags = CONSOLE | saveFlags
logger.msgQueue = make([]string, 0)
if logger.saveFlags&REMOTE != 0 {
gLogger.remoteLog = newRemote()
}
return logger
}
func (this* logger) getCurDate() string{
now := time.Now()
str := now.Format("2006-01-02")
return str
}
func (this* logger) pathExists(path string)bool{
_, err := os.Stat(path)
if err == nil{
return true
}
return false
}
func (this *logger) getLoggerFd() *os.File {
curDate := this.getCurDate()
if this.lastDate != curDate{
path := strings.TrimSuffix(this.path, "/")
path = path + "/" + curDate + "/"
if !this.pathExists(path){
err := os.Mkdir(path, os.ModePerm)
if err != nil{
fmt.Println(err)
panic(err)
}
}
this.lastDate = curDate
}
var err error
path := strings.TrimSuffix(this.path, "/")
flag := os.O_WRONLY | os.O_APPEND | os.O_CREATE
this.fullPath = path + "/" + this.lastDate + "/"+ this.baseName
now := time.Now()
this.fullPath += fmt.Sprintf("%04d%02d%02d%02d.log", now.Year(), now.Month(), now.Day(), now.Hour())
this.logFd, err = os.OpenFile(this.fullPath, flag, 0666)
if err != nil {
panic(err)
}
return this.logFd
}
func (this *logger) start() {
if this.saveFlags&LOCAL != 0 {
err := os.MkdirAll(this.path, os.ModePerm)
if err != nil {
panic(err)
}
this.logFd = this.getLoggerFd()
RunCoroutine(func() {
this.autoWrite()
})
}
}
func (this *logger) writeLog(buf []byte) {
now := time.Now()
if now.Hour() != this.lastHour {
err := this.logFd.Close()
if err != nil {
str := fmt.Sprintf("close file[%v] failed[err:%v]", this.fullPath, err.Error())
fmt.Println(str)
}
this.logFd = this.getLoggerFd()
this.lastHour = now.Hour()
}
_, err := this.logFd.Write(buf)
if err != nil {
fmt.Printf("write failed, %v", err)
}
}
func (this *logger) autoWrite() {
for {
d := this.pop_front()
if d != "" {
this.writeLog(bytes.NewBufferString(d).Bytes())
} else {
time.Sleep(time.Millisecond * 20)
}
}
}
func (this *logger) output(fd io.Writer, level, prefix string, format string, v ...interface{}) (err error) {
var msg string
if format == "" {
msg = fmt.Sprintln(v...)
} else {
msg = fmt.Sprintf(format, v...)
}
this.buf = this.buf[:0]
this.buf = append(this.buf, "["+this.logName+"]"...)
this.buf = append(this.buf, level...)
this.buf = append(this.buf, prefix...)
this.buf = append(this.buf, ":"+msg...)
if len(msg) > 0 && msg[len(msg)-1] != '\n' {
this.buf = append(this.buf, '\n')
}
_, err = fd.Write(this.buf)
return nil
}
func (l *logger) setCallDepth(d int) {
l.callDepth = d
}
func (l *logger) openDebug() {
l.debugSwitch = true
}
func (l *logger) getFileLine() string {
_, file, line, ok := runtime.Caller(l.callDepth)
if !ok {
file = "???"
line = 0
}
return l.getFileName(file) + ":" + itoa(line, -1)
}
func (l *logger) getFileName(path string) string {
strArr := strings.Split(path, "/")
nLen := len(strArr)
if nLen > 0 {
return strArr[nLen-1]
}
return path
}
func itoa(i int, wid int) string {
var u uint = uint(i)
if u == 0 && wid <= 1 {
return "0"
}
// Assemble decimal in reverse order.
var b [32]byte
bp := len(b)
for ; u > 0 || wid > 0; u /= 10 {
bp--
wid--
b[bp] = byte(u%10) + '0'
}
return string(b[bp:])
}
func (l *logger) getTime() string {
// Time is yyyy-mm-dd hh:mm:ss.microsec
var buf []byte
t := time.Now()
year, month, day := t.Date()
buf = append(buf, itoa(int(year), 4)+"-"...)
buf = append(buf, itoa(int(month), 2)+"-"...)
buf = append(buf, itoa(int(day), 2)+" "...)
hour, min, sec := t.Clock()
buf = append(buf, itoa(hour, 2)+":"...)
buf = append(buf, itoa(min, 2)+":"...)
buf = append(buf, itoa(sec, 2)...)
buf = append(buf, '.')
buf = append(buf, itoa(t.Nanosecond()/1e3, 6)...)
return string(buf[:])
}
func (l *logger) closeDebug() {
l.debugSwitch = false
}
func (l *logger) setDebugOutput(o Outputer) {
l.debugOutputer = o
}
func LogTrace(appUser int, format string, v ...interface{}) error {
return gLogger.addlog(TRACE, appUser, format, v...)
}
func LogDebug(appUser int, format string, v ...interface{}) error {
return gLogger.addlog(DEBUG, appUser, format, v...)
}
func LogInfo(appUser int, format string, v ...interface{}) error {
return gLogger.addlog(INFO, appUser, format, v...)
}
func Log(format string, v ...interface{}) error {
return gLogger.addlog(INFO, APP_USER, format, v...)
}
func LogWarn(appUser int, format string, v ...interface{}) error {
return gLogger.addlog(WARN, appUser, format, v...)
}
func LogNotice(appUser int, format string, v ...interface{}) error {
return gLogger.addlog(NOTICE, appUser, format, v...)
}
func LogError(appUser int, format string, v ...interface{}) error {
return gLogger.addlog(ERROR, appUser, format, v...)
}
func LogCrit(appUser int, format string, v ...interface{}) error {
return gLogger.addlog(CRIT, appUser, format, v...)
}
func (this *logger) getLogLvlStr(logType int) string {
str := ""
switch logType {
case EMEGR:
str = "[EMEGR]"
case ALERT:
str = "[ALERT]"
case CRIT:
str = "[CRIT]"
case ERROR:
str = "[ ERR]"
case WARN:
str = "[WARN]"
case NOTICE:
str = "[NOTICE]"
case INFO:
str = "[INFO]"
case DEBUG:
str = "[DEBUG]"
case TRACE:
str = "[TRACE]"
default:
str = "[DEBUG]"
}
return str
}
func (this *logger) getAPPStr(APP int) string {
str := ""
switch APP {
case APP_SYS:
str = "[ SYS]"
case APP_ADMIN:
str = "[ADMIN]"
case APP_SEC:
str = "[ SEC]"
case APP_APP:
str = "[ APP]"
case APP_DB:
str = "[ DB]"
case APP_GAME:
str = "[ GAME]"
case APP_USER:
str = "[ USER]"
default:
break
}
return str
}
func (this *logger) GetGoID() int32 {
var buf [64]byte
n := runtime.Stack(buf[:], false)
idField := strings.Fields(strings.TrimPrefix(string(buf[:n]), "goroutine "))[0]
id, err := strconv.Atoi(idField)
if err != nil {
panic(fmt.Sprintf("cannot get goroutine id: %v", err))
}
return int32(id)
}
func (this *logger) addlog(logLev int, APP int, format string, v ...interface{}) error {
strLevel := this.getLogLvlStr(logLev)
strAPP := this.getAPPStr(APP)
strGoID := fmt.Sprintf("[%05d]", this.GetGoID())
strTime := this.getTime() + " "
strFile := "[" + this.getFileLine() + "]"
var msg string
if format == "" {
msg = fmt.Sprint(v...)
} else {
msg = fmt.Sprintf(format, v...)
}
strContent := fmt.Sprintf("%s%s%s", strGoID, strFile, msg)
strLog := fmt.Sprintf("%s%s%s%s", strTime, strLevel, strAPP, strContent)
if this.saveFlags&CONSOLE != 0 {
fmt.Println(strLog)
}
if logLev > this.starLev {
return nil
}
if this.saveFlags&REMOTE != 0 {
if this.remoteLog != nil {
this.remoteLog.put(uint64(time.Now().UnixNano()/10e5),
uint8(APP), uint8(logLev), strContent)
}
}
strLog += "\n"
// this.logChan <- strLog
this.put(strLog)
return nil
}
// func (this *logger) popLog() *string {
// str := <-this.logChan
// return &str
// }
func (this *logger) put(data string) {
lenData := len(data)
if 0 == lenData {
return
}
if lenData > max_dataLen_local{
data = data[:max_dataLen_local]
}
this.msgQueueMutex.Lock()
this.msgQueue = append(this.msgQueue, data)
if len(this.msgQueue) > max_local_queue_size {
this.msgQueue = this.msgQueue[1:]
}
this.msgQueueMutex.Unlock()
}
func (this *logger) pop_front() string {
this.msgQueueMutex.Lock()
defer this.msgQueueMutex.Unlock()
if len(this.msgQueue) > 0 {
d := this.msgQueue[0]
this.msgQueue = this.msgQueue[1:]
return d
}
return ""
}