-
Notifications
You must be signed in to change notification settings - Fork 5
/
hlog.go
471 lines (405 loc) · 11.1 KB
/
hlog.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package hlog
import (
"fmt"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"io/ioutil"
"path/filepath"
"runtime"
"strings"
"time"
)
const (
FileNameDateFormat = "%Y%m%d" // 日志文件名的默认日期格式
TimestampFormat = "2006-01-02 15:04:05" // 日志条目中的默认日期时间格式
Text = "text" // 普通文本格式日志
JSON = "json" // json格式日志
DataKey = "data" // json日志条目中 数据字段都会作为该字段的嵌入字段
FileInfoField = "call" // 文件名和行号 显示字段
)
// Level type
type Level uint32
const (
// 日志级别
PanicLevel Level = iota
FatalLevel
ErrorLevel
WarnLevel
InfoLevel
DebugLevel
)
var (
logger *Logger
fileNameDateFormat string // 日志文件名的日期格式
timestampFormat string // 日志条目中的日期时间格式
fileInfoField string // 文件名和行号 显示字段
)
// 要写入日志的数据字段
type D map[string]interface{}
type Option struct {
// log 路径
LogPath string
// 日志类型 json|text
LogType string
// 文件名的日期格式
FileNameDateFormat string
// 日志中日期时间格式
TimestampFormat string
// 日志级别
LogLevel Level
// 日志最长保存多久
MaxAge time.Duration
// 日志默认多长时间轮转一次
RotationTime time.Duration
// 是否开启记录文件名和行号
IsEnableRecordFileInfo bool
// 文件名和行号字段名
FileInfoField string
// json日志是否美化输出
JSONPrettyPrint bool
// json日志条目中 数据字段都会作为该字段的嵌入字段
JSONDataKey string
}
type Logger struct {
logrus *logrus.Logger
enableRecordFileinfo bool
}
func GetLogger() *Logger {
return logger
}
func newLogger(option *Option) (*logrus.Logger, error) {
var (
err error
logrusLogger *logrus.Logger
)
if err = makeDirAll(option.LogPath); err != nil {
return nil, err
}
if option.FileNameDateFormat == "" {
fileNameDateFormat = FileNameDateFormat
} else {
fileNameDateFormat = option.FileNameDateFormat
}
if option.TimestampFormat == "" {
timestampFormat = TimestampFormat
} else {
timestampFormat = option.TimestampFormat
}
if option.FileInfoField == "" {
fileInfoField = FileInfoField
} else {
fileInfoField = option.FileInfoField
}
logrusLogger = logrus.New()
logrusLogger.SetOutput(ioutil.Discard)
logrusLogger.Level = logrus.Level(option.LogLevel)
switch option.LogType {
case JSON:
format := &logrus.JSONFormatter{
TimestampFormat: timestampFormat,
PrettyPrint: option.JSONPrettyPrint,
}
if option.JSONDataKey != "" {
format.DataKey = option.JSONDataKey
}
logrusLogger.Formatter = format
default:
logrusLogger.Formatter = &logrus.TextFormatter{
TimestampFormat: timestampFormat,
}
}
return logrusLogger, nil
}
// New 返回Logger
// 日志类型是: 普通文本日志|JSON日志 全部级别都写入到同一个文件
func New(option *Option) (*Logger, error) {
var (
err error
logrusLogger *logrus.Logger
writer *rotatelogs.RotateLogs
fileHook *lfshook.LfsHook
absPath string
)
if logrusLogger, err = newLogger(option); err != nil {
return nil, err
}
if isWindow() {
writer, err = rotatelogs.New(
fmt.Sprintf("%s-%s", option.LogPath, fileNameDateFormat),
rotatelogs.WithMaxAge(option.MaxAge),
rotatelogs.WithRotationTime(option.RotationTime),
)
} else {
absPath, err = filepath.Abs(option.LogPath)
if err != nil {
return nil, fmt.Errorf("rotatelogs.New error: %s", err)
}
writer, err = rotatelogs.New(
fmt.Sprintf("%s-%s", absPath, fileNameDateFormat),
rotatelogs.WithMaxAge(option.MaxAge),
rotatelogs.WithRotationTime(option.RotationTime),
rotatelogs.WithLinkName(absPath),
)
}
if err != nil {
return nil, err
}
fileHook = lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: writer,
logrus.InfoLevel: writer,
logrus.WarnLevel: writer,
logrus.ErrorLevel: writer,
logrus.FatalLevel: writer,
logrus.PanicLevel: writer,
}, logrusLogger.Formatter)
logrusLogger.Hooks.Add(fileHook)
logger = &Logger{
logrus: logrusLogger,
enableRecordFileinfo: option.IsEnableRecordFileInfo,
}
return logger, nil
}
func newRotatelog(option *Option, levelStr string) (*rotatelogs.RotateLogs, error) {
var (
err error
filename string
writer *rotatelogs.RotateLogs
absPath string
)
filename = fmt.Sprintf("%s.%s", option.LogPath, levelStr)
if isWindow() {
writer, err = rotatelogs.New(
fmt.Sprintf("%s.%s", filename, fileNameDateFormat),
rotatelogs.WithMaxAge(option.MaxAge),
rotatelogs.WithRotationTime(option.RotationTime),
)
} else {
absPath, err = filepath.Abs(filename)
if err != nil {
return nil, fmt.Errorf("rotatelogs.New error: %s", err)
}
writer, err = rotatelogs.New(
fmt.Sprintf("%s.%s", absPath, fileNameDateFormat),
rotatelogs.WithMaxAge(option.MaxAge),
rotatelogs.WithRotationTime(option.RotationTime),
rotatelogs.WithLinkName(absPath),
)
}
if err != nil {
return nil, fmt.Errorf("rotatelogs.New error: %s", err)
}
return writer, nil
}
// NewSeparate 不同级别的日志输出到不同的文件
func NewSeparate(option *Option) (*Logger, error) {
var (
err error
logrusLogger *logrus.Logger
debugWriter *rotatelogs.RotateLogs
infoWriter *rotatelogs.RotateLogs
warnWriter *rotatelogs.RotateLogs
errorWriter *rotatelogs.RotateLogs
fatalWriter *rotatelogs.RotateLogs
panicWriter *rotatelogs.RotateLogs
fileHook *lfshook.LfsHook
)
if logrusLogger, err = newLogger(option); err != nil {
return nil, err
}
if debugWriter, err = newRotatelog(option, "debug"); err != nil {
return nil, err
}
if infoWriter, err = newRotatelog(option, "info"); err != nil {
return nil, err
}
if warnWriter, err = newRotatelog(option, "warn"); err != nil {
return nil, err
}
if errorWriter, err = newRotatelog(option, "error"); err != nil {
return nil, err
}
if fatalWriter, err = newRotatelog(option, "fatal"); err != nil {
return nil, err
}
if panicWriter, err = newRotatelog(option, "panic"); err != nil {
return nil, err
}
fileHook = lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: debugWriter, // 为不同级别设置不同的输出目的
logrus.InfoLevel: infoWriter,
logrus.WarnLevel: warnWriter,
logrus.ErrorLevel: errorWriter,
logrus.FatalLevel: fatalWriter,
logrus.PanicLevel: panicWriter,
}, logrusLogger.Formatter)
logrusLogger.Hooks.Add(fileHook)
logger = &Logger{
logrus: logrusLogger,
enableRecordFileinfo: option.IsEnableRecordFileInfo,
}
return logger, nil
}
func (l *Logger) Debug(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if l.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
l.logrus.WithFields(logrus.Fields(dataFields)).Debug(message)
}
func (l *Logger) Info(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if l.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
l.logrus.WithFields(logrus.Fields(dataFields)).Info(message)
}
func (l *Logger) Warn(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if l.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
l.logrus.WithFields(logrus.Fields(dataFields)).Warn(message)
}
func (l *Logger) Error(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if l.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
l.logrus.WithFields(logrus.Fields(dataFields)).Error(message)
}
func (l *Logger) Fatal(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if l.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
l.logrus.WithFields(logrus.Fields(dataFields)).Fatal(message)
}
func (l *Logger) Panic(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if l.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
l.logrus.WithFields(logrus.Fields(dataFields)).Panic(message)
}
func Debug(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if logger.logrus == nil {
logrus.Debug(dataFields, message)
return
}
if logger.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
logger.logrus.WithFields(logrus.Fields(dataFields)).Debug(message)
}
func Info(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if logger.logrus == nil {
logrus.Info(dataFields, message)
return
}
if logger.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
logger.logrus.WithFields(logrus.Fields(dataFields)).Info(message)
}
func Warn(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if logger.logrus == nil {
logrus.Warn(dataFields, message)
return
}
if logger.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
logger.logrus.WithFields(logrus.Fields(dataFields)).Warn(message)
}
func Error(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if logger.logrus == nil {
logrus.Error(dataFields, message)
return
}
if logger.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
logger.logrus.WithFields(logrus.Fields(dataFields)).Error(message)
}
func Fatal(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if logger.logrus == nil {
logrus.Fatal(dataFields, message)
return
}
if logger.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
logger.logrus.WithFields(logrus.Fields(dataFields)).Fatal(message)
}
func Panic(dataFields D, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
if dataFields == nil {
dataFields = D{}
}
if logger.logrus == nil {
logrus.Panic(dataFields, message)
return
}
if logger.enableRecordFileinfo {
dataFields[fileInfoField] = fileInfo(2)
}
logger.logrus.WithFields(logrus.Fields(dataFields)).Panic(message)
}
func StderrFatalf(format string, args ...interface{}) {
logrus.Fatalf(format, args...)
}
func Print(format string, args ...interface{}) {
fmt.Printf(fmt.Sprintf("%s => %s\n", getNowDateTime(), format), args...)
}
func fileInfo(skip int) string {
_, file, line, ok := runtime.Caller(skip)
if !ok {
file = "<???>"
line = 1
} else {
slash := strings.LastIndex(file, "/")
if slash >= 0 {
file = file[slash+1:]
}
}
return fmt.Sprintf("%s:%d", file, line)
}