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 if _, err = writer.Write(msg); err != nil {
78 func clearLockFiles(logPath string) error {
79 files, err := ioutil.ReadDir(logPath)
80 if os.IsNotExist(err) {
82 } else if err != nil {
86 for _, file := range files {
87 if ok := strings.HasSuffix(file.Name(), "_lock"); ok {
88 if err := os.Remove(filepath.Join(logPath, file.Name())); err != nil {
96 func (hook *BtmHook) Fire(entry *logrus.Entry) error {
98 defer hook.lock.Unlock()
99 return hook.ioWrite(entry)
102 // Levels returns configured log levels.
103 func (hook *BtmHook) Levels() []logrus.Level {
104 return logrus.AllLevels