Python:记录设置,允许多行字符串:logging.info('foo \nbar')

gue*_*tli 5 python logging

到目前为止,我只是简单地记录到文件,如果我记录多行字符串,那么结果如下所示:

发送日志:

logging.info('foo\nbar') 
Run Code Online (Sandbox Code Playgroud)

日志文件:

2018-03-05 10:51:53 root.main +16: INFO     [28302] foo
Run Code Online (Sandbox Code Playgroud)

酒吧

到目前为止,所有不包含"INFO"或"DEBUG"的行都会报告给运营商.

这意味着该行bar被报告.这是误报.

环境:Linux.

如何在Python中设置日志记录以将INFO保留foo\nbar在一个字符串中并忽略整个字符串,因为它只是"INFO"?

注意:是的,您可以过滤解释器中的日志记录.不幸的是,这不是问题所在.这个问题不同.首先记录日志.然后解析日志.

这是一个重现它的脚本:

import sys
import logging


def set_up_logging(level=logging.INFO):
    root_logger = logging.getLogger()
    root_logger.setLevel(level)
    handler = logging.StreamHandler(sys.stdout)
    handler.setFormatter(
        logging.Formatter('%(asctime)s %(name)s: %(levelname)-8s [%(process)d] %(message)s', '%Y-%m-%d %H:%M:%S'))
    root_logger.addHandler(handler)


def main():
    set_up_logging()
    logging.info('foo\nbar')


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

在再次考虑之后,我认为真正的问题是:哪种日志格式是可行的?只是删除跨越多行的消息中的换行符会使人眼难以阅读某些输出.另一方面,logging.info()与日志文件中的一行之间的当前1:1关系易于阅读.......我不确定

urb*_*ban 6

我通常有一个类来自定义日志记录,但您可以通过自定义实现您想要的logging.Formatter:

import logging

class NewLineFormatter(logging.Formatter):

    def __init__(self, fmt, datefmt=None):
        """
        Init given the log line format and date format
        """
        logging.Formatter.__init__(self, fmt, datefmt)


    def format(self, record):
        """
        Override format function
        """
        msg = logging.Formatter.format(self, record)

        if record.message != "":
            parts = msg.split(record.message)
            msg = msg.replace('\n', '\n' + parts[0])

        return msg
Run Code Online (Sandbox Code Playgroud)

format()上面的函数拆分行并复制每行中的timestamp/logging-preamble(每个后\n)

现在您需要将格式化程序附加到根记录器.handler如果您构建自己的日志记录设置/结构,您实际上可以将它附加到任何:

# Basic config as usual
logging.basicConfig(level=logging.DEBUG)

# Some globals/consts
DATEFORMAT = '%d-%m-%Y %H:%M:%S'
LOGFORMAT = '%(asctime)s %(process)s %(levelname)-8s %(filename)15s-%(lineno)-4s: %(message)s'

# Create a new formatter
formatter = NewLineFormatter(LOGFORMAT, datefmt=DATEFORMAT)

# Attach the formatter on the root logger
lg = logging.getLogger()

# This is a bit of a hack... might be a better way to do this
lg.handlers[0].setFormatter(formatter)


# test root logger
lg.debug("Hello\nWorld")

# test module logger + JSON
lg = logging.getLogger("mylogger")
lg.debug('{\n    "a": "Hello",\n    "b": "World2"\n}')
Run Code Online (Sandbox Code Playgroud)

以上给出了:

05-03-2018 08:37:34 13065 DEBUG     test_logger.py-47  : Hello
05-03-2018 08:37:34 13065 DEBUG     test_logger.py-47  : World
05-03-2018 08:37:34 13065 DEBUG     test_logger.py-51  : {
05-03-2018 08:37:34 13065 DEBUG     test_logger.py-51  :     "a": "Hello",
05-03-2018 08:37:34 13065 DEBUG     test_logger.py-51  :     "b": "World2"
05-03-2018 08:37:34 13065 DEBUG     test_logger.py-51  : }
Run Code Online (Sandbox Code Playgroud)

请注意,我正在访问.handlers[0]根记录器,这有点像黑客,但我无法找到解决方法......另外,请注意格式化的JSON打印:)