Got some problems when using logging Filter

sword john.37 at gmail.com
Mon Nov 21 02:15:21 EST 2011


On Nov 20, 8:42 am, Vinay Sajip <vinay_sa... at yahoo.co.uk> wrote:
> On Nov 17, 9:06 am, sword <john... at gmail.com> wrote:
>
>
>
>
>
>
>
>
>
> > 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
> > > > importlogging
> > > > fromloggingimport 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
> > > importlogging
> > > 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.
>
> Or you can add a filter to the handler (but then you can't use
> basicConfig() to configure it - you need to do it explicitly).
>
> Regards,
>
> Vinay Sajip


Thank you! Maybe I should find out another way to manipulate the log,
like wrap the getLogger function and add the filter at the first
time :)



More information about the Python-list mailing list