Skip to content

Commit 391ac19

Browse files
committed
change approach: redirect stderr to file instead using defer
1 parent bdbd029 commit 391ac19

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

main.go

+12
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,18 @@ func main() {
111111
os.Exit(0)
112112
}
113113

114+
// save crashreport to file
115+
logFilename := "crashreport_" + time.Now().Format("20060102150405") + ".txt"
116+
currDir, err := osext.ExecutableFolder()
117+
if err != nil {
118+
panic(err)
119+
}
120+
logFile, err := os.OpenFile(filepath.Join(currDir, logFilename), os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_APPEND, 0644)
121+
if err != nil {
122+
log.Print("Cannot create file used for crash-report")
123+
}
124+
redirectStderr(logFile)
125+
114126
// Launch main loop in a goroutine
115127
go loop()
116128

redirect_stderr_unix.go

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Log the panic under unix to the log file
2+
3+
// +build !windows
4+
5+
package main
6+
7+
import (
8+
"log"
9+
"os"
10+
11+
"golang.org/x/sys/unix"
12+
)
13+
14+
// redirectStderr to the file passed in
15+
func redirectStderr(f *os.File) {
16+
err := unix.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
17+
if err != nil {
18+
log.Fatalf("Failed to redirect stderr to file: %v", err)
19+
}
20+
}

redirect_stderr_win.go

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// Log the panic under windows to the log file
2+
//
3+
// Code from minix, via
4+
//
5+
// https://play.golang.org/p/kLtct7lSUg
6+
7+
// +build windows
8+
9+
package main
10+
11+
import (
12+
"log"
13+
"os"
14+
"syscall"
15+
)
16+
17+
var (
18+
kernel32 = syscall.MustLoadDLL("kernel32.dll")
19+
procSetStdHandle = kernel32.MustFindProc("SetStdHandle")
20+
)
21+
22+
func setStdHandle(stdhandle int32, handle syscall.Handle) error {
23+
r0, _, e1 := syscall.Syscall(procSetStdHandle.Addr(), 2, uintptr(stdhandle), uintptr(handle), 0)
24+
if r0 == 0 {
25+
if e1 != 0 {
26+
return error(e1)
27+
}
28+
return syscall.EINVAL
29+
}
30+
return nil
31+
}
32+
33+
// redirectStderr to the file passed in
34+
func redirectStderr(f *os.File) {
35+
err := setStdHandle(syscall.STD_ERROR_HANDLE, syscall.Handle(f.Fd()))
36+
if err != nil {
37+
log.Fatalf("Failed to redirect stderr to file: %v", err)
38+
}
39+
// SetStdHandle does not affect prior references to stderr
40+
os.Stderr = f
41+
}

0 commit comments

Comments
 (0)