18

Python logging formats strings with a syntax I don't see elsewhere in python, like

 'format': '%(name)s'

Is there any way to truncate an error message using the formatter, or do I need to override the LogRecord class for that?

This truncates parts of the message (though I can't find the documentation for this feature in the normal places):

 'format': '%(name).40s %(message).40s'

I'd rather truncate the entire formatted message, if possible (for an 80 column console, say).

hobs
  • 18,473
  • 10
  • 83
  • 106

1 Answers1

30

This is just the old style of string formatting. I think you can just use a ".L", where L is the length to truncate the string to whatever length you like. eg:

'format': '%(name).5s'  

would truncate the length to 5 characters.

It's a little hard to find, but they actually do mention it in the docs:

The precision is a decimal number indicating how many digits should be displayed after the decimal point for a floating point value formatted with 'f' and 'F', or before and after the decimal point for a floating point value formatted with 'g' or 'G'. For non-number types the field indicates the maximum field size - in other words, how many characters will be used from the field content

Gerrat
  • 28,863
  • 9
  • 73
  • 101
  • yea I thought of that after writing the question and edited to include your suggestion above (which does work, for individual placeholders in the message). – hobs May 28 '13 at 18:51
  • So I guess my question doesn't really make sense. All you can pass to the formatter is an old-style string formatter. It doesn't make sense to ask about formatting the result of the formatting from within that formatter spec. – hobs May 28 '13 at 18:56
  • 1
    It looks likee you have a little more control in Python 3.2+, since you can override LogRecord Creation: http://plumberjack.blogspot.ca/2010/12/getting-more-control-over-logrecord.html – Gerrat May 28 '13 at 19:44
  • 5
    There's no way to truncate from the left though is there? – OrangeDog Dec 04 '17 at 15:50
  • @OrangeDog: Interesting question, but I don't think so. – Gerrat Dec 04 '17 at 20:00
  • @Gerrat If I'm not mistaken factories are interesting, but the `message` attribute is only created at a later stage. When the factory is called you have only the `msg` and the `args` attribute. – gelonida May 28 '20 at 11:38