是否可以根据消息日志级别修改Python的日志记录格式? [英] Can Python's logging format be modified depending on the message log level?
问题描述
我正在使用Python的logging
机制将输出打印到屏幕上.我可以使用print语句来做到这一点,但是我想允许用户调整更好的粒度以禁用某些类型的输出.我喜欢为错误而打印的格式,但是当输出级别为信息"时,我希望使用一种更简单的格式.
I'm using Python's logging
mechanism to print output to the screen. I could do this with print statements, but I want to allow a finer-tuned granularity for the user to disable certain types of output. I like the format printed for errors, but would prefer a simpler format when the output level is "info."
例如:
logger.error("Running cmd failed")
logger.info("Running cmd passed")
在此示例中,我希望以不同的方式打印错误的格式:
In this example, I would like the format of the error to be printed differently:
# error
Aug 27, 2009 - ERROR: Running cmd failed
# info
Running cmd passed
是否可以在没有多个日志记录对象的情况下针对不同的日志级别使用不同的格式?我宁愿在创建记录器后也无需修改它,因为有大量的if/else语句来确定如何记录输出.
Is it possible to have different formats for different log levels without having multiple logging objects? I'd prefer to do this without modifying the logger once it's created since there are a high number of if/else statements to determine how the output should be logged.
推荐答案
是的,您可以通过自定义Formatter
类来实现此目的:
Yes, you can do this by having a custom Formatter
class:
class MyFormatter(logging.Formatter):
def format(self, record):
#compute s according to record.levelno
#for example, by setting self._fmt
#according to the levelno, then calling
#the superclass to do the actual formatting
return s
然后将MyFormatter
实例附加到您的处理程序.
Then attach a MyFormatter
instance to your handlers.
这篇关于是否可以根据消息日志级别修改Python的日志记录格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!