How to get the stacktrace of a panic (and store as a variable)

后端 未结 2 1536
逝去的感伤
逝去的感伤 2021-02-01 14:44

As we all know, panics produce a stacktrace to stdout (Playground link).:

panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
    /tmp/sa         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-01 15:01

    Create a log file to add the stacktrace to the file for stdout or stderr. This will add the data including the time with line of the error inside a file.

    package main
    
    import (
        "log"
        "os"
        "runtime/debug"
    )
    
    func main() {
    
        defer func() {
            if r := recover(); r != nil {
                log.Println(string(debug.Stack()))
            }
        }()
    
        //create your file with desired read/write permissions
        f, err := os.OpenFile("filename", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
        if err != nil {
            log.Println(err)
        }
    
        //set output of logs to f
        log.SetOutput(f)
        var mySlice []int
        j := mySlice[0]
    
        log.Println("Hello, playground %d", j)
    
        //defer to close when you're done with it, not because you think it's idiomatic!
        f.Close()
    }
    

    Working example on Go playground

提交回复
热议问题