tags:

views:

33

answers:

2

Hi,

I'm trying to reformat the output data sent to the logger based on it's class.

For example:

  • strings will be printed as they are
  • dictionaries/lists will be automatically indented/beautified into html
  • my custom classes will be handled on an individual basis and converted to html

My problem is that the message sent to the formatter is always a string. The documentation specifically says that you can send objects as messages, but it seems to be converting the objects to strings before I can format them.

class MyFormatter(logging.Formatter):

    def format(self, record):
        #The problem is that record.message is already a string...
        ...

Where is the appropriate place for me to handle objects sent as messages?

A: 

Maybe in the __str__() method of the objects you are logging?

llasram
+1  A: 

Ok, I've figured it out.

The documentation in the official docs is a little bit unclear, but basically, there are two attributes

LogRecord.message -> a string representation of the message and LogRecord.msg -> the message itself.

To get the actual object, you must reference the .msg for it to work.

I hope this was useful to someone else.

Bill Zimmerman
The LogRecord should not contain a .message except if it has been formatted by the default Formatter (or a costum Formatter that adds a .message). Perhaps either you have a multiple handler or you are calling the Formatter.format(record) from your derived function, which should be unnecessary?
Lie Ryan
You are correct. I'm not explicitly calling the parent classes format(), however, I haven't overridden the default __init__, so I suspect that has something to do with it.
Bill Zimmerman