You can set a different logging level for each logging handler but it seems you will have to set the logger's level to the "lowest".
(您可以为每个日志记录处理程序设置不同的日志记录级别,但是似乎您必须将记录器的级别设置为“最低”。)
In the example below I set the logger to DEBUG, the stream handler to INFO and the TimedRotatingFileHandler to DEBUG. (在下面的示例中,我将记录器设置为DEBUG,将流处理程序设置为INFO,并将TimedRotatingFileHandler设置为DEBUG。)
So the file has DEBUG entries and the stream outputs only INFO. (因此,该文件具有DEBUG条目,并且流仅输出INFO。)
You can't direct only DEBUG to one and only INFO to another handler. (您不能仅将DEBUG定向到一个,而只能将INFO定向到另一个处理程序。)
For that you'll need another logger. (为此,您将需要另一个记录器。)
logger = logging.getLogger("mylog")
formatter = logging.Formatter(
'%(asctime)s | %(name)s | %(levelname)s: %(message)s')
logger.setLevel(logging.DEBUG)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)
logFilePath = "my.log"
file_handler = logging.handlers.TimedRotatingFileHandler(
filename=logFilePath, when='midnight', backupCount=30)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
logger.info("Started");
try:
x = 14
y = 0
z = x / y
except Exception as ex:
logger.error("Operation failed.")
logger.debug(
"Encountered {0} when trying to perform calculation.".format(ex))
logger.info("Ended");
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…