OSDN Git Service

add read me doc
[bytom/vapor.git] / log / log.go
index 43bcc9c..5563cd0 100644 (file)
@@ -1,14 +1,18 @@
 package log
 
 import (
+       "fmt"
+       "io/ioutil"
+       "os"
        "path/filepath"
+       "strings"
        "sync"
        "time"
 
        rotatelogs "github.com/lestrrat-go/file-rotatelogs"
        "github.com/sirupsen/logrus"
 
-       "github.com/vapor/config"
+       "github.com/bytom/vapor/config"
 )
 
 const (
@@ -16,11 +20,22 @@ const (
        maxAge       int64 = 604800
 )
 
-var defaultFormatter = &logrus.TextFormatter{DisableColors: true}
+var defaultFormatter = &logrus.TextFormatter{
+       DisableColors:   true,
+       TimestampFormat: time.StampMicro,
+}
+
+func InitLogFile(config *config.Config) error {
+       logPath := config.LogDir()
+       if err := clearLockFiles(logPath); err != nil {
+               return err
+       }
 
-func InitLogFile(config *config.Config) {
-       hook := newBtmHook(config.LogDir())
+       hook := newBtmHook(logPath)
        logrus.AddHook(hook)
+       logrus.SetOutput(ioutil.Discard) //控制台不输出
+       fmt.Printf("all logs are output in the %s directory\n", logPath)
+       return nil
 }
 
 type BtmHook struct {
@@ -56,8 +71,29 @@ func (hook *BtmHook) ioWrite(entry *logrus.Entry) error {
                return err
        }
 
-       _, err = writer.Write(msg)
-       return err
+       if _, err = writer.Write(msg); err != nil {
+               return err
+       }
+
+       return writer.Close()
+}
+
+func clearLockFiles(logPath string) error {
+       files, err := ioutil.ReadDir(logPath)
+       if os.IsNotExist(err) {
+               return nil
+       } else if err != nil {
+               return err
+       }
+
+       for _, file := range files {
+               if ok := strings.HasSuffix(file.Name(), "_lock"); ok {
+                       if err := os.Remove(filepath.Join(logPath, file.Name())); err != nil {
+                               return err
+                       }
+               }
+       }
+       return nil
 }
 
 func (hook *BtmHook) Fire(entry *logrus.Entry) error {