12 rotatelogs "github.com/lestrrat-go/file-rotatelogs"
13 "github.com/sirupsen/logrus"
15 "github.com/bytom/vapor/config"
19 rotationTime int64 = 86400
23 var defaultFormatter = &logrus.TextFormatter{
25 TimestampFormat: time.StampMicro,
28 func InitLogFile(config *config.Config) error {
29 logPath := config.LogDir()
30 if err := clearLockFiles(logPath); err != nil {
34 hook := newBtmHook(logPath)
36 logrus.SetOutput(ioutil.Discard) //控制台不输出
37 fmt.Printf("all logs are output in the %s directory\n", logPath)
46 func newBtmHook(logPath string) *BtmHook {
47 hook := &BtmHook{lock: new(sync.Mutex)}
48 hook.logPath = logPath
52 // Write a log line to an io.Writer.
53 func (hook *BtmHook) ioWrite(entry *logrus.Entry) error {
55 if data, ok := entry.Data["module"]; ok {
56 module = data.(string)
59 logPath := filepath.Join(hook.logPath, module)
60 writer, err := rotatelogs.New(
62 rotatelogs.WithMaxAge(time.Duration(maxAge)*time.Second),
63 rotatelogs.WithRotationTime(time.Duration(rotationTime)*time.Second),
69 msg, err := defaultFormatter.Format(entry)
74 if _, err = writer.Write(msg); err != nil {
81 func clearLockFiles(logPath string) error {
82 files, err := ioutil.ReadDir(logPath)
83 if os.IsNotExist(err) {
85 } else if err != nil {
89 for _, file := range files {
90 if ok := strings.HasSuffix(file.Name(), "_lock"); ok {
91 if err := os.Remove(filepath.Join(logPath, file.Name())); err != nil {
99 func (hook *BtmHook) Fire(entry *logrus.Entry) error {
101 defer hook.lock.Unlock()
102 return hook.ioWrite(entry)
105 // Levels returns configured log levels.
106 func (hook *BtmHook) Levels() []logrus.Level {
107 return logrus.AllLevels