Monday, November 21, 2016

Print line number for debugging in Go

Print line number for debugging in Go

Method 1:

// to change the flags on the default logger
log.SetFlags(log.LstdFlags | log.Lshortfile)

Method 2:

package main

import (
        "log"
        "runtime"
)

func MyFunc() {
        FancyHandleError()
}

func FancyHandleError() {
        // notice that we're using 1, so it will actually log the where
        // the error happened, 0 = this function, we don't want that.
        pc, fn, line, _ := runtime.Caller(1)
        log.Printf("[error] in %s[%s:%d]", runtime.FuncForPC(pc).Name(), fn, line)
}

func main() {
        MyFunc()
}

Method 3:

package main

import (
        //"log"
        //"runtime"
        "runtime/debug"
)

func MyFunc() {
        FancyHandleError()
}

func FancyHandleError() {
        debug.PrintStack()
}

func main() {
        MyFunc()
}

Reference:

https://golang.org/pkg/log/#pkg-constants

https://golang.org/pkg/runtime/debug/#PrintStack

http://stackoverflow.com/questions/24809287/how-do-you-get-a-golang-program-to-print-the-line-number-of-the-error-it-just-ca

No comments: