Python logging.StreamHandler() 的封装输出

3 投票
1 回答
1493 浏览
提问于 2025-04-18 06:52

我使用了多个处理程序,比如

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进行正确的包装和缩进,像这样

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

我应该从哪里开始呢?

1 个回答

6

需要注意的是,这样做确实会对你保存的日志造成不好的影响,因为它会破坏像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.

撰写回答