Skip to content

Commit

Permalink
exit: improve line number, include stack
Browse files Browse the repository at this point in the history
  • Loading branch information
hrfee committed Jul 20, 2021
1 parent a869acd commit db526fc
Showing 1 changed file with 34 additions and 3 deletions.
37 changes: 34 additions & 3 deletions exit.go
Expand Up @@ -6,27 +6,58 @@ import (
"log"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"strings"
"time"

"github.com/hrfee/jfa-go/logger"

"github.com/pkg/browser"
)

// https://gist.github.com/swdunlop/9629168
func identifyPanic() string {
var name, file string
var line int
var pc [16]uintptr

n := runtime.Callers(4, pc[:])
for _, pc := range pc[:n] {
fn := runtime.FuncForPC(pc)
if fn == nil {
continue
}
file, line = fn.FileLine(pc)
name = fn.Name()
if !strings.HasPrefix(name, "runtime.") {
break
}
}

switch {
case name != "":
return fmt.Sprintf("%v:%v", name, line)
case file != "":
return fmt.Sprintf("%v:%v", file, line)
}

return fmt.Sprintf("pc:%x", pc)
}

// Exit dumps the last 100 lines of output to a crash file in /tmp (or equivalent), and generates a prettier HTML file containing it that is opened in the browser if possible.
func Exit(err interface{}) {
tmpl, err2 := template.ParseFS(localFS, "html/crash.html", "html/header.html")
if err2 != nil {
log.Fatalf("Failed to load template: %v", err)
}
logCache := lineCache.String()
logCache += "\n" + string(debug.Stack())
sanitized := sanitizeLog(logCache)
data := map[string]interface{}{
"Log": logCache,
"SanitizedLog": sanitized,
}
if err != nil {
data["Err"] = fmt.Sprintf("%s %v", logger.Lshortfile(), err)
data["Err"] = fmt.Sprintf("%s %v", identifyPanic(), err)
}
fpath := filepath.Join(temp, "jfa-go-crash-"+time.Now().Local().Format("2006-01-02T15:04:05"))
err2 = os.WriteFile(fpath+".txt", []byte(logCache), 0666)
Expand Down

0 comments on commit db526fc

Please sign in to comment.