Python Summary Account

At the end of my Python program, I would like to get a summary of the number of elements registered through standard logging. I would especially like to receive an invoice for each given name (and possibly his children). For instance. if I have:

input_logger = getLogger('input')
input_logger.debug("got input1")
input_logger.debug("got input2")
input_logger.debug("got input3")

network_input_logger = getLogger('input.network')
network_input_logger.debug("got network input1")
network_input_logger.debug("got network input2")

getLogger('output')
output_logger.debug("sent output1")

Then at the end I would like to get a resume, for example:

input: 5
input.network: 2
output: 1

I think by calling a method getcount()for a registrar or handler.

What would be a good way to achieve this? I assume this is due to a subclass of one of the classes in the module logging, but I'm not sure what would be the best way.

+5
source share
2 answers

, , - :

class myDecorator(object):
    def __init__(self, inner):
        self.inner = inner
        self.log = {}

    def __getattr__(self,name):
        self.log[name] = self.log.get(name,0)+1
        return getattr(self.inner,name)

    def __setattr__(self,name,value):
        setattr(self.inner,name,value)

, , . , , .

, , , , . ( )

. , , -, .

class LoggerLogger(object):
    def __init__(self,inner,name):
        self.inner = inner
        self.calls = 0
    def __call__(self,*args,**kwargs):
        self.calls += 1
        return self.inner(*args,**kwargs)


def loggerDecorator(func):
    def inner(name):
        logger = func(name)
        logger.debug = LoggerLogger(logger.debug,name)
    return inner

getLogger = loggerDecorator(getLogger)
+3

, .

Logger LoggerDecorator, , . , -. getCount() .

Python:

http://wiki.python.org/moin/DecoratorPattern

+2

All Articles