This repository has been archived by the owner on Jun 11, 2021. It is now read-only.
/
logrus.go
119 lines (98 loc) · 2.44 KB
/
logrus.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
package logger
import (
"io"
"github.com/sirupsen/logrus"
)
// Logger 定义日志别名
type Logger = logrus.Logger
// Hook 定义日志钩子别名
type Hook = logrus.Hook
// StandardLogger 获取标准日志
func StandardLogger() *Logger {
return logrus.StandardLogger()
}
// SetLevel 设定日志级别
func SetLevel(level string) {
lvl, err := logrus.ParseLevel(level)
if err != nil {
logrus.SetLevel(lvl)
}
}
// SetFormatter 设定日志输出格式
func SetFormatter(format string) {
switch format {
case "json":
logrus.SetFormatter(new(logrus.JSONFormatter))
default:
logrus.SetFormatter(new(logrus.TextFormatter))
}
}
// SetOutput 设定日志输出
func SetOutput(out io.Writer) {
logrus.SetOutput(out)
}
// AddHook 增加日志钩子
func AddHook(hook Hook) {
logrus.AddHook(hook)
}
// newEntry 新建日志元数据
func newEntry(entry *logrus.Entry) *Entry {
return &Entry{entry}
}
// newEntry 新建日志元数据
func newEntryWithFields(fields map[string]interface{}) *Entry {
return newEntry(logrus.WithFields(fields))
}
// Entry 定义统一的日志写入方式
type Entry struct {
entry *logrus.Entry
}
func (e *Entry) checkAndDelete(fields map[string]interface{}, keys ...string) {
for _, key := range keys {
_, ok := fields[key]
if ok {
delete(fields, key)
}
}
}
// WithFields 结构化字段写入
func (e *Entry) WithFields(fields map[string]interface{}) *Entry {
e.checkAndDelete(fields,
TraceIDKey,
UserIDKey,
RoleIDKey,
HostnameKey,
VersionKey,
LogVerKey,
NamespaceKey,
)
return newEntry(e.entry.WithFields(fields))
}
// WithField 结构化字段写入
func (e *Entry) WithField(key string, value interface{}) *Entry {
return e.WithFields(map[string]interface{}{key: value})
}
// Fatalf 重大错误日志
func (e *Entry) Fatalf(format string, args ...interface{}) {
e.entry.Fatalf(format, args...)
}
// Errorf 错误日志
func (e *Entry) Errorf(format string, args ...interface{}) {
e.entry.Errorf(format, args...)
}
// Warnf 警告日志
func (e *Entry) Warnf(format string, args ...interface{}) {
e.entry.Warnf(format, args...)
}
// Infof 消息日志
func (e *Entry) Infof(format string, args ...interface{}) {
e.entry.Infof(format, args...)
}
// Printf 消息日志
func (e *Entry) Printf(format string, args ...interface{}) {
e.entry.Printf(format, args...)
}
// Debugf 写入调试日志
func (e *Entry) Debugf(format string, args ...interface{}) {
e.entry.Debugf(format, args...)
}