Ich stellte diese Frage für Python 2 here, stieß aber erneut auf das Problem, wenn die Antwort für Python 3.2.3 nicht mehr funktionierte.Ändern von Protokollierungsnachrichtenformat basierend auf Nachrichtenprotokollierungsgrad in Python3
Hier ist Code, der auf Python arbeitet 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")
Ein Lauf mit 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
Soweit ich das beurteilen kann, Umstellung auf Python3 benötigt nur einen kleinen Mod zu CustomConsoleFormatter. init():
def __init__(self):
super().__init__(fmt="%(levelno)d: %(msg)s", datefmt=None, style='%')
auf 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
Wie Sie sehen können, mein Wunsch zu ersetzen '10' mit 'DEBUG' vereitelt wird.
Ich habe versucht, in Python3 Quelle herum zu graben und es sieht aus wie die PercentStyle Instanziierung ist Clobbering self._fmt nach mir, na ja, es selbst Clobber.
Meine Logging Chops stoppen nur kurz in der Lage, um diese Falte zu arbeiten.
Kann jemand einen anderen Weg empfehlen oder vielleicht darauf hinweisen, was ich übersehe?