Python显示并记录运行时错误到控制台和日志文件

2024-06-12 16:11:58 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的脚本正在将所有错误写入日志文件和控制台,但引发的异常仅写入控制台而不写入日志。如何让它将引发的异常写入日志,或任何运行时异常?谢谢。

import os
import sys
import logging
import logging.config

class Main(object):

    @staticmethod
    def main():
    logging.config.fileConfig("logging.conf")
    logging.debug("1")
    logging.info("2")
    logging.warn("3")
    logging.error("4")
    logging.critical("5")
    raise Exception("test")

if __name__ == "__main__":
    Main.main()


import logging
import logging.config

logging.config.fileConfig('logging.conf')

# create logger
logger = logging.getLogger('simpleExample')

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
raise Exception("Exception raised")

配置文件:

[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0

[handler_fileHandler]
formatter=simpleFormatter
args=('error.log')

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=

Tags: debugimportinfoconfigmessagemainloggingexception
1条回答
网友
1楼 · 发布于 2024-06-12 16:11:58

为了使用logging模块捕获所有错误,第一个要求是使用except语句捕获所有错误。一旦捕捉到它们,就必须根据错误级别调用Logger.exception()或其他合适的函数。

如果不能预先捕获所有异常,最好的方法是将stdoutstderr重定向到文件。然后,执行tail -f来模拟控制台输出。无论如何,一个意外的异常将导致程序停止执行。

但是,我更愿意尝试捕捉所有异常,即使这意味着必须做这样的事情。

try:
    Main.main()
except Exception as e:
    logging.Exception("Unexpected exception! %s",e)

这允许您使用整洁的logging模块,而不必依赖糟糕的输出重定向。

相关问题 更多 >