debugging 如何获取死机的堆栈跟踪(并存储为变量)

8wtpewkr  于 2022-11-14  发布在  其他
关注(0)|答案(3)|浏览(135)

我们都知道,死机会产生stdout(Playground link)的堆栈跟踪。

panic: runtime error: index out of range
goroutine 1 [running]:
main.main()
    /tmp/sandbox579134920/main.go:9 +0x20

当您从死机中恢复时,recover()似乎只返回error,它描述了导致死机的原因(Playground link)。

runtime error: index out of range

我的问题是,是否可以存储写入stdout的stacktrace?这比字符串runtime error: index out of range提供了更好的调试信息,因为它显示了文件中导致死机的确切行。

l5tcr1uw

l5tcr1uw1#

就像上面提到的@Volker,以及作为评论发布的内容,我们可以使用runtime/debug包。

package main

import (
    "fmt"
    "runtime/debug"
)

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("stacktrace from panic: \n" + string(debug.Stack()))
        }
    }()

    var mySlice []int
    j := mySlice[0]

    fmt.Printf("Hello, playground %d", j)
}

印刷品

stacktrace from panic: 
goroutine 1 [running]:
runtime/debug.Stack(0x1042ff18, 0x98b2, 0xf0ba0, 0x17d048)
    /usr/local/go/src/runtime/debug/stack.go:24 +0xc0
main.main.func1()
    /tmp/sandbox973508195/main.go:11 +0x60
panic(0xf0ba0, 0x17d048)
    /usr/local/go/src/runtime/panic.go:502 +0x2c0
main.main()
    /tmp/sandbox973508195/main.go:16 +0x60

Playground link

tquggr8v

tquggr8v2#

创建一个日志文件,将stacktrace添加到stdout或stderr的文件中。这将在文件中添加包含错误行的时间在内的数据。

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()
}

Go playground上的工作示例

brgchamk

brgchamk3#

以下是将死机转换为错误的解决方案,并像记录任何其他错误一样记录stacktrace

package main

import (
    "fmt"

    "github.com/pkg/errors"
)

func wrong() int {
    var mySlice []int
    return mySlice[0]
}

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Printf("Error: %+v", errors.New(fmt.Sprintf("%v", r)))
        }
    }()

    fmt.Printf("Hello, playground %d", wrong())
}

Go Playground输出

Error: runtime error: index out of range [0] with length 0
main.main.func1
    /tmp/sandbox2058999152/prog.go:17
runtime.gopanic
    /usr/local/go-faketime/src/runtime/panic.go:884
runtime.goPanicIndex
    /usr/local/go-faketime/src/runtime/panic.go:113
main.wrong
    /tmp/sandbox2058999152/prog.go:11
main.main
    /tmp/sandbox2058999152/prog.go:21
runtime.main
    /usr/local/go-faketime/src/runtime/proc.go:250
runtime.goexit
    /usr/local/go-faketime/src/runtime/asm_amd64.s:1594
Program exited.

相关问题