如何在Python logging.Formatter中对齐level字段

时间:2011-10-14 18:25:14

标签: python logging formatting

我目前正试图在我的Python记录器中正确对齐日志记录级别字段,以便输出如下:

[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)

看起来像:

[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)

第一个块的格式行是:

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

如果我知道最大级别长度是8(例如:CRITICAL),那么我将右对齐8个空格。 我试图弄清楚如何实现这一目标。以下错误是因为&#34;%(levelname)s&#34;是超过8个字符(替换不会发生,直到以后)。如果我使用&#34; {0:&gt; 20}&#34; .format&#34;%(levelname)s&#34;之类的东西,那么它可以工作,但这比我需要或想要的填充更多。< / p>

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

没有子类化Formatter,任何人都有办法实现这个目标吗?

2 个答案:

答案 0 :(得分:52)

像这样:

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

答案 1 :(得分:3)

尝试使用此格式行:

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

python logger formatter使用标准python string formatting rules