From 93da02bf90539e32c4fbf005d0c78d778a681e7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krist=C3=B3f=20T=C3=B3th?= Date: Tue, 8 Sep 2020 15:27:52 +0200 Subject: [PATCH] Setup proper logging --- cmd/after-lock/after-lock.go | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/cmd/after-lock/after-lock.go b/cmd/after-lock/after-lock.go index b4aebf4..0162e90 100644 --- a/cmd/after-lock/after-lock.go +++ b/cmd/after-lock/after-lock.go @@ -6,9 +6,9 @@ import ( "after-lock/xdg/keypressdetector" "after-lock/xdg/lockscreen" "after-lock/lockfile" - "fmt" "os" "runtime/debug" + "log" ) const ( @@ -17,11 +17,16 @@ const ( keyboardDeviceNode = "/dev/input/by-id/usb-Dell_Dell_USB_Entry_Keyboard-event-kbd" lockfilePath = "/tmp/after-lock.lock" printStackTraces = false + logFilePath = "/home/superuser/Desktop/after-lock.log" ) func main() { defer handleErrors() + f := initLogging() + if f != nil { + defer f.Close() + } lock := grabExclusiveProcessLock() defer lock.Unlock() @@ -36,11 +41,25 @@ func main() { 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() { 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 { - fmt.Printf("Stack trace:\n\n") + log.Printf("Stack trace:\n\n") debug.PrintStack() } os.Exit(1)