Got some problems when using logging Filter

sword john.37 at gmail.com
Thu Nov 17 04:06:03 EST 2011


On Nov 16, 10:50 pm, Peter Otten <__pete... at web.de> wrote:
> sword wrote:
> > Thanks for your reply. I tried to edit the source a bit, now the
> > main.py looks like this:
> > #main.py
> > import logging
> > from logging import Filter
> > import a
> > import b
>
> > logging.basicConfig(level=logging.DEBUG)
> > root = logging.getLogger()
> > root.addFilter(Filter("GoneWithTheWind")) #so I suppose no log msg
> > would pass this filter
>
> > logger = logging.getLogger("main")
> > logger.debug("main process")
> > a.print_log()
> > b.print_log()
>
> > ####
> > And It still prints out all the log msg. :(
>
> Here's a little demo to explore how filtering works:
>
> $ cat demo.py
> import logging
> class Filter(logging.Filter):
>     def filter(self, record):
>         print "applying filter", self.name
>         return True
>
> logging.basicConfig()
>
> loggers = [logging.getLogger(path) for path in ["", "a", "a.b"]]
> for logger in loggers:
>     logger.addFilter(Filter("filter@" + logger.name))
>
> [handler] = logging.getLogger().handlers
> handler.addFilter(Filter("filter at handler"))
>
> for logger in loggers:
>     logger.critical("whatever")
> $ python demo.py
> applying filter filter at root
> applying filter filter at handler
> CRITICAL:root:whatever
> applying filter filter at a
> applying filter filter at handler
> CRITICAL:a:whatever
> applying filter fil... at a.b
> applying filter filter at handler
> CRITICAL:a.b:whatever
> $
>
> As you can infer from the output only the filter(s) of the original logger
> and of the handler(s) are applied.

Thanks, so if I want to see my own log out of all logs produced by
different module in the project, I should addFilter to each
corresponding logger. I thought I could add Filter in root and filter
out only the interested info from it before.



More information about the Python-list mailing list