-
Notifications
You must be signed in to change notification settings - Fork 0
/
rotate_log_hook.go
69 lines (58 loc) · 1.7 KB
/
rotate_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
package xlogrus
import (
"github.com/lestrrat-go/file-rotatelogs"
"github.com/sirupsen/logrus"
"io"
"path"
"time"
)
// RotateLogHook's config
type RotateLogConfig struct {
MaxAge time.Duration // default to one week
RotationTime time.Duration // default to one day
LocalTime bool // default to false (UTC)
ForceNewFile bool // force to create a new file to record log
Filepath string // log filepath
Filename string // log filename, without extension
Level logrus.Level // log level
Formatter logrus.Formatter // text formatter
}
// Write log into files (split logs to files automatically)
type RotateLogHook struct {
config *RotateLogConfig
logWriter io.Writer
}
func NewRotateLogHook(config *RotateLogConfig) logrus.Hook {
fileName := path.Join(config.Filepath, config.Filename)
options := []rotatelogs.Option{
rotatelogs.WithLinkName(fileName),
rotatelogs.WithMaxAge(config.MaxAge),
rotatelogs.WithRotationTime(config.RotationTime),
}
options = append(options, rotatelogs.WithClock(rotatelogs.UTC))
if config.LocalTime {
options = append(options, rotatelogs.WithClock(rotatelogs.Local))
}
if config.ForceNewFile {
options = append(options, rotatelogs.ForceNewFile())
}
writer, err := rotatelogs.New(fileName+".%Y%m%d.log", options...)
if err != nil {
panic(err)
}
return &RotateLogHook{
config: config,
logWriter: writer,
}
}
func (r *RotateLogHook) Levels() []logrus.Level {
return logrus.AllLevels[:r.config.Level+1]
}
func (r *RotateLogHook) Fire(entry *logrus.Entry) error {
b, err := r.config.Formatter.Format(entry)
if err != nil {
return err // unreachable
}
_, _ = r.logWriter.Write(b) // lock
return nil
}