Reputation: 189646
I have this snippet of code I wrote in a cleanup method
for (key, target) in self.targets.items():
try:
logger.info('releasing %s: %s', key, target)
target.dispose() # Something bad can occur here
except:
logger.exception('uh oh, something has gone wrong')
The problem I am having is that in the target.dispose()
call, something bad can happen, and can cause a crash in the interpreter. (The target object calls stuff in C and/or C#) I would like to flush the logs first, before calling target.dispose()
, but python loggers don't have a flush() method; only handlers do.
Is there a way to notify the logging framework that something bad might happen next, and the handlers should be flushed now before proceeding?
Upvotes: 0
Views: 137
Reputation: 64308
Looking into the implementation in logging/__init__.py
, this seems to be the correct way to iterate over the all the handlers of a logger:
def flush_logger(logger):
c = logger
while c:
for hdlr in c.handlers:
try:
hdlr.flush()
except AttributeError:
pass
if not c.propagate:
c = None #break out
else:
c = c.parent
Upvotes: 1