I'm using the python logging
module to output logs to the console. I have the problem that I'm iterating through a list of objects in my code and while doing so I'm generating some log messages. For each object I decide if I need to modify it or not. I only want to output all the log information for that object when it is modified but that information is not available by the time I generate the log message.
So what I would need is some sort of buffer that saves all log messages that are generated while I handle the object and at the end when I decide to modify the object I want the messages printed to console and if I don't modify the object I want the messages to get flushed without printing them to the console. Some pseudo code:
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
fmt = logging.Formatter("%(levelname)s: %(message)s")
ch.setFormatter(fmt)
log.addHandler(ch)
for o in objects:
object_modified = False
log.info('Analyzing {}'.format(o.name))
... do stuff ...
if not o.is_active:
log.warning('The object is inactive')
log.info('Some generic message')
if o.minimum < 0:
o.minumum = 0
object_modified = True
if object_modified:
# Magic here ...
make_log_print_to_console()
else:
make_log_entries_disappear()
So all log calls I make in that for loop (whatever the level) should be held back right until the end where they either get all printed to the console or they just get flushed without any output depending on the object_modified
variable.
Any idea how to do this (in an elegant way) with the logging module?