logrus有七种日志级别:
Trace, Debug, Info, Warning, Error, Fatal and Panic
log.Trace("Something very low level.")
log.Debug("Useful debugging information.")
log.Info("Something noteworthy happened!")
log.Warn("You should probably take a look at this.")
log.Error("Something failed but I'm not quitting.")
// Calls os.Exit(1) after logging
log.Fatal("Bye.")
// Calls panic() after logging
log.Panic("I'm bailing.")
如果设置了Logger的日志记录级别, Logger只会记录该日志级别大于等于它的级别的条目
logrus有自带的hook, 也支持自定义hook
type Hook interface {
Levels() []Level
Fire(*Entry) error
}
package test
import (
log "github.com/sirupsen/logrus"
"testing"
)
type customLogHook struct {
}
func(c *customLogHook) Levels() []log.Level {
return log.AllLevels
}
func (c *customLogHook)Fire(entry *log.Entry) error {
entry.Data["appName"] = "blog_server"
return nil
}
func TestLog(t *testing.T) {
log.AddHook(&customLogHook{})
log.WithFields(log.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}
logrus本身是不提供日志分割功能的, file-rotatelogs 实现了 io.Writer 接口,并且提供了文件的切割功能,其实例可以作为 logrus 的目标输出,两者能无缝集成
对于访问量大的应用来说日志的自动轮转切割管理是个很重要的问题,如果应用不能妥善处理日志管理,那么会带来很多不必要的维护开销:外部工具切割日志、人工清理日志等手段确保不会将磁盘打满
/*
`WithLinkName` 为最新的日志建立软连接
`WithRotationTime` 设置日志分割的时间,隔多久分割一次
WithMaxAge 和 WithRotationCount二者只能设置一个
`WithMaxAge` 设置文件清理前的最长保存时间
`WithRotationCount` 设置文件清理前最多保存的个数
*/
path := "/Users/opensource/test/go.log"
writer, _ := rotatelogs.New(
path+".%Y%m%d%H%M",
rotatelogs.WithLinkName(path),
rotatelogs.WithMaxAge(24*time.Hour),
rotatelogs.WithRotationTime(time.Hour),
)
log.SetOutput(writer)