Reputation: 5260
I tried to capture panic and log the error:
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
defer func() {
if err := recover(); err != nil {
glog.Errorf("Recovered from err: %v", err)
}
}()
panic("TISH IS A PANIC")
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
But to my surprise, the "Recovered from err: "
never occurs in my log file, instead, it occurs in /var/log/messages
.
How can I log that error in my original log file?
[Updated]
If there is no panic, glog.Errorf
will log correctly to its log dir; when there is panic, it just can't:
// this glog will log correctly, unless uncomment the panic below
glog.Errorf("This is a normal log: %v", err)
// panic("TISH IS A PANIC")
Maybe this is impossible, since that's what crash means?
Upvotes: 0
Views: 3227
Reputation: 1460
You need to call glog.Flush()
in your deferred function. From the documentation of glog:
Log output is buffered and written periodically using Flush. Programs should call Flush before exiting to guarantee all log output is written.
https://godoc.org/github.com/golang/glog
Upvotes: 1