在Python Logging Formatter中右/左对齐多个值



为了在日志中左对齐8个字符的levelname值,可以使用%(levelname)-8s

import logging
logging.basicConfig(
level=logging.DEBUG,
format="[%(asctime)s] (%(module)s:%(funcName)s::%(lineno)s) - %(levelname)-8s - %(message)s ",
handlers=[logging.StreamHandler()]
)
def fake_function():
logging.info("This is a info message")
fake_function()

将:

[2023-01-09 18:03:48,842] (example:fake_function::12)-100s -     INFO - This is a info message

然而,我更感兴趣的是左对齐3值(%(module)s:%(funcName)s::%(lineno)s。我想在一个块中完成它,例如:

[2023-01-09 18:07:14,743] (example:fake_function::12)                     - INFO     - This is a info message 
[2023-01-09 18:07:14,745] (another_example:another_fake_function::123456) - INFO     - This is a info message 
[2023-01-09 18:07:14,758] (a:b::1)                                        - INFO     - This is a info message 

我知道我可以分别左对齐这3个值,但是它会在module,funcNamelineno之间留下很多空格,使它对我的口味来说太混乱了。

我试图使用%(%(module)s:%(funcName)s::%(lineno)s)-100s,但它没有工作(它只是打印-100s)。

是否有一种方法来右/左对齐几个值从日志一起作为一个?

您可以设置一个过滤器,将这三个条目合并为一个,并确保将其添加到需要以这种方式输出它们的所有处理程序中,然后在您的格式中引用位置-如以下示例所示:

import logging
def combining_filter(record):
record.location = '(%s:%s:%s)' % (record.module, record.funcName, record.lineno)
return True
h = logging.StreamHandler()
h.addFilter(combining_filter)
logging.basicConfig(
level=logging.DEBUG,
format="[%(asctime)s] %(location)-40s - %(levelname)-8s - %(message)s ",
handlers=[h]
)
def fake_function():
logging.info("This is a info message")
fake_function()

应该打印

[2023-01-09 17:53:49,677] (so_75060822:fake_function:17)           - INFO     - This is a info message 

最新更新