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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大