1、安装
go get github.com/sirupsen/logrus
实现日志滚动
go get gopkg.in/natefinch/lumberjack.v2
2、初始化logrus参数
var Logger = logrus.New()func SetLogrus(logConf conf.LogConfig) {Logger.SetLevel(GetLevel(logConf.Level))Logger.SetReportCaller(true)Logger.SetFormatter(&logrus.JSONFormatter{TimestampFormat: constants.DateTimeMillLayout,CallerPrettyfier: func(frame *runtime.Frame) (function string, file string) {fileName := path.Base(frame.File)lineNum := strconv.Itoa(frame.Line)return "", fileName + ":" + lineNum},})// 使用 lumberjack 实现 logrus 的滚动日志logger := &lumberjack.Logger{Filename: logConf.Path,MaxSize: 300, // 日志文件大小,单位是 MBMaxBackups: 30, // 最大过期日志保留个数MaxAge: 30, // 保留过期文件最大时间,单位 天Compress: false, // 是否压缩日志,默认是不压缩,这里设置为true,压缩日志}Logger.SetOutput(logger)}func GetLogger() *logrus.Logger {return Logger
}func GetLevel(levelStr string) logrus.Level {switch levelStr {case "trace":return logrus.TraceLevelcase "debug":return logrus.DebugLevelcase "info":return logrus.InfoLevelcase "warn":return logrus.WarnLevelcase "error":return logrus.ErrorLevelcase "fatal":return logrus.FatalLevelcase "panic":return logrus.PanicLeveldefault:return logrus.InfoLevel}
}
问题点:若要对logrus进行包装,会存在输出的文件和行号错误,解决方案:
func Infof(msg string, args ...interface{}) {entry := logrus.NewEntry(Logger) // work!entry.Data["file:line"] = fileInfo(2)entry.Infof(msg, args...)
}func fileInfo(skip int) string {_, file, line, ok := runtime.Caller(skip)if !ok {file = "<???>"line = 1} else {slash := strings.LastIndex(file, "/")if slash >= 0 {file = file[slash+1:]}}return fmt.Sprintf("%s:%d", file, line)
}
使用示例:
// 推荐使用
logrus.WithFields(logrus.Fields{"name": "张三","age": 20,}).Info("my msg")// 支持
logrus.Infof("to %s, do %s", "xxx", "yyyy")