| 1 |
package log |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"io" |
| 6 |
"os" |
| 7 |
"runtime/debug" |
| 8 |
"strings" |
| 9 |
"time" |
| 10 |
) |
| 11 |
|
| 12 |
var ( |
| 13 |
UICleanup = func() {} |
| 14 |
BuildInfo string |
| 15 |
) |
| 16 |
|
| 17 |
// PanicHandler tries to restore the terminal. A stack trace is written to |
| 18 |
// aerc-crash.log and then passed on if a panic occurs. |
| 19 |
func PanicHandler() { |
| 20 |
r := recover() |
| 21 |
|
| 22 |
if r == nil { |
| 23 |
return |
| 24 |
} |
| 25 |
|
| 26 |
UICleanup() |
| 27 |
|
| 28 |
filename := time.Now().Format("/tmp/aerc-crash-20060102-150405.log") |
| 29 |
|
| 30 |
panicLog, err := os.OpenFile(filename, os.O_SYNC|os.O_APPEND|os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o600) |
| 31 |
if err != nil { |
| 32 |
// we tried, not possible. bye |
| 33 |
panic(r) |
| 34 |
} |
| 35 |
defer panicLog.Close() |
| 36 |
|
| 37 |
outputs := io.MultiWriter(panicLog, os.Stderr) |
| 38 |
|
| 39 |
// if any error happens here, we do not care. |
| 40 |
fmt.Fprintln(panicLog, strings.Repeat("#", 80)) |
| 41 |
fmt.Fprint(panicLog, strings.Repeat(" ", 34)) |
| 42 |
fmt.Fprintln(panicLog, "PANIC CAUGHT!") |
| 43 |
fmt.Fprint(panicLog, strings.Repeat(" ", 24)) |
| 44 |
fmt.Fprintln(panicLog, time.Now().Format("2006-01-02T15:04:05.000000-0700")) |
| 45 |
fmt.Fprintln(panicLog, strings.Repeat("#", 80)) |
| 46 |
fmt.Fprintf(outputs, "%s\n", panicMessage) |
| 47 |
fmt.Fprintf(outputs, "Version: %s\n", BuildInfo) |
| 48 |
fmt.Fprintf(panicLog, "Error: %v\n\n", r) |
| 49 |
panicLog.Write(debug.Stack()) //nolint:errcheck // we are already in a panic, so not much we can do here |
| 50 |
fmt.Fprintf(os.Stderr, "\nThis error was also written to: %s\n", filename) |
| 51 |
panic(r) |
| 52 |
} |
| 53 |
|
| 54 |
const panicMessage = ` |
| 55 |
aerc has encountered a critical error and has terminated. Please help us fix |
| 56 |
this by sending this log and the steps to reproduce the crash to: |
| 57 |
~rjarry/[email protected] |
| 58 |
|
| 59 |
Thank you |
| 60 |
` |