Reputation: 20355
I am using logging throughout my code for easier control over logging level. One thing that's been confusing me is
when do you prefer
logging.error()
toraise Exception()
?
To me, logging.error()
doesn't really make sense, since the program should stop when encountered with an error, like what raise Exception()
does.
In what scenarios, do we put up an error message with logging.error()
and let the program keep running?
Upvotes: 1
Views: 9081
Reputation: 25799
That purely depends on your process flow but it basically boils down to whether you want to deal with an encountered error (and how), or do you want to propagate it to the user of your code - or both.
logging.error()
is typically used to log when an error occurs - that doesn't mean that your code should halt and raise an exception as there are recoverable errors. For example, your code might have been attempting to load a remote resource - you can log an error and try again at later time without raising an exception.
btw. you can use logging
to log an exception (full, with a stack trace) by utilizing logging.exception()
.
Upvotes: 3
Reputation: 522382
Logging is merely to leave a trace of events for later inspection but does absolutely nothing to influence the program execution; raising an exception allows you to signal an error condition to higher up callers and let them handle it. Typically you use both together, it's not an either-or.
Upvotes: 5