12 rotatelogs "github.com/lestrrat-go/file-rotatelogs"
13 "github.com/sirupsen/logrus"
15 "github.com/vapor/config"
19 rotationTime int64 = 86400
23 var defaultFormatter = &logrus.TextFormatter{DisableColors: true}
25 func InitLogFile(config *config.Config) error {
26 logPath := config.LogDir()
27 if err := clearLockFiles(logPath); err != nil {
31 hook := newBtmHook(logPath)
33 logrus.SetOutput(ioutil.Discard) //控制台不输出
34 fmt.Printf("all logs are output in the %s directory\n", logPath)
43 func newBtmHook(logPath string) *BtmHook {
44 hook := &BtmHook{lock: new(sync.Mutex)}
45 hook.logPath = logPath
49 // Write a log line to an io.Writer.
50 func (hook *BtmHook) ioWrite(entry *logrus.Entry) error {
52 if data, ok := entry.Data["module"]; ok {
53 module = data.(string)
56 logPath := filepath.Join(hook.logPath, module)
57 writer, err := rotatelogs.New(
59 rotatelogs.WithMaxAge(time.Duration(maxAge)*time.Second),
60 rotatelogs.WithRotationTime(time.Duration(rotationTime)*time.Second),
66 msg, err := defaultFormatter.Format(entry)
71 _, err = writer.Write(msg)
75 func clearLockFiles(logPath string) error {
76 files, err := ioutil.ReadDir(logPath)
77 if os.IsNotExist(err) {
83 for _, file := range files {
84 if ok := strings.HasSuffix(file.Name(), "_lock"); ok {
85 if err := os.Remove(filepath.Join(logPath, file.Name())); err != nil {
93 func (hook *BtmHook) Fire(entry *logrus.Entry) error {
95 defer hook.lock.Unlock()
96 return hook.ioWrite(entry)
99 // Levels returns configured log levels.
100 func (hook *BtmHook) Levels() []logrus.Level {
101 return logrus.AllLevels