【问题标题】:Python: setup of logging, allowing multiline strings: logging.info('foo\nbar')Python:设置日志记录,允许多行字符串:logging.info('foo\nbar')
【发布时间】:2018-03-01 11:45:43
【问题描述】:

到目前为止,我对文件进行了简单的日志记录,如果我记录了多行字符串,则结果如下所示:

发出日志:

logging.info('foo\nbar') 

日志文件:

2018-03-05 10:51:53 root.main +16: INFO     [28302] foo

酒吧

到目前为止,所有不包含“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()

再想一想,我觉得真正的问题是:哪种日志记录格式是可行的?仅删除跨越多行的消息中的换行符会使人眼难以阅读某些输出。另一方面,当前 logging.info() 和日志文件中的一行之间的 1:1 关系很容易阅读。 ...我不确定

【问题讨论】:

  • 你能显示你的日志设置行吗?像logging.basicConfig(.. 一样,还可以显示您想要的不同日志级别的输出到底是什么?
  • @Chris_Rands 我添加了一个脚本来重现它。你的问题“你想要的输出到底是什么?”非常好。我没有任何线索。到目前为止,我们解析日志文件并假设每一行都是一个日志条目。我想目前的模式不再可行。什么是最简单、理智、最 Pythonic 的解决方案?
  • 我在想(对我来说很少见:)) - 你用什么来解析日志?增强该部分可能更容易且更一致,特别是如果您不想修改 python 源代码。例如,在我下面的解决方案中,您最终可能会收到 2 个或更多警报,其中没有一个包含完整消息! (取决于解析器的工作方式)。不过,这需要一个单独的问题...
  • 您可以使用logging.info(json.dumps(message)),它将返回一个包含转义换行符的字符串。或者,您可以创建一个自动执行此操作的自定义 Formatter 类。

标签: python logging


【解决方案1】:

我通常有一个类来自定义日志记录,但您可以使用自定义 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

上面的 format() 函数拆分行并在每行中复制时间戳/日志记录前导码(在每个 \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}')

以上为您提供:

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  : }

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

【讨论】:

  • 希望这个问题可以通过配置解决。但是看来您需要进行编程....但是您的答案当然比没有解决方案要好得多:-)
  • 我明白了...上面的代码/解决方案来自 3 年前!所以在这个时候logging 可能已经引入了一种更好的方法来做到这一点。但是,当时我找不到任何东西。
  • 使用第 3 方 structlog 及其处理器堆栈会容易得多。
【解决方案2】:

我认为保持这种 1:1 的关系,即每个 logging.info() 调用的日志文件中的一行,对于保持日志文件的简单和可解析是非常可取的。因此,如果您确实需要记录换行符,那么我将简单地记录 字符串表示,例如:

logging.info(repr('foo\nbar'))

输出:

2018-03-05 11:34:54 root: INFO     [32418] 'foo\nbar'

一个简单的替代方法是分别记录每个部分:

log_string = 'foo\nbar'
for item in log_string.split('\n'):
    logging.info(item)

输出:

2018-03-05 15:39:44 root: INFO     [4196] foo
2018-03-05 15:39:44 root: INFO     [4196] bar

【讨论】:

  • 我不确定。我从 1996 年开始使用 Linux,并且非常喜欢简单的基于 ascii 的解决方案。但也许是时候切换到这里了?这种 1:1 的关系自古就有。可以用什么来代替它?如果您只是删除换行符,事情可能会变得不可读。
【解决方案3】:

你可以使用:

logging.basicConfig(level=your_level)

your_level 是其中之一:

  'debug': logging.DEBUG,
  'info': logging.INFO,
  'warning': logging.WARNING,
  'error': logging.ERROR,
  'critical': logging.CRITICAL

在您的情况下,您可以使用警告来忽略信息

import logging
logging.basicConfig(filename='example.log',level=logging.WARNING)

logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

Output:
WARNING:root:And this, too

您可以尝试在登录为之前禁用 INFO

import logging
logging.basicConfig(filename='example.log')

logging.debug('This message should go to the log file')
logging.disable(logging.INFO)
logging.info('So should this')
logging.disable(logging.NOTSET)
logging.warning('And this, too')
Output:
WARNING:root:And this, too

或者

logger.disabled = True
someOtherModule.function()
logger.disabled = False

【讨论】:

  • 是的,您可以在解释器中过滤日志记录。不幸的是,这不是问题所在。这个问题不一样。首先发生日志记录。然后解析日志。
  • @guettli 我已经编辑了我的答案,以便您可以在生成日志之前禁用 INFO。
  • 我希望 INFO 出现在日志文件中。这个问题是关于日志文件的解析/读取/分析。
猜你喜欢
  • 2012-02-02
  • 1970-01-01
  • 2021-11-06
  • 2014-05-21
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多