Logging within a class

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Feb 11 08:41:23 EST 2013


----- Original Message -----
> Within __init__ I setup a log with self.log =
> logging.getLogger('foo') then add a
> console and filehandler which requires the formatting to be
> specified. There a few
> methods I setup a local log object by calling getChild against the
> global log object.
> 
> 
> This works fine until I need to adjust the formatter for a few. With
> this style, I need
> to redefine the handlers, so basically setup logging again.
> 
> 
> I tried to get around this by using basicConfig and simply
>  re-specifying format inside
> the few methods, but it didn't work.
> 
> 
> How does one accomplish this most elegantly so I can define one log
> instance with
> the appropriate general console and file handlers in my class, then
> simply override
> the formatter for both handlers they use in a couple methods?
> 
> 
> Thanks!
> jlc

Hi,

Depend on what type of customization you need, if you need additional fields, that's pretty easy : 
http://docs.python.org/2/howto/logging-cookbook.html#context-info

If you need to completely change the format pattern, I'm not sure there an easy way, thread safe to do such thing. The closest thing that comes to my mind would be to write your own Formatter than can handle multiple formats, depending on the record attributes:

Class MultiFormatter(logging.Formatter):
  def format(record): 
    if record.funcName == 'bar':
      # substitute self._fmt with something else
      
      # then call super(format)
      logging.Formatter(self, record) # not sure this one would be thread safe

Records have a funcName and module attribute, but I'm not sure collision could be handled properly with those.

Maybe the safest thing to do would be to add a contextual info to your log holding a specific format.

class Foo():
  def bar(self):
    self.logger.info("hello", extra = {'format' : "%(message)s}) # would be handled in MultiFormatter

cheers,

JM


-- IMPORTANT NOTICE: 

The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you.


More information about the Python-list mailing list