go logrus输出json日志并转储

相比于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() {
	logrus.Info("begin to run")
}

 

posted on 2024-09-26 21:47  王景迁  阅读(8)  评论(0编辑  收藏  举报

导航