如何获取记录器的文件和函数名称

我正在使用 logrus操作系统,它按预期工作,现在我们需要将文件和函数添加到记录器输出中,您可以从其中调用记录器,

我们需要它是这样的

文件log-ut-usage

func main(){



  logs := lts.InitLogger("test","1","debug")


  logs.Debugf("test 123")

....


}

这是所需的输出



{"file":"log-ut-usage/main.go:21","function":"main","level":"warn","test 123":"ddd","timestamp":"2019-10-02T09:21:39.309559Z"}

目前我们得到了文件和函数


文件logger.go


func InitLog(label string) LoggerI {


loggerImpl = &logrus.Logger{

        Out:          os.Stdout,

        Level:        level,

        ReportCaller: true,

        Formatter: &logrus.JSONFormatter{

            TimestampFormat: timestampFormat,

            CallerPrettyfier: func(f *runtime.Frame) (string, string) {

                s := strings.Split(f.Function, ".")

                funcname := s[len(s)-1]

                _, filename := path.Split(f.File)

                return funcname, filename

            },

        },

    }

这是(不需要的)输出


{"file":"logger.go","func":"InitLog","level":"debug","msg":"test 123","time":"2019-10-02 12:21:39"}

我不想获取logger.go我们编码 json 格式化程序的文件,我想获取使用 logger 的文件。


holdtom
浏览 97回答 1
1回答

慕田峪9158850

您可以使用文件、函数和行信息包装记录器,然后使用它们。这是一个例子:package mainimport (    "os"    "runtime"    "strconv"    "strings"    log "github.com/sirupsen/logrus")func init() {    log.SetFormatter(&log.JSONFormatter{})    log.SetOutput(os.Stdout)}func logger() *log.Entry {    pc, file, line, ok := runtime.Caller(1)    if !ok {        panic("Could not get context info for logger!")    }    filename := file[strings.LastIndex(file, "/")+1:] + ":" + strconv.Itoa(line)    funcname := runtime.FuncForPC(pc).Name()    fn := funcname[strings.LastIndex(funcname, ".")+1:]    return log.WithField("file", filename).WithField("function", fn)}func test() {    logger().Info("Testing...")}func main() {    logger().Info("Testing...")    test()}输出:{"file":"prog.go:34","function":"main","level":"info","msg":"Testing...","time":"2009-11-10T23:00:00Z"}{"file":"prog.go:30","function":"test","level":"info","msg":"Testing...","time":"2009-11-10T23:00:00Z"}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go