example of logging w/ user-defined keywords?

Peter Hansen peter at engcorp.com
Wed Apr 12 08:56:28 EDT 2006


Chris Curvey wrote:
> Several things that I've read lead me to think this is possible, but I
> can't figure out how to do it.  I have some information (a "job
> number")  that I would like logged on every log message, just like the
> time or the severity.
> 
> I saw some mail threads that suggested that there was an easy way to do
> this, but I havent' found any examples.  Is there a simple way to do
> this, or do I need to write my own logger subclass?

class MyClass:
     def __init__(self, name, job):
        self.logger = logging.getLogger(name)
        self.job = job


     def log(self, msg):
        self.logger.debug('#%d: %s' % (self.job, msg)


Then just call self.log('foo') whenever you want to log something.

If this isn't sufficient please describe what requirements you have that 
it doesn't meet.  (Subclassing Logger is certainly a simple way to do it 
though... in that case you would just pass the job number to the 
subclass when you construct it and it could do something like that above.

-Peter




More information about the Python-list mailing list