Is there any way to redirect output from panic to a file with a timestamp for each panic.
Current example result of the panic log file:
goroutine 6 [running]:
_/C_/....func·001(0x11691e80, 0x1a, 0x0, 0x0, 0x10d3550, 0x11691ec0, 0x0, 0x0)
C:/.../Logger.go:309 +0x47
path/filepath.Walk(0x11691e80, 0x1a, 0x1161defc, 0x0, 0x0)
c:/...../path.go:392 +0x97
_/C_/...../Logger.Sample(0x1168ac00, 0x59, 0x0, 0x0)
C:/...../Logger.go:322 +0x1c5
main.handleFileActions()
C:/...../main.go:453 +0x2ad
created by main.main
C:/..../main.go:278 +0x6ea
Expected result:
2017-02-27T14:24:22.627Z - goroutine 6 [running]:
_/C_/....func·001(0x11691e80, 0x1a, 0x0, 0x0, 0x10d3550, 0x11691ec0, 0x0, 0x0)
C:/.../Logger.go:309 +0x47
path/filepath.Walk(0x11691e80, 0x1a, 0x1161defc, 0x0, 0x0)
c:/...../path.go:392 +0x97
_/C_/...../Logger.Sample(0x1168ac00, 0x59, 0x0, 0x0)
C:/...../Logger.go:322 +0x1c5
main.handleFileActions()
C:/...../main.go:453 +0x2ad
created by main.main
C:/..../main.go:278 +0x6ea
It is possible to add a timestamp to your log file.
Because the errors are also just values, you are able to do something before you panic.
Just a simple example:
var buf bytes.Buffer
logger := log.New(&buf, "logger: ", log.Ldate|log.Ltime|log.Llongfile)
logger.Print("Error when calling that code")
fmt.Print(&buf)
logger.Panic("Error")
https://play.golang.org/p/g4mweH4Dex
Here you should not panic as soon as your error occurs. You can write some more information inside your log. For example the parameters of your function or the values of the config file.
With the correct flags inside your logger definition log.Ldate|log.Ltime|log.Llongfile
you will also get a timestamp.
Edited: Thanks to reticentroot for the comment about the recover wrapper. The article Defer, Panic and Recover describes a way how to handle panicking. Here you can recover by using defer.
func main() {
myFunc()
fmt.Print(&buf)
}
func myFunc() {
defer func() {
if r := recover(); r != nil {
logger.Println("Recovered from panic: ", r)
}
}()
myPanic()
}
func myPanic() {
panic("Panicking in myPanic")
}