如何在Pythonlogging.Formatter中右对齐级别字段
我目前正在尝试右对齐 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个空格。 我正在努力弄清楚如何实现这一目标。以下操作失败,因为“%(levelname)s”超过 8 个字符(替换直到稍后才会发生)。如果我使用类似“{0:>20}”.format“%(levelname)s”的内容,那么它可以工作,但这比我需要或想要的填充更多。
logging.Formatter("[%(asctime)s] [" + "{0:>8}".format"%(levelname)s" + "] --- %(message)s (%(filename)s:%(lineno)s)", "%Y-%m-%d %H:%M:%S")
除了子类化 Formatter 之外,有人有办法实现这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样:
PS:如果您希望 INFO 左对齐,可以使用
[%(levelname)-8s]
代替。Like this:
PS: If you would like INFO to be left aligned, you can use
[%(levelname)-8s]
instead.尝试使用此格式行:
python 记录器格式化程序使用标准 python 字符串格式化规则< /a>
Try with this format line :
python logger formatter use the standard python string formatting rules