Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logging: print message only once

Tags:

python

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()
like image 861
robertlayton Avatar asked Aug 11 '15 22:08

robertlayton


1 Answers

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)
like image 192
chepner Avatar answered Oct 24 '22 00:10

chepner