我在这里为 python 2 提出了这个问题,但是当答案不再适用于 Python 3.2.3 时,我又遇到了这个问题。
这是适用于 Python 2.7.3 的代码:
import logging
# Attempt to set up a Python3 logger than will print custom messages
# based on each message's logging level.
# The technique recommended for Python2 does not appear to work for
# Python3
class CustomConsoleFormatter(logging.Formatter):
"""
Modify the way DEBUG messages are displayed.
"""
def __init__(self, fmt="%(levelno)d: %(msg)s"):
logging.Formatter.__init__(self, fmt=fmt)
def format(self, record):
# Remember the original format
format_orig = self._fmt
if record.levelno == logging.DEBUG:
self._fmt = "DEBUG: %(msg)s"
# Call the original formatter to do the grunt work
result = logging.Formatter.format(self, record)
# Restore the original format
self._fmt = format_orig
return result
# Set up a logger
my_logger = logging.getLogger("my_custom_logger")
my_logger.setLevel(logging.DEBUG)
my_formatter = CustomConsoleFormatter()
console_handler = logging.StreamHandler()
console_handler.setFormatter(my_formatter)
my_logger.addHandler(console_handler)
my_logger.debug("This is a DEBUG-level message")
my_logger.info("This is an INFO-level message")
使用 Python 2.7.3 运行:
tcsh-16: python demo_python_2.7.3.py
DEBUG: This is a DEBUG-level message
20: This is an INFO-level message
据我所知,转换为 Python3 只需要对 CustomConsoleFormatter 稍作修改。初始化():
def __init__(self):
super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=None, style='%')
在 Python 3.2.3 上:
tcsh-26: python3 demo_python_3.2.3.py
10: This is a DEBUG-level message
20: This is an INFO-level message
如您所见,我用“DEBUG”替换“10”的愿望被挫败了。
我已经尝试在 Python3 源代码中进行挖掘,看起来 PercentStyle 实例化正在破坏 self._fmt 在我自己破坏它之后。
我的伐木工作很快就无法解决这个皱纹了。
谁能推荐另一种方式,或者指出我忽略了什么?