上述解决方案适用于 3.3.3 版本。但是,对于 3.3.4,您会收到以下错误。
FORMATS = { logging.DEBUG : logging._STYLES['{']("{module} DEBUG: {lineno}: {message}"),
TypeError:“元组”对象不可调用
在日志类 Lib\logging__init__.py 中搜索后,我发现导致问题的数据结构已从 3.3.3 更改为 3.3.4
3.3.3
_STYLES = {
'%': PercentStyle,
'{': StrFormatStyle,
'$': StringTemplateStyle
}
3.3.4
_STYLES = {
'%': (PercentStyle, BASIC_FORMAT),
'{': (StrFormatStyle, '{levelname}:{name}:{message} AA'),
'$': (StringTemplateStyle, '${levelname}:${name}:${message} BB'),
}
因此,更新的解决方案是
class SpecialFormatter(logging.Formatter):
FORMATS = {logging.DEBUG : logging._STYLES['{'][0]("{module} DEBUG: {lineno}: {message}"),
logging.ERROR : logging._STYLES['{'][0]("{module} ERROR: {message}"),
logging.INFO : logging._STYLES['{'][0]("{module}: {message}"),
'DEFAULT' : logging._STYLES['{'][0]("{module}: {message}")}
def format(self, record):
# Ugly. Should be better
self._style = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT'])
return logging.Formatter.format(self, record)