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 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度