Python traceback.print_exc() returns 'None'

Python traceback.print_exc() returns 'None'

这个函数应该在主执行中捕获异常。如果有异常,它应该用 log.error(traceback.print_exc()) 打印出错误并用 exit_main().

清理
def main():
    try:
        exec_app()
    except KeyboardInterrupt:
        log.error('Error: Backup aborted by user.')
        exit_main()
    except Exception:
        log.error('Error: An Exception was thrown.')
        log.error("-" * 60)
        log.error(traceback.print_exc())
        log.error("-" * 60)
        exit_main()

不幸的是,log.error(traceback.print_exc()) 仅在出现异常时才执行 return None。在这种情况下,如何使回溯打印完整的错误报告?

PS:我用的是python3.4.

来自其__doc__

Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'

也就是说,它不应该 return 任何东西,它的工作是打印。如果您希望将回溯记录为字符串,请改用 traceback.format_exc()

我通常使用 traceback.print_exc() 只是为了调试。在您的情况下,要记录您的异常,您只需执行以下操作:

try:
    # Your code that might raise exceptions
except SomeSpecificException as e:
    # Do something (log the exception, rollback, etc)
except Exception as e:
    log.error(e)  # or log(e.message) if you want to log only the message and not all the error stack