据我所知,您无法将恐慌的输出重定向到标准错误或记录器。最好的办法是将标准错误重定向到可以在外部或在程序内部执行的文件。
对于我的rclone程序,我重定向了标准错误,以将所有内容捕获到一个选项上的文件中,但是不幸的是,以跨平台的方式并不是一件容易的事。这是我的操作方法(请参阅redirect* .go文件)
对于linux / unix
// Log the panic under unix to the log file//+build unixpackage mainimport ( "log" "os" "syscall")// redirectStderr to the file passed infunc redirectStderr(f *os.File) { err := syscall.Dup2(int(f.Fd()), int(os.Stderr.Fd())) if err != nil { log.Fatalf("Failed to redirect stderr to file: %v", err) }}和窗户
// Log the panic under windows to the log file//// Code from minix, via//// http://play.golang.org/p/kLtct7lSUg//+build windowspackage mainimport ( "log" "os" "syscall")var ( kernel32 = syscall.MustLoadDLL("kernel32.dll") procSetStdHandle = kernel32.MustFindProc("SetStdHandle"))func setStdHandle(stdhandle int32, handle syscall.Handle) error { r0, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0) if r0 == 0 { if e1 != 0 { return error(e1) } return syscall.EINVAL } return nil}// redirectStderr to the file passed infunc redirectStderr(f *os.File) { err := setStdHandle(syscall.STD_ERROR_HANDLE, syscall.Handle(f.Fd())) if err != nil { log.Fatalf("Failed to redirect stderr to file: %v", err) } // SetStdHandle does not affect prior references to stderr os.Stderr = f}


