How to right align level field in Python logging.Formatter
Asked Answered
S

2

67

I'm currently trying to right align the logging level field in my Python logger so that output such as:

[2011-10-14 13:47:51] [DEBUG] --- starting... (smtphandlers.py:96)
[2011-10-14 13:47:51] [INFO] --- first things first... (smtphandlers.py:97)
[2011-10-14 13:47:51] [WARNING] --- about to end... (smtphandlers.py:98)
[2011-10-14 13:47:51] [DEBUG] --- ending (smtphandlers.py:99)

instead looks like:

[2011-10-14 13:47:51] [   DEBUG] --- starting... (smtphandlers.py:96)
[2011-10-14 13:47:51] [    INFO] --- first things first... (smtphandlers.py:97)
[2011-10-14 13:47:51] [ WARNING] --- about to end... (smtphandlers.py:98)
[2011-10-14 13:47:51] [   DEBUG] --- ending (smtphandlers.py:99)

The format line for the first block is:

logging.Formatter("[%(asctime)s] [%(levelname)s] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S")

If I know the max level length is 8 (eg: CRITICAL), then I'll right align to 8 spaces. I'm trying to figure out how to achieve this. The following fails because "%(levelname)s" is more than 8 characters (the substitution doesn't happen until later). If I use something like "{0:>20}".format"%(levelname)s", then it works, but that is more padding than I need or want.

logging.Formatter("[%(asctime)s] [" + "{0:>8}".format"%(levelname)s" + "] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S")

Short of subclassing Formatter, anyone have a way to achieve this?

Sigrid answered 14/10, 2011 at 18:25 Comment(1)
The %(...)s is called printf-style String Formatting. We're able to adjust the string width by setting the "minimum field width" or left align the content by using a "-" (dash or hyphen) "conversion flags".Wales
P
121

Like this:

logging.Formatter("[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S")

PS: If you would like INFO to be left aligned, you can use [%(levelname)-8s] instead.

Prescribe answered 14/10, 2011 at 18:31 Comment(2)
@AlexL What about center aligned?Hwang
@JoeVictor Late to the party but this can be done by setting the style parameter for the Formatter object to { and doing something like [{levelname:^8s}].Pigpen
A
16

Try with this format line :

logging.Formatter("[%(asctime)s] [%(levelname)8s] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S")

python logger formatter use the standard python string formatting rules

Atomizer answered 14/10, 2011 at 18:28 Comment(1)
%8(levelname)s won't work, it needs to be %(levelname)8s.Prescribe

© 2022 - 2024 — McMap. All rights reserved.