如何使用记录器在 Python 中的一行中打印列表

Jek*_*ONG 9 python logging python-3.x

我想在 Python 3.6 中仅使用一行登录来打印列表。目前我的代码看起来像这样。

logger = logging.getLogger()
logger.setLevel(log_level)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(log_level)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch.setFormatter(formatter)
logger.addHandler(ch)

# some codes in-between

num_list = [1, 2, 3, 4, 5]
logger.info("Numbers in num_list are: ")
for item in num_list:
    logger.info(item)
Run Code Online (Sandbox Code Playgroud)

我想得到的是

2018-07-23 17:29:30,200 - root - INFO - Numbers in num_list are: 1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)

但是,我会得到

2018-07-23 17:29:30,200 - root - INFO - Numbers in num_list are:
2018-07-23 17:29:30,200 - root - INFO - 1
2018-07-23 17:29:30,200 - root - INFO - 2
2018-07-23 17:29:30,200 - root - INFO - 3
2018-07-23 17:29:30,200 - root - INFO - 4
2018-07-23 17:29:30,200 - root - INFO - 5
Run Code Online (Sandbox Code Playgroud)

我知道如果我曾经print输出,我可以使用print(item, end=" ")显式更改输出后面的内容。但是,日志记录似乎不接受end作为输入参数。

有没有人有任何想法如何获得所需的输出?非常感谢!

idb*_*rii 10

您可以将格式字符串和参数传递给logging.

文档使用这个例子debug()

d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logging.warning('Protocol problem: %s', 'connection reset', extra=d)
Run Code Online (Sandbox Code Playgroud)

对于您的情况,您可以将其num_list作为字符串传递给格式字符串,它会为您漂亮地打印它。

>>> num_list = [1, 2, 3, 4, 5, ]
>>> logger.info("Numbers in num_list are: %s", num_list)
INFO: Numbers in num_list are: [1, 2, 3, 4, 5]

>>> num_list = [1, 2, 3, 4, 5, [44,454,54], { "aa": 234} ]
>>> logger.info("Complex example: %s", num_list)
INFO: Complex example: [1, 2, 3, 4, 5, [44, 454, 54], {'aa': 234}]
Run Code Online (Sandbox Code Playgroud)

正如@Maico Timmerman 指出的:

最好让日志记录模块使用 % 语法进行实际格式化,因为可能根本不会打印消息。


Jor*_*rmc 8

您正在使用 for 循环,它遍历您的所有列表并一一记录它尝试:logger.info("Numbers in num_list are: {}".format(' '.join(map(str, num_list))))将它们全部发布一次

请参阅:https : //docs.python.org/3/library/stdtypes.html?highlight=str#str.join