【发布时间】:2017-10-12 06:03:48
【问题描述】:
这应该是一个非常简单的问题,但是在谷歌搜索、阅读文档和其他几个 SO 线程之后,我没有看到答案:如何使用 Python 标准日志记录异常?一个小问题是我从未来得到了例外。我自己不是在编写except 异常处理程序。理想情况下,我会得到异常消息、堆栈跟踪、发送的额外消息以及异常类型。这是一个显示我的问题的简单程序:
import logging
from concurrent.futures import ThreadPoolExecutor
logger = logging.getLogger(__name__)
def test_f(a, b=-99, c=50):
logger.info("test_f a={} b={} c={}".format(a, b, c))
def future_callback_error_logger(future):
e = future.exception()
if e is not None:
# This log statement does not seem to do what I want.
# It logs "Executor Exception" with no information about the exception.
# I would like to see the exception type, message, and stack trace.
logger.error("Executor Exception", exc_info=e)
def submit_with_log_on_error(executor, func, *args, **kwargs):
future = executor.submit(func, *args, **kwargs)
future.add_done_callback(future_callback_error_logger)
if __name__ == "__main__":
logging.basicConfig(level="DEBUG")
logger.info("start")
executor = ThreadPoolExecutor(max_workers=5)
# This will work.
submit_with_log_on_error(executor, test_f, 10, c=20)
# This will intentionally trigger an error due to too many arguments.
# I would like that error to be properly logged.
submit_with_log_on_error(executor, test_f, 10, 20, 30, 40)
# This will work.
submit_with_log_on_error(executor, test_f, 50, c=60)
executor.shutdown(True)
logger.info("shutdown")
【问题讨论】:
标签: python exception logging exception-handling