-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathlog_hook.go
235 lines (204 loc) · 5.33 KB
/
log_hook.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
package global
import (
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"github.com/mattn/go-colorable"
"github.com/sirupsen/logrus"
)
// LocalHook logrus本地钩子
type LocalHook struct {
lock *sync.Mutex
levels []logrus.Level // hook级别
formatter logrus.Formatter // 格式
path string // 写入path
writer io.Writer // io
}
// Levels ref: logrus/hooks.go impl Hook interface
func (hook *LocalHook) Levels() []logrus.Level {
if len(hook.levels) == 0 {
return logrus.AllLevels
}
return hook.levels
}
func (hook *LocalHook) ioWrite(entry *logrus.Entry) error {
log, err := hook.formatter.Format(entry)
if err != nil {
return err
}
_, err = hook.writer.Write(log)
if err != nil {
return err
}
return nil
}
func (hook *LocalHook) pathWrite(entry *logrus.Entry) error {
dir := filepath.Dir(hook.path)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return err
}
fd, err := os.OpenFile(hook.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o666)
if err != nil {
return err
}
defer fd.Close()
log, err := hook.formatter.Format(entry)
if err != nil {
return err
}
_, err = fd.Write(log)
return err
}
// Fire ref: logrus/hooks.go impl Hook interface
func (hook *LocalHook) Fire(entry *logrus.Entry) error {
hook.lock.Lock()
defer hook.lock.Unlock()
if hook.writer != nil {
return hook.ioWrite(entry)
}
if hook.path != "" {
return hook.pathWrite(entry)
}
return nil
}
// SetFormatter 设置日志格式
func (hook *LocalHook) SetFormatter(consoleFormatter, fileFormatter logrus.Formatter) {
hook.lock.Lock()
defer hook.lock.Unlock()
// 支持处理windows平台的console色彩
logrus.SetOutput(colorable.NewColorableStdout())
// 用于在console写出
logrus.SetFormatter(consoleFormatter)
// 用于写入文件
hook.formatter = fileFormatter
}
// SetWriter 设置Writer
func (hook *LocalHook) SetWriter(writer io.Writer) {
hook.lock.Lock()
defer hook.lock.Unlock()
hook.writer = writer
}
// SetPath 设置日志写入路径
func (hook *LocalHook) SetPath(path string) {
hook.lock.Lock()
defer hook.lock.Unlock()
hook.path = path
}
// NewLocalHook 初始化本地日志钩子实现
func NewLocalHook(args any, consoleFormatter, fileFormatter logrus.Formatter, levels ...logrus.Level) *LocalHook {
hook := &LocalHook{
lock: new(sync.Mutex),
}
hook.SetFormatter(consoleFormatter, fileFormatter)
hook.levels = append(hook.levels, levels...)
switch arg := args.(type) {
case string:
hook.SetPath(arg)
case io.Writer:
hook.SetWriter(arg)
default:
panic(fmt.Sprintf("unsupported type: %v", reflect.TypeOf(args)))
}
return hook
}
// GetLogLevel 获取日志等级
//
// 可能的值有
//
// "trace","debug","info","warn","warn","error"
func GetLogLevel(level string) []logrus.Level {
switch level {
case "trace":
return []logrus.Level{
logrus.TraceLevel, logrus.DebugLevel,
logrus.InfoLevel, logrus.WarnLevel, logrus.ErrorLevel,
logrus.FatalLevel, logrus.PanicLevel,
}
case "debug":
return []logrus.Level{
logrus.DebugLevel, logrus.InfoLevel,
logrus.WarnLevel, logrus.ErrorLevel,
logrus.FatalLevel, logrus.PanicLevel,
}
case "info":
return []logrus.Level{
logrus.InfoLevel, logrus.WarnLevel,
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel,
}
case "warn":
return []logrus.Level{
logrus.WarnLevel, logrus.ErrorLevel,
logrus.FatalLevel, logrus.PanicLevel,
}
case "error":
return []logrus.Level{
logrus.ErrorLevel, logrus.FatalLevel,
logrus.PanicLevel,
}
default:
return []logrus.Level{
logrus.InfoLevel, logrus.WarnLevel,
logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel,
}
}
}
// LogFormat specialize for go-cqhttp
type LogFormat struct {
EnableColor bool
}
// Format implements logrus.Formatter
func (f LogFormat) Format(entry *logrus.Entry) ([]byte, error) {
buf := NewBuffer()
defer PutBuffer(buf)
if f.EnableColor {
buf.WriteString(GetLogLevelColorCode(entry.Level))
}
buf.WriteByte('[')
buf.WriteString(entry.Time.Format("2006-01-02 15:04:05"))
buf.WriteString("] [")
buf.WriteString(strings.ToUpper(entry.Level.String()))
buf.WriteString("]: ")
buf.WriteString(entry.Message)
buf.WriteString(" \n")
if f.EnableColor {
buf.WriteString(colorReset)
}
ret := make([]byte, len(buf.Bytes()))
copy(ret, buf.Bytes()) // copy buffer
return ret, nil
}
const (
colorCodePanic = "\x1b[1;31m" // color.Style{color.Bold, color.Red}.String()
colorCodeFatal = "\x1b[1;31m" // color.Style{color.Bold, color.Red}.String()
colorCodeError = "\x1b[31m" // color.Style{color.Red}.String()
colorCodeWarn = "\x1b[33m" // color.Style{color.Yellow}.String()
colorCodeInfo = "\x1b[37m" // color.Style{color.White}.String()
colorCodeDebug = "\x1b[32m" // color.Style{color.Green}.String()
colorCodeTrace = "\x1b[36m" // color.Style{color.Cyan}.String()
colorReset = "\x1b[0m"
)
// GetLogLevelColorCode 获取日志等级对应色彩code
func GetLogLevelColorCode(level logrus.Level) string {
switch level {
case logrus.PanicLevel:
return colorCodePanic
case logrus.FatalLevel:
return colorCodeFatal
case logrus.ErrorLevel:
return colorCodeError
case logrus.WarnLevel:
return colorCodeWarn
case logrus.InfoLevel:
return colorCodeInfo
case logrus.DebugLevel:
return colorCodeDebug
case logrus.TraceLevel:
return colorCodeTrace
default:
return colorCodeInfo
}
}