panic_handler.go 843 B

123456789101112131415161718192021222324252627282930313233
  1. package log
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "runtime/debug"
  7. "time"
  8. )
  9. //捕获panic信息,输出到log文件
  10. func PanicHandler(exeName string) {
  11. if err := recover(); err != nil {
  12. now := time.Now() //获取当前时间
  13. pid := os.Getpid() //获取进程ID
  14. time_str := now.Format("200601021504") //设定时间格式
  15. fname := fmt.Sprintf("%s-%d-%s-dump.log", exeName, pid, time_str) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒)
  16. path := "./panicLog"
  17. os.MkdirAll(path, 0777)
  18. fn := filepath.Join(path, fname)
  19. f, osErr := os.Create(fn)
  20. if osErr != nil {
  21. return
  22. }
  23. defer f.Close()
  24. f.WriteString(fmt.Sprintf("%v\r\n", err)) //输出panic信息
  25. f.WriteString("========\r\n")
  26. f.WriteString(string(debug.Stack())) //输出堆栈信息
  27. }
  28. }