相比于klog,logrus支持输出json日志,但是默认time不在最前面,而在最后,因为日志输出时按照key字母顺序排序。
go get github.com/sirupsen/logrus
go get github.com/natefinch/lumberjack
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"github.com/sirupsen/logrus"
"gopkg.in/natefinch/lumberjack.v2"
)
const (
logFilePath = "./test.log"
)
var (
logFile *os.File
)
func init() {
logrus.SetReportCaller(true)
logrus.SetFormatter(
&logrus.JSONFormatter{
TimestampFormat: "2006-01-02 15:04:05",
CallerPrettyfier: func(f *runtime.Frame) (function string, file string) {
return "", fmt.Sprintf("%s:%d", filepath.Base(f.File), f.Line)
},
},
)
var err error
// 使用os.create方法,每次都会创建新文件
logFile, err = os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil {
logrus.Fatalf("Failed to open log file: %v", err)
}
logFile.Close()
l := &lumberjack.Logger{
Filename: logFilePath,
MaxSize: 1,
MaxBackups: 3,
MaxAge: 28,
Compress: true,
}
logrus.SetOutput(io.MultiWriter(os.Stdout, l))
}
func main() {
defer logFile.Close()
logrus.Info("begin to run")
}
标签:err,logrus,转储,json,go,日志,logFile,os From: https://www.cnblogs.com/WJQ2017/p/18434473