Skip to content

Commit 09db9bb

Browse files
author
NullpointerW
committed
feat: redirect stderr
1 parent 48e54a1 commit 09db9bb

File tree

3 files changed

+59
-4
lines changed

3 files changed

+59
-4
lines changed

conf/env.go

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
util "github.com/NullpointerW/anicat/utils"
99
"gopkg.in/yaml.v3"
1010
"os"
11+
"path/filepath"
1112
"runtime"
1213
)
1314

@@ -137,7 +138,7 @@ func logInit(debug bool) {
137138
if debug {
138139
level = "debug"
139140
}
140-
output := os.Stderr
141+
output := os.Stdout
141142
if runtime.GOOS == "windows" && !IdeDebugging {
142143
var err error
143144
executePath, err := util.GetExecutePath()
@@ -148,12 +149,22 @@ func logInit(debug bool) {
148149
}
149150
executePath = util.FileSeparatorConv(executePath)
150151
output, err = os.OpenFile(executePath, os.O_TRUNC|os.O_CREATE, 0777)
151-
// recv PANIC
152-
os.Stderr = output
153152
if err != nil {
154-
output = os.Stderr
153+
output = os.Stdout
155154
defer log.Error(log.Struct{"err", err}, "create logfile failed")
156155
}
156+
// receive PANIC
157+
dirP := filepath.Dir(executePath)
158+
PanicP := filepath.Join(dirP, "panic.log")
159+
panicOp, err := os.OpenFile(PanicP, os.O_APPEND|os.O_CREATE, 0777)
160+
if err == nil {
161+
err = errs.PanicRedirect(panicOp)
162+
if err != nil {
163+
defer log.Error(log.Struct{"err", err}, "redirect stderr failed")
164+
_ = panicOp.Close()
165+
}
166+
}
167+
157168
}
158169
log.Init("text", level, "2006-01-02T15:04:05", debug, output)
159170
log.Debug(log.Struct{"os", runtime.GOOS}, "debug mode")

errs/panic_redirect_linux.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package errs
2+
3+
import (
4+
"os"
5+
"runtime"
6+
"syscall"
7+
)
8+
9+
var _g *os.File
10+
11+
func PanicRedirect(file *os.File) error {
12+
_g = file
13+
if err := syscall.Dup2(int(file.Fd()), int(os.Stderr.Fd())); err != nil {
14+
fmt.Println(err)
15+
return err
16+
}
17+
// 内存回收前关闭文件描述符
18+
runtime.SetFinalizer(_g, func(fd *os.File) {
19+
_ = fd.Close()
20+
})
21+
return nil
22+
}

errs/panic_redirect_windows.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package errs
2+
3+
import (
4+
"golang.org/x/sys/windows"
5+
"os"
6+
"runtime"
7+
)
8+
9+
var _g *os.File
10+
11+
func PanicRedirect(file *os.File) error {
12+
_g = file
13+
err := windows.SetStdHandle(windows.STD_ERROR_HANDLE, windows.Handle(file.Fd()))
14+
if err != nil {
15+
return err
16+
}
17+
// 内存回收前关闭文件描述符
18+
runtime.SetFinalizer(_g, func(fd *os.File) {
19+
_ = fd.Close()
20+
})
21+
return nil
22+
}

0 commit comments

Comments
 (0)