fine grain logging cotrol

Peter Otten __peter__ at
Thu Mar 22 14:47:35 CET 2007

Eric S. Johansson wrote:

> I need to to be able to conditionally log based on the method the log
> statement is in and one other factor like a log level.  in order to do
> so, I need to be able to automatically find out the name of the method
> and its class but I haven't found out how to do that yet.
> for example,
> class catus(Felis):
>    def Siamese_cat( yowl, purr, demand_food):
>      ...
>      log("state of litter box %s"% litter_box.smell, level = 1)
> If the table of methods logged contains "catus.Siamese_cat", then I
> would expect to see the output of the log statements in a log file.  If
> not then I wouldn't see anything in the log.
> Has somebody done this already?  Is it even possible to do without
> manually adding the class and method information for every log statement?
> a related question is using signals for reloading configurations etc.  I
> have to find any good examples of how to use signals to cause a
> long-running process to reload external data.  Any good pointers?

Instead of rolling your own, use the logging package which can handle
everything but the class info out of the box (levels are spelt as method
names info(), warn() etc.).

import logging

class LoggedType(type):
    def __new__(mcl, name, bases, classdict):
        classdict["logger"] = logging.getLogger(name)
        return type.__new__(mcl, name, bases, classdict)

class Felis:
    __metaclass__ = LoggedType
    def alpha(self):"felis-alpha")

class Catus(Felis):
    def alpha(self):"catus-alpha")
    def beta(self):"catus-beta")

if __name__ == "__main__":
    logging.basicConfig(format="%(name)s.%(funcName)s: %(message)s",
    f = Felis()
    c = Catus()

If the metaclass bothers you, here's a simpler alternative:

class Felis(object):
    logger = logging.getLogger("Felis")
    def alpha(self):"felis-alpha")

class Catus(Felis):
    logger = logging.getLogger("Catus")
    def alpha(self):"catus-alpha")
    def beta(self):"catus-beta")


More information about the Python-list mailing list