Python logging: print message only once

I am using the logging module in python 3 and want the specific warning message to be displayed only once. The problem is that the check is inside the loop:

 def canned_example(): logger.warning("This function hasn't been created yet") for i in range(10): canned_example() 

Is there a flag for the registration module that will mean that this particular warning should be displayed only once? An alternative is to keep a record of different flags, but I would like to keep it simple, if possible.

Update: Amir Yazdanbakhsh wrote a response in the comments that allows us to do this for all posts. Ideally, I need some flag for each message:

 def canned_example(): logger.warning("This function hasn't been created yet", norepeat=True) for i in range(10): canned_example() 
+7
python
source share
1 answer

Define a filter that tracks what has been logged and attach it to your registrar throughout the cycle. In this example, they will remember every message that he sees, and allow only the first entry.

 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) 
+1
source share

All Articles