[Python-Dev] Passing contextual information when logging

Nick Coghlan ncoghlan at gmail.com
Fri Jan 11 16:18:57 CET 2008


Vinay Sajip at Red Dove wrote:
> One solution is to create a generic wrapper around loggers to which a logger
> name and contextual information can be passed. The wrapper would delegate
> logging calls to the logger with the specified name, but would manipulate
> the arguments passed to the logging call to insert the contextual
> information. I have created such a wrapper class, called LoggerAdapter,
> which is in the example script located at
> 
> http://dpaste.com/30613/
> 
> I would welcome your views on whether the LoggerAdapter class is suitable
> for adding to the logging package in Python 2.6/3.0. Does it do what might
> reasonably be expected out of the box? LoggerAdapters are, of course,
> garbage collected in the normal way and so impose no particular memory
> burden.

It looks pretty good (and useful) to me, but I have a couple of questions.

When you talk about stacking in the constructor docstring, do you mean 
something like having LoggerAdapterA delegating to LoggerAdapterB which 
in turn delegates to the real logger?

If that's what you mean, then I think the process() method will need to 
be changed to handle the case where there is already an "extras" entry 
in the keyword arguments. If that's not what you mean... then please 
explain because I don't have any other ideas :)

I was also going to suggest modifying the constructor to accept keyword 
arguments, but realised that case can be adequately handled just by 
using a dict:

   logger_with_extra = LoggerAdapter(logger, dict(attr1=5, attr2=True))

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list