gpt4 book ai didi

go - 是否可以在不丢失行号前缀的情况下包装 logrus.Logger 函数?

转载 作者:行者123 更新时间:2023-12-01 20:18:43 28 4
gpt4 key购买 nike

使用包装的 logrus 函数/记录器时,记录器将使用记录器函数调用的文件名和行号作为所有日志行的前缀,例如:

INFO[0000]logging.go:39 myfolder/logging.Info()
如果我像这样包装 log 函数,例如:
包记录
import (
"fmt"
"github.com/sirupsen/logrus"
"os"
"path"
"runtime"
)

var (
log *logrus.Logger
)

func init() {

log = logrus.New()
log.SetReportCaller(true)
log.Formatter = &logrus.TextFormatter{
CallerPrettyfier: func(f *runtime.Frame) (string, string) {
filename := path.Base(f.File)
return fmt.Sprintf("%s()", f.Function), fmt.Sprintf("%s:%d", filename, f.Line)
},
}
}

func Info(args ...interface{}) {
log.Info(args...)
}
此函数发出的每一行都将以 logging function 的行号为前缀。称呼。这是预期的,但所需的行为是每行都以行的行号为前缀,其中 Info叫做。
所需的输出应该是:
INFO[0000]myfile.go:39 myfolder/myfile.myfunction()
有什么办法可以解决吗?

最佳答案

在 logrus 中是不可能做到的。我有一个类似的要求,最终做了以下对我们有用的事情。

package mylog

import (
"fmt"
"github.com/Sirupsen/logrus"
"runtime"
"strings"
)

var logger = logrus.New()

func SetLogFormatter(formatter logrus.Formatter) {
logger.Formatter = formatter
}

// Info logs a message at level Info on the standard logger.
func Info(args ...interface{}) {
if logger.Level >= logrus.InfoLevel {
entry := logger.WithFields(logrus.Fields{})
entry.Data["file"] = fileInfo(2)
entry.Info(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)
}
看看这个或它的一些变体是否适用于您的用例。我已经从上面的代码片段中删除了特定于应用程序的代码。

关于go - 是否可以在不丢失行号前缀的情况下包装 logrus.Logger 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63658002/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com