python logging.StreamHandler()的包装输出

bra*_*tor 3 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)
Run Code Online (Sandbox Code Playgroud)

并希望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
Run Code Online (Sandbox Code Playgroud)

我应该从哪里开始?

Jas*_*n S 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)
Run Code Online (Sandbox Code Playgroud)

输出:

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.
Run Code Online (Sandbox Code Playgroud)