Jason S
Jason S

Reputation: 189646

how to notify python logging handlers that a crash may occur and logs should be flushed?

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

Answers (1)

shx2
shx2

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

Related Questions