簡體   English   中英

如何使用 python 日志模塊打印多行日志?

[英]How to print multiline logs using python logging module?

我想使用 python 日志模塊創建多行記錄器。 當我使用下面的代碼片段來格式化記錄器時:

import logging
logger = logging.getLogger(file_name)
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

當我使用logger.info("""line 1\\nline 2\\n line 3""")時,我得到以下多行日志的輸出

2017-07-20 13:21:14,754 - my_logger.py - INFO - line 1
line 2
line 3

我希望我的輸出如下:

2017-07-20 13:21:14,754 - my_logger.py - INFO - line 1
2017-07-20 13:21:14,754 - my_logger.py - INFO - line 2
2017-07-20 13:21:14,754 - my_logger.py - INFO - line 3

您可以創建自己的格式化程序:

import logging
class MultilineFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord):
        save_msg = record.msg
        output = ""
        for line in save_msg.splitlines():
            record.msg = line
            output += super().format(record) + "\n"
        record.msg = save_msg
        record.message = output
        return output

比修改您的記錄器初始化如下:

formatter = MultilineFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

簡短的回答,你不能。 可以執行以下操作:

logger.info('line 1')
logger.info('line 2')
logger.info('line 3')

或者如果你有多行的東西,你可以這樣做:

map(logger.info, 'line 1\nline 2\nline 3'.split('\n'))

這些不會同時出現,但會非常接近......

如果我只使用單個日志級別(警告或信息或類似級別),我更願意使用輔助函數來執行此操作:

def multiline_warning(header, body):
  for line in body.splitlines():
    logging.warning(f"{header}: {line}")

在上下文中,只需調用:

multiline_warning("stderr", subprocess_result.stderr)

如果使用多個(CRITICAL、ERROR、WARNING、INFO 或 DEBUG),您可以抽象日志級別並將其作為參數傳遞,並使用 logging.log 代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM