dream752614590 2015-10-24 18:38
浏览 185
已采纳

Golang log。致命错误中的致命更改行号

This program emits app: 2015/10/24 11:28:15 example.go:22: open some-crazy-non-existent-file: no such file or directory which corresponds to a line inside the fatal function instead of inside main where the error is logically being generated/handled. I have a lot of repetitive error handling code that I want to wrap in a function, but I don't want to lose the convenience of informative line numbers. How do I make my fatal function transparent to whatever mechanism associates line numbers with log messages, or generate the line number earlier?

This would be a wonderful use of a preprocessor / macro system if golang had one

package main

import (
    "log"
    "os"
)

// logger configured to emit app name, line number, timestamps etc.
var mylog = log.New(os.Stderr, "app: ", log.LstdFlags|log.Lshortfile)

// in order to avoid repetitive error handling code like
//
// result, err := someOperation(argument0, argument1)
// if err != nil {
//     mylog.Fatal(err)
// }
//
// I defined the following function

func fatal(err error) {
    if err != nil {
        mylog.Fatal(err)
    }
}

func main() {
    _, err := os.Open("some-crazy-non-existent-file")
    fatal(err)
}
  • 写回答

1条回答 默认 最新

  • dongxian6741 2015-10-24 19:48
    关注

    you can get the line number of whatever called your fatal function using runtime.Caller(1)

    Here's an example on Play

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥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测量血氧,找不到相关的代码。