2015-10-24 18:38

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 (

// 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 {

func main() {
    _, err := os.Open("some-crazy-non-existent-file")
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongxian6741 dongxian6741 6年前

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

    Here's an example on Play

    点赞 评论 复制链接分享