python - python logging.StreamHandler() 的包装输出

标签 python logging word-wrap

我使用多个处理程序,例如

rootLogger = logging.getLogger()
rootLogger.basicConfig(filename = logfile, level=logging.INFO)
consLogger = logging.StreamHandler()
consLogger.setFormatter(logging.Formatter('%(asctime)-8s %(levelname)-8s %(message)s', '%H:%M:%S'))
consLogger.setLevel(logging.DEBUG)
rootLogger.addHandler(consLogger)

并希望 consLogger(只是 consLogger,而不是所有日志处理程序)被正确包装和缩进,例如

11:03:46 DEBUG text
11:03:47 DEBUG text again
11:03:47 DEBUG some text that is longer than current cons
               ole width or at least some pre-defined lin
               e length

我应该从哪里开始?

最佳答案

需要注意的是,这确实对您要保存的任何日志都不利(因为它会破坏 grep 或类似的逐行搜索),您可以通过简单的方法做到这一点与 textwrap 模块和自定义 logging.Formatter 子类一起使用。

textwrap 是一个标准库模块,可以对段落进行换行,还可以应用缩进和一些其他格式。真正需要的是通过创建一个自定义格式化程序类来连接它,该类覆盖 format() 方法(它处理将整个日志消息放在一起,而不是处理部分的其他一些方法):

import logging
import textwrap

class WrappedFixedIndentingLog(logging.Formatter):
    def __init__(self, fmt=None, datefmt=None, style='%', width=70, indent=4):
        super().__init__(fmt=fmt, datefmt=datefmt, style=style)
        self.wrapper = textwrap.TextWrapper(width=width, subsequent_indent=' '*indent)

    def format(self, record):
        return self.wrapper.fill(super().format(record))

# standard stuff
rootLogger = logging.getLogger()
rootLogger.setLevel(logging.DEBUG)
consLogger = logging.StreamHandler()
rootLogger.addHandler(consLogger)

# indent=18 matches fixed width of asctime + levelname + spaces
consLogger.setFormatter(WrappedFixedIndentingLog(
    '%(asctime)-8s %(levelname)-8s %(message)s', '%H:%M:%S', indent=18))

message = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
rootLogger.log(logging.DEBUG, message)

输出:

18:48:56 DEBUG    Lorem ipsum dolor sit amet, consectetur adipisicing
                  elit, sed do eiusmod tempor incididunt ut labore et
                  dolore magna aliqua. Ut enim ad minim veniam, quis
                  nostrud exercitation ullamco laboris nisi ut aliquip
                  ex ea commodo consequat. Duis aute irure dolor in
                  reprehenderit in voluptate velit esse cillum dolore
                  eu fugiat nulla pariatur. Excepteur sint occaecat
                  cupidatat non proident, sunt in culpa qui officia
                  deserunt mollit anim id est laborum.

关于python - python logging.StreamHandler() 的包装输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23714981/

相关文章:

html - 断行长句的方法

python - 如何使 Django 中的代码仅在 debug 设置为 true 时运行

Python TkMessageBox 问题不工作!

python - 如何使用 Python 遍历 MySQL 表?

mysql - 用于 INSERT INTO 的 awk General-query.log

python - Django uWSGI 创建日志文件但该文件为空(适用于开发服务器)

java - 如何为动态Web项目创建log4j.xml文件?

html - 使 float div 填充整个父级宽度

blackberry - 自动换行在带有自定义 GridField Manager 的 BB 中不起作用

python - 解释训练损失/准确性与验证损失/准确性