saving the panic stack trace and an awkward thing about defer/recover

113 views
Skip to first unread message

Petar Maymounkov

unread,
Jun 8, 2011, 6:38:28 PM6/8/11
to golang-nuts
I wanted to implement a programmatic mechanism that saves the stack
trace (in the event
of a panic) to a file, rather than displaying it.

The point of this code is that during normal execution, stderr is what
it is, only in
the event of a panic, the stderr is redirected to a file so that it
captures just the
stack trace.

I came up with this:

func SavePanicTrace() {
r := recover()
if r == nil {
return
}
// Redirect stderr
file, err := os.Create("panic")
if err != nil {
panic("dumper (no file) " + r.(string))
}
syscall.Dup2(file.Fd(), os.Stderr.Fd())
panic("dumper " + r.(string))
}

You use it by saying

func main() {
defer SavePanicTrace()
...
}

There are a few problems with this solution that bug me:

(a) I don't get to gracefully close the file that is created for the
dump.
Unless maybe: Does the file end up closed after the process exit
closes the file descriptor for stderr? Even still, it would be nice to
have
a hook at a place where I can go file.Close(), using Go's close.

(b) This is the bigger one: You actually have to include "defer
SavePanicStack()"
in every go-routing that you fork. This is awkward. Is there a way
around this?

Thanks,
--Petar

Evan Shaw

unread,
Jun 8, 2011, 6:56:05 PM6/8/11
to Petar Maymounkov, golang-nuts
On Thu, Jun 9, 2011 at 10:38 AM, Petar Maymounkov <pet...@gmail.com> wrote:
> I wanted to implement a programmatic mechanism that saves the stack
> trace (in the event
> of a panic) to a file, rather than displaying it.
>
> The point of this code is that during normal execution, stderr is what
> it is, only in
> the event of a panic, the stderr is redirected to a file so that it
> captures just the
> stack trace.

See the package runtime/debug and I think you can accomplish what you
want much more cleanly. Note that in a deferred function that
recovers, its stack trace still shows the location of the panic.

- Evan

Reply all
Reply to author
Forward
0 new messages