- 使用logrus配合file-rotatelogs、lfshook实现:
1 日志文件按时间切割
2 根据日志等级输出到不同文件
3 增加默认的日志信息(比如本文中的本机ip,获取本机ip的代码就不贴了)
import (
"github.com/lestrrat-go/file-rotatelogs"
"github.com/lfz757077613/goLearn/utils"
"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"
"time"
)
const (
_infoPath = "info.log"
_errorPath = "error.log"
_rotationHour = 24
_maxAgeHour = 72
_timeStampFormat = "2016-01-02 15:04:05"
)
func init() {
logrus.SetFormatter(&logrus.TextFormatter{
DisableColors: true,
TimestampFormat: _timeStampFormat,
})
// 不向控制台打印
//log.Out = ioutil.Discard
// 写文件不加锁,具体参考logrus文档确认可不可以不锁
// log.SetNoLock()
infoWriter, err := rotatelogs.New(
_infoPath+".%Y-%m-%d",
rotatelogs.WithLinkName(_infoPath),
rotatelogs.WithRotationTime(time.Hour*_rotationHour),
rotatelogs.WithMaxAge(time.Hour*_maxAgeHour),
)
if err != nil {
panic(err)
}
errorWriter, err := rotatelogs.New(
_errorPath+".%Y-%m-%d",
rotatelogs.WithLinkName(_errorPath),
rotatelogs.WithRotationTime(time.Hour*_rotationHour),
rotatelogs.WithMaxAge(time.Hour*_maxAgeHour),
)
if err != nil {
panic(err)
}
logrus.AddHook(&DefaultFieldsHook{})
logrus.AddHook(lfshook.NewHook(
lfshook.WriterMap{
logrus.InfoLevel: infoWriter,
logrus.ErrorLevel: errorWriter,
},
&logrus.TextFormatter{
DisableColors: true,
TimestampFormat: _timeStampFormat,
},
))
}
type DefaultFieldsHook struct {
}
func (df *DefaultFieldsHook) Fire(entry *logrus.Entry) error {
entry.Data["localIp"] = utils.GetLocalIp()
return nil
}
func (df *DefaultFieldsHook) Levels() []logrus.Level {
return logrus.AllLevels
}
有疑问加站长微信联系(非本文作者)