package log
import (
"fmt"
rotatelogs "github.com/lestrrat-go/file-rotatelogs"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"github.com/project/config"
"os"
"runtime"
"strings"
"time"
)
var Logger *logrus.Logger
var format = &logrus.JSONFormatter{
CallerPrettyfier: func(f *runtime.Frame) (function string, file string) {
goPath := strings.Split(os.Getenv("GOPATH"), ":")[0]
apiPath := fmt.Sprintf("%s/src/github.com/project/", goPath)
funcName := strings.Replace(f.Function, "github.com/project/", "", -1)
filename := strings.Replace(f.File, apiPath, "", -1)
return fmt.Sprintf("%s()", funcName), fmt.Sprintf("%s:%d", filename, f.Line)
},
}
func InitLogger(cfg config.ServerConfig) {
lv, err := logrus.ParseLevel(cfg.LogLevel)
if err != nil {
lv = logrus.DebugLevel
}
defaultHook := &DefaultFieldHook{}
lfsHook := newLfsHook(cfg.LogPath, cfg.LogLink)
logrus.SetReportCaller(true)
logrus.SetFormatter(format)
logrus.AddHook(defaultHook)
logrus.AddHook(lfsHook)
logrus.SetLevel(lv)
logrus.SetFormatter(format)
Logger = logrus.New()
Logger.SetReportCaller(true)
Logger.SetFormatter(format)
Logger.AddHook(defaultHook)
Logger.AddHook(lfsHook)
Logger.SetLevel(lv)
Logger.SetFormatter(format)
}
func newLfsHook(path, link string) logrus.Hook {
writer, err := rotatelogs.New(
path+".%Y%m%d",
rotatelogs.WithLinkName(link),
rotatelogs.WithRotationTime(time.Hour*24),
//rotatelogs.WithMaxAge(time.Hour*24*30),
//rotatelogs.WithRotationCount(maxRemainCnt),
)
if err != nil {
panic(err)
}
lfsHook := lfshook.NewHook(lfshook.WriterMap{
logrus.DebugLevel: writer,
logrus.InfoLevel: writer,
logrus.WarnLevel: writer,
logrus.ErrorLevel: writer,
logrus.FatalLevel: writer,
logrus.PanicLevel: writer,
}, format)
return lfsHook
}
type DefaultFieldHook struct {
}
func (hook *DefaultFieldHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (hook *DefaultFieldHook) Fire(entry *logrus.Entry) error {
entry.Data["appName"] = "api"
return nil
}