tags:

views:

65

answers:

2

Maybe it's just doesn't exist, as I cannot find it in pydoc. But using python's logging package, is there a way to query a Logger to find out how many times a particular function was called? For example, how many errors/warnings were reported?

A: 

There'a a warnings module that -- to an extent -- does some of that.

You might want to add this counting feature to a customized Handler. The problem is that there are a million handlers and you might want to add it to more than one kind.

You might want to add it to a Filter, since that's independent of the Handlers in use.

S.Lott
+3  A: 

The logging module doesn't appear to support this. In the long run you'd probably be better off creating a new module, and adding this feature via sub-classing the items in the existing logging module to add the features you need, but you could also achieve this behavior pretty easily with a decorator:

class callcounted(object):
    """Decorator to determine number of calls for a method"""

    def __init__(self,method):
        self.method=method
        self.counter=0

    def __call__(self,*args,**kwargs):
        self.counter+=1
        return self.method(*args,**kwargs)


import logging
logging.error=callcounted(logging.error)
logging.error('one')
logging.error('two')
print logging.error.counter

Output:

ERROR:root:one
ERROR:root:two
2
Mark Roddy