I have an application in which the main go routine spawns few more go routines. Is it possible to log the stack trace for any go routine that crashes? Using "defer debug.Stack()" and "recover()" in the main prints the stack trace of main goroutine as expected. Is there any way to print stack trace of the go routines spawned if they panic ?
Asked
Active
Viewed 3,760 times
0
-
1If the goroutines panic the application should crash, which will show the stack traces. If you are recovering, then you have to handle it yourself. – JimB Feb 17 '21 at 16:17
-
"Is there any way to print stack trace of the go routines spawned if they panic ?" No. – Volker Feb 17 '21 at 17:00
1 Answers
1
If a goroutine panic
s, its stack trace will be shown.
If a goroutine is calling debug.Stack
, its (the calling goroutine's) stack trace will be provided.
Run this example to demonstrate both:
package main
import (
"fmt"
"runtime/debug"
"time"
)
func foo() {
stack := debug.Stack()
fmt.Println("foo's stack:", string(stack))
panic("oh noes")
}
func worker() {
foo()
}
func main() {
go foo()
time.Sleep(200 * time.Millisecond)
}
You'll see something like:
foo's stack: goroutine 6 [running]:
runtime/debug.Stack(0x0, 0x0, 0x0)
/usr/local/go/src/runtime/debug/stack.go:24 +0x9f
main.foo()
/tmp/gogo.go:10 +0x26
created by main.main
/tmp/gogo.go:21 +0x35
panic: oh noes
goroutine 6 [running]:
main.foo()
/tmp/gogo.go:13 +0xe6
created by main.main
/tmp/gogo.go:21 +0x35
exit status 2
The first stack trace is what foo
obtains with debug.Stack
. The second is a result of the unrecovered panic
crashing the process.
You can call debug.Stack
in a recover
. See this answer for example: How to get the stacktrace of a panic (and store as a variable)

Eli Bendersky
- 263,248
- 89
- 350
- 412
-
Thank you for the response. I get what you are saying, but what I am asking is, I don't want to call debug.Stack() in every go routine. Can't we have a cleaner way of having one function in main, that prints stack trace for any goroutine ? – Guna K K Feb 17 '21 at 16:30
-
1@GunaKK: no, that's not possible. Each goroutine needs its own `recover`. You can abstract this away in a function – Eli Bendersky Feb 17 '21 at 16:31