3 Commits

Author SHA1 Message Date
13a7d8db91 Fix package 2025-04-18 12:43:57 +02:00
bdad721b3d Add safe.go for panic recovery 2025-04-18 12:41:56 +02:00
f164e9699d Update module name
oopsie
2025-04-18 12:22:39 +02:00
3 changed files with 51 additions and 2 deletions

2
go.mod
View File

@@ -1,3 +1,3 @@
module cylogger
module git.site.quack-lab.dev/dave/cylogger
go 1.24.2

View File

@@ -1,4 +1,4 @@
package logger
package cylogger
import (
"bytes"

49
safe.go Normal file
View File

@@ -0,0 +1,49 @@
package cylogger
import (
"fmt"
"runtime/debug"
)
// PanicHandler handles a panic and logs it
func PanicHandler() {
if r := recover(); r != nil {
goroutineID := GetGoroutineID()
stackTrace := debug.Stack()
Error("PANIC in goroutine %s: %v\n%s", goroutineID, r, stackTrace)
}
}
// SafeGo launches a goroutine with panic recovery
// Usage: logger.SafeGo(func() { ... your code ... })
func SafeGo(f func()) {
go func() {
defer PanicHandler()
f()
}()
}
// SafeGoWithArgs launches a goroutine with panic recovery and passes arguments
// Usage: logger.SafeGoWithArgs(func(arg1, arg2 interface{}) { ... }, "value1", 42)
func SafeGoWithArgs(f func(...interface{}), args ...interface{}) {
go func() {
defer PanicHandler()
f(args...)
}()
}
// SafeExec executes a function with panic recovery
// Useful for code that should not panic
func SafeExec(f func()) (err error) {
defer func() {
if r := recover(); r != nil {
goroutineID := GetGoroutineID()
stackTrace := debug.Stack()
Error("PANIC in goroutine %s: %v\n%s", goroutineID, r, stackTrace)
err = fmt.Errorf("panic recovered: %v", r)
}
}()
f()
return nil
}