Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python logging, how to filter a specific logger

It seems a very simple question, but I can't find any good example for me.

I want to filter a logger which has a specific name.

For example

import logging

logging.root.setLevel(logging.DEBUG)
logging.root.addHandler(logging.StreamHandler())
logging.root.addFilter(logging.Filter(name="a"))

a = logging.getLogger("a")
b = logging.getLogger("b")

a.info("aaaaa")
b.info("bbbbb")

I expected that root logger will filters message from b because I understood that logging.Filter only pass the name or childs of the name.

But as you expect it just passes all of the messages.

What is the point I misunderstand?

like image 567
SangminKim Avatar asked Sep 04 '26 20:09

SangminKim


1 Answers

As logging documentation states:

events which have been generated by descendant loggers will not be filtered by a logger’s filter setting, unless the filter has also been applied to those descendant logger

If you just want to turn off messages from a sub-logger, you can just set its level:

logging.getLogger("a").setLevel(logging.CRITICAL + 1)
like image 142
loopbackbee Avatar answered Sep 07 '26 10:09

loopbackbee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!