OSDN Git Service

43bcc9ca29d10db7006b63a732425f973fbed3d7
[bytom/vapor.git] / log / log.go
1 package log
2
3 import (
4         "path/filepath"
5         "sync"
6         "time"
7
8         rotatelogs "github.com/lestrrat-go/file-rotatelogs"
9         "github.com/sirupsen/logrus"
10
11         "github.com/vapor/config"
12 )
13
14 const (
15         rotationTime int64 = 86400
16         maxAge       int64 = 604800
17 )
18
19 var defaultFormatter = &logrus.TextFormatter{DisableColors: true}
20
21 func InitLogFile(config *config.Config) {
22         hook := newBtmHook(config.LogDir())
23         logrus.AddHook(hook)
24 }
25
26 type BtmHook struct {
27         logPath string
28         lock    *sync.Mutex
29 }
30
31 func newBtmHook(logPath string) *BtmHook {
32         hook := &BtmHook{lock: new(sync.Mutex)}
33         hook.logPath = logPath
34         return hook
35 }
36
37 // Write a log line to an io.Writer.
38 func (hook *BtmHook) ioWrite(entry *logrus.Entry) error {
39         module := "general"
40         if data, ok := entry.Data["module"]; ok {
41                 module = data.(string)
42         }
43
44         logPath := filepath.Join(hook.logPath, module)
45         writer, err := rotatelogs.New(
46                 logPath+".%Y%m%d",
47                 rotatelogs.WithMaxAge(time.Duration(maxAge)*time.Second),
48                 rotatelogs.WithRotationTime(time.Duration(rotationTime)*time.Second),
49         )
50         if err != nil {
51                 return err
52         }
53
54         msg, err := defaultFormatter.Format(entry)
55         if err != nil {
56                 return err
57         }
58
59         _, err = writer.Write(msg)
60         return err
61 }
62
63 func (hook *BtmHook) Fire(entry *logrus.Entry) error {
64         hook.lock.Lock()
65         defer hook.lock.Unlock()
66         return hook.ioWrite(entry)
67 }
68
69 // Levels returns configured log levels.
70 func (hook *BtmHook) Levels() []logrus.Level {
71         return logrus.AllLevels
72 }