如何自定义Golang日志格式

1072
2025/4/12 12:32:24
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Golang中,可以使用标准库"log"或第三方库(如"logrus"或"zap")来自定义日志格式。下面是使用标准库"log"自定义日志格式的方法:

  1. 导入"log"包:
import (
	"log"
	"os"
)
  1. 创建一个自定义的日志记录器:
type customLogger struct {
	logger *log.Logger
}

func (cl *customLogger) log(prefix string, flag int, msg string) {
	// 自定义日志格式
	formattedMsg := fmt.Sprintf(prefix+msg+"\n", cl.logger.Flags())
	// 输出日志
	fmt.Print(formattedMsg)
}
  1. 创建一个自定义的日志输出函数:
func customOutput(prefix string, flag int, msg string) {
	cl.log(prefix, flag, msg)
}
  1. 创建一个自定义的日志记录器实例:
func newCustomLogger(prefix string, flag int) *customLogger {
	return &customLogger{
		logger: log.New(os.Stdout, prefix, flag),
	}
}
  1. 使用自定义的日志记录器:
func main() {
	cl := newCustomLogger("INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
	cl.log("This is a custom log message", 0, "Hello, World!")
}

这将输出如下格式的日志:

INFO: 2022/01/01 12:00:00 main.go:25: Hello, World!

如果你想要使用第三方库来自定义日志格式,可以参考以下示例:

  1. 安装"logrus"库:
go get github.com/sirupsen/logrus
  1. 导入"logrus"包:
import (
	"github.com/sirupsen/logrus"
)
  1. 创建一个自定义的日志记录器:
func main() {
	logrus.SetFormatter(&logrus.TextFormatter{
		FullTimestamp: true,
		CallerPrettyfier: func(f *runtime.Frame) (string, string) {
			filename := filepath.Base(f.File)
			return filename, ""
		},
	})
	logrus.Info("This is a custom log message")
}

这将输出如下格式的日志:

time="2022-01-01T12:00:00Z" level=info msg="This is a custom log message" file="main.go" line=25

你可以根据自己的需求调整日志格式。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: linux中find命令能按大小吗