We have a large-ish golang application that uses the logger (actually, a custom logger), to write output to a log file that is periodically rotated.
However, when an application crashes or panic()'s, those messages go to standard error.
Is there any way to override the panic functionality to use our logger?
You can use
recover()
to recover panics from the same goroutine. When callingrecover()
in a deferred method (remember that deferred methods will still be called, even whenpanic()
ing), it will return whatever was passed into the lastpanic()
call as argument (ornil
when the program is not panicking).Note however, that you cannot recover from panics that were triggered in a different goroutine (thanks to JimB for the hint). Using a single
recover()
to recover from panics from any goroutine is not possible.Expanding @nick-craig-wood's answer: If you are on Linux you can spawn a logger(1) instance and redirect stderr to it. That way you get the full backtrace into syslog. This is what gocryptfs does:
As far as I know, you can't redirect the output from panic away from standard error, or to your logger. The best thing you can do is redirect standard error to a file which you can do externally, or inside your program.
For my rclone program I redirected standard error to capture everything to a file on an option which is unfortunately isn't particularly easy to do in a cross platform way. Here is how I did it (see the redirect*.go files)
For linux/unix
and for windows