Reputation: 4357
While I use logging
to record exceptions, it occurred to me the methods of the logging
library itself can throw exceptions.
For example, if a "bad" path is set for the log file, like
import logging
logging.basicConfig(filename='/bad/path/foo.log')
a FileNotFoundError
will be thrown.
Suppose my goal of handling these logging
exceptions is to keep the program running (and not exit, which the program would otherwise do). The first thing that comes to mind is
try:
logging.basicConfig(filename='/bad/path/foo.log')
except Exception:
pass
But this is considered by some to be an antipattern. It's also quite ugly to wrap every logging.error
with try
and except
blocks.
What's a good pattern to handle exceptions thrown by logging methods like basicConfig()
, and possibly by debug()
, error()
, etc.?
Upvotes: 0
Views: 176
Reputation: 4357
Unless you re-initialise your logger mid-way through your code, why not just check whether the file exists during logger initialisation:
import os
if os.path.isfile(filename):
# Initialise the logger
This should work normally, unless of course some part of the later code will attemp to delete the file, but I hope that it's not the case.
Upvotes: 1