python logging, handling multiline log entries

Jean-Michel Pichavant jeanmichel at sequans.com
Thu Nov 4 07:57:52 EDT 2010


Jean-Michel Pichavant wrote:
> Hi python fellows,
>
> I'm looking to do the following :
>
> import logging
>
> l = logging.getLogger('aHeader')
> l.handlers = []
> l.addHandler(logging.StreamHandler())
> l.handlers[-1].setFormatter(logging.Formatter("%(asctime)s - %(name)s 
> - %(message)s"))
> l.error('1st line\n2nd line')
>
> output:
> 2010-11-04 12:22:05,593 - aHeader - 1st line
> 2nd line
>
>
>
> I'd like to get something like:
> 2010-11-04 12:22:05,593 - aHeader - 1st line
>                                    2nd line
>
> I don't want to get the header on every line, otherwise I would just 
> need to log every lines.
>
> Is there a simple way of doing that? anyone already gave a though on 
> that ?
>
> The main problem I'm facing is that I cannot alter the log entry 
> itself, I don't know the size of the header and I think it would be 
> anti-pattern. My guess is that it should be handled in  the formatter, 
> overriding the format method, but how do you get the header size (i.e. 
> the indentation size).
>
> So if anyone has a piece of code doing that, feel free to point it to me.
>
> Cheers,
>
> JM
>
>
>
You can ignore me, I just found an acceptable solution (i think).
You guys still have been usefull because writing this mail helped me 
structure my thoughts :o)

JM

PS:
class MultiLineFormatter(logging.Formatter):
    def format(self, record):
        str = logging.Formatter.format(self, record)
        header, footer = str.split(record.message)
        str = str.replace('\n', '\n' + ' '*len(header))
        return str

There could be a problem if "%(message)s" is not in the formatter 
string, but honestly, who would be doing that :)





More information about the Python-list mailing list