我使用多个处理程序,例如
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/