I’m trying to construct a logging.handlers.MemoryHandler
which accepts only DEBUG level messages, so that I can dump them out if an ERROR message comes along (but without duplicating all of the previously-emitted INFO or other messages). This is the code (tested with Python 3.9.1):
import logging
import logging.handlers
logger = logging.getLogger(__name__)
fmt = logging.Formatter("%(levelname)s:%(message)s")
hdlr1 = logging.StreamHandler()
hdlr2 = logging.handlers.MemoryHandler(capacity=10, flushLevel=logging.ERROR, target=hdlr1, flushOnClose=False)
hdlr1.setLevel(logging.CRITICAL)
hdlr2.setLevel(logging.DEBUG)
hdlr1.setFormatter(fmt)
# hdlr2.addFilter(lambda r: r.levelno == logging.DEBUG)
logger.addHandler(hdlr1)
logger.addHandler(hdlr2)
logger.setLevel(logging.DEBUG)
logger.info("foo")
logger.debug("foo1")
logger.debug("foo2")
logger.warning("foo")
logger.error("foo")
hdlr2.close()
With the filter commented out, the MemoryHandler behaves as expected, when the ERROR message is logged all of the previous messages are dumped too:
INFO:foo
DEBUG:foo1
DEBUG:foo2
WARNING:foo
ERROR:foo
With the filter active, the MemoryHandler doesn’t dump any messages at all.
Weirdly, if I change the filter to return ‘True’ for messages that are not DEBUG messages, then the MemoryHandler dumps all of the non-DEBUG messages. No matter which level I put in the filter (tried both DEBUG and INFO), the messages of that level are not emitted.
Changing the threshold level of hdlr1
to DEBUG doesn’t change the MemoryHandler’s output, although of course that handler now displays the DEBUG messages.
I must be doing something wrong, but I cannot figure out what it is…