I'm using the logging
module in python 3, and want a particular warning message to be displayed only once.
The problem is that the check is inside a loop:
def canned_example():
logger.warning("This function hasn't been created yet")
for i in range(10):
canned_example()
Is there a flag to set inside the logging module that will denote that this particular warning is only to be displayed once? The alternative is to keep a record of different flags, but I'd like to keep it simple if possible.
Update: Amir Yazdanbakhsh has posted an answer in the comments that allows us to do this for all messages. Ideally, I'd like some per-message flag:
def canned_example():
logger.warning("This function hasn't been created yet", norepeat=True)
for i in range(10):
canned_example()
Define a filter which keeps track of what was logged, and attach it to your logger for the duration of the loop. This example will remember each message it sees, and only allow the first occurrence to be logged.
class DuplicateFilter(object):
def __init__(self):
self.msgs = set()
def filter(self, record):
rv = record.msg not in self.msgs
self.msgs.add(record.msg)
return rv
dup_filter = DuplicateFilter()
logger.addFilter(dup_filter)
for i in range(10):
canned_example()
logger.removeFilter(dup_filter)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With