Perhaps this is an opinion or maybe it's actually a best practice, but I want to do it correctly.
Consider the following code:
func main() {
if err := doSomething(); err != nil {
// log here and exit?
}
}
func doSomething() {
f, err := os.Open("filename.ext")
if err != nil {
// log here and return the error/exit?
}
}
I am interested to know where the error should be logged and where the program should be exited (assuming recovery is impossible). Some possibilities include: logging and exiting in the callee; logging in the callee, returning the error, and exiting in the caller; logging in the callee, returning the error, logging in the caller, and exiting. There seem to be benefits to all of these approaches. The second approach, for instance, allows a fine grained error message but still passes the error on to the caller. However, it will result in two log messages.
Thanks!
Golang has an inbuilt logging library, called log, comes with the default logger that writes to standard error and adds the timestamp without the need for configuration. You can use these rough-and-ready logs for local development in which you need to get fast feedback from your code may be more important than generating rich, structured logs.
To use logging in Go, we need to import the log package. The log package consists of logging functions that allow us to log data at various segments of a program. Here are some of the functions discussed in detail. 1. The Fatal function The fatal function is just like the print function the difference is that it calls os.Exit (1) at the end.
If an error occurs it calls log.Fatal to print the error message and stop. You can get a lot done in Go knowing just this about the error type, but in this article we’ll take a closer look at error and discuss some good practices for error handling in Go.
The logger is a type defined as a struct in the package. It is an object which can log into the io.Writer. The logging package is a versatile package that can be used in many different situations and it is an important package in the Go ecosystem.
This is an interesting topic, and really boils down to a lot of opinion, so this may get closed. There are a few guidelines I try to follow:
Only "handle" an error once. Logging counts as handling. If you do not know what action needs to be taken, just pass it up. You definitely don't want errors to be logged multiple times per occurrence.
If your caller is likely to change their behavior because of the error, you should return it. If you can still do your "job" despite the error, maybe you should log it and continue.
Sometimes it helps to add context to where the error initially entered your system (so the log line can include where the error came from, not just where it finally got logged). Something like https://github.com/pkg/errors can be useful for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With