Overriding a global
Antoon Pardon
antoon.pardon at rece.vub.ac.be
Tue Dec 13 04:15:41 EST 2011
On 12/10/2011 09:47 PM, Roy Smith wrote:
> I've got a code pattern I use a lot. In each module, I create a logger
> for the entire module and log to it all over:
>
> logger = logging.getLogger('my.module.name')
>
> class Foo:
> def function(self):
> logger.debug('stuff')
> logger.debug('other stuff')
>
> and so on. This works, but every once in a while I decide that a
> particular function needs a more specific logger, so I can adjust the
> logging level for that function independent of the rest of the module.
> What I really want to do is:
>
> def function(self):
> logger = logger.getChild('function')
> logger.debug('stuff')
> logger.debug('other stuff')
>
> which lets me not have to change any lines of code other than inserting
> the one to redefine logger. Unfortunately, that's not legal Python (it
> leads to "UnboundLocalError: local variable 'logger' referenced before
> assignment").
>
> Any ideas on the best way to implement this?
>
How about two global references:
globallogger = logger = logging.getLogger('my.module.name')
def function(self):
logger = globallogger.getChild('function')
logger.debug('stuff')
logger.debug('other stuff')
--
Antoon Pardon
More information about the Python-list
mailing list