登录
首页 >  Golang >  Go问答

获取记录器的文件和函数名称的方法

来源:stackoverflow

时间:2024-02-28 10:54:26 247浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《获取记录器的文件和函数名称的方法》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我正在使用 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"}

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


解决方案


您可以使用文件、函数和行信息包装记录器,然后使用它们。

这是一个示例 (live):

package main

import (
    "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"}

您是否尝试过使用debug.stack()来获取调用initlog的文件名?

https://play.golang.org/p/g6yLGsiuEEn

goroutine 1 [running]:
runtime/debug.Stack(0x15d6b0, 0x3, 0x68360, 0x1580)
    /usr/local/go/src/runtime/debug/stack.go:24 +0xc0
main.fun2()
    /tmp/sandbox834348417/prog.go:20 +0x20
main.fun1(...)
    /tmp/sandbox834348417/prog.go:15
main.main()
    /tmp/sandbox834348417/prog.go:10 +0x20

希望它能起作用。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>