1
0
Fork 0
mirror of https://git.sr.ht/~ashkeel/strimertul synced 2024-09-18 01:50:50 +00:00

feat: add stderr logging to its own file

This commit is contained in:
Ash Keel 2023-03-09 12:41:50 +01:00
parent 074a8757b7
commit d28db037ae
No known key found for this signature in database
GPG key ID: BAD8D93E7314ED3E
3 changed files with 69 additions and 1 deletions

19
main.go
View file

@ -34,6 +34,8 @@ func main() {
log.Fatal(err)
}
var panicLog *os.File
app := &cli.App{
Name: "strimertul",
Usage: "the small broadcasting suite for Twitch",
@ -83,12 +85,27 @@ func main() {
level = zapcore.InfoLevel
}
initLogger(level)
// Create file for panics
panicLog, err = os.OpenFile("strimertul-panic.log", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o666)
if err != nil {
logger.Warn("could not create panic log", zap.Error(err))
} else {
utils.RedirectStderr(panicLog)
}
zap.RedirectStdLog(logger)()
ctx.Context = context.WithValue(ctx.Context, utils.ContextLogger, logger)
return nil
},
After: func(ctx *cli.Context) error {
if panicLog != nil {
utils.Close(panicLog, logger)
}
_ = logger.Sync()
zap.RedirectStdLog(logger)()
return nil
},
}

17
utils/stderr_unix.go Normal file
View file

@ -0,0 +1,17 @@
//go:build unix
package utils
import "os"
import (
"log"
"syscall"
)
func 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)
}
}

34
utils/stderr_windows.go Normal file
View file

@ -0,0 +1,34 @@
//go:build windows
package utils
import (
"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
}
func 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
}