Setup proper logging

This commit is contained in:
Kristóf Tóth 2020-09-08 15:27:52 +02:00
parent f80f2be784
commit 93da02bf90

View File

@ -6,9 +6,9 @@ import (
"after-lock/xdg/keypressdetector" "after-lock/xdg/keypressdetector"
"after-lock/xdg/lockscreen" "after-lock/xdg/lockscreen"
"after-lock/lockfile" "after-lock/lockfile"
"fmt"
"os" "os"
"runtime/debug" "runtime/debug"
"log"
) )
const ( const (
@ -17,11 +17,16 @@ const (
keyboardDeviceNode = "/dev/input/by-id/usb-Dell_Dell_USB_Entry_Keyboard-event-kbd" keyboardDeviceNode = "/dev/input/by-id/usb-Dell_Dell_USB_Entry_Keyboard-event-kbd"
lockfilePath = "/tmp/after-lock.lock" lockfilePath = "/tmp/after-lock.lock"
printStackTraces = false printStackTraces = false
logFilePath = "/home/superuser/Desktop/after-lock.log"
) )
func main() { func main() {
defer handleErrors() defer handleErrors()
f := initLogging()
if f != nil {
defer f.Close()
}
lock := grabExclusiveProcessLock() lock := grabExclusiveProcessLock()
defer lock.Unlock() defer lock.Unlock()
@ -36,11 +41,25 @@ func main() {
al.Start() al.Start()
} }
func initLogging() *os.File {
if len(logFilePath) == 0 {
return nil
}
f, err := os.OpenFile(logFilePath, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0600)
if err != nil {
panic(err)
}
log.SetOutput(f)
return f
}
func handleErrors() { func handleErrors() {
if err := recover(); err != nil { if err := recover(); err != nil {
fmt.Printf("Crashed with unexpected error: %v!\n", err) log.Printf("Crashed with unexpected error: %v!\n", err)
if printStackTraces { if printStackTraces {
fmt.Printf("Stack trace:\n\n") log.Printf("Stack trace:\n\n")
debug.PrintStack() debug.PrintStack()
} }
os.Exit(1) os.Exit(1)