dqzve68846 2017-03-13 11:21
浏览 251
已采纳

是否可以包装log.Logger函数而不会丢失行号前缀?

When using the log.Lshortfile flag, the logger prefixes all log lines with the file name and line number of the logger function call, for example:

myfile.go:14: Hello, world!

If I wrap the log function like this, for instance:

func info(pattern string, args ...interface{}) {
    myLogger.Printf(pattern + "
", args...)
}

Every line emitted by this function is going to be prefixed with the line number of the Printf call. That is as expected, but the desired behavior is for each line to be prefixed with the line number of the line where info is called.

Is there any way around it?

  • 写回答

2条回答 默认 最新

  • doupu9251 2017-03-13 11:43
    关注

    Methods of log.Logger call the Logger.Output() method to send the message to the appropriate output. Logger.Output() allows you to pass the calldepth (the number of frames to skip).

    Unfortunately methods of log.Logger contain the calldepth "wired in", so you can't provide an offset to skip the wrapper function's frame.

    But a much better alternative is to call this Logger.Output() from your wrapper, so you don't have to bother with frames and lines yourself. Also note that you don't need to append a newline " ", as the log.Logger type already does that if the message to be logged does not end with a newline.

    So a better and shorter alternative:

    var myLogger = log.New(os.Stdout, "[my]", log.Lshortfile)
    
    func info(pattern string, args ...interface{}) {
        myLogger.Output(2, fmt.Sprintf(pattern, args...))
    }
    

    Testing it:

    func main() {
        log.SetFlags(log.Lshortfile)
        log.Println("hello")
        info("world")
    }
    

    Output (try it on the Go Playground):

    main.go:11: hello
    [my]main.go:12: world
    

    As you can see, info() prints the proper line number (+1 compared to the line number printed by log.Println() in the previous line).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。