1

How can I log an exception object with its traceback in Python 3, using the standard logging module?

Note that the exception in question isn't necessarily the one currently being handled.

2 Answers 2

5

Logger objects accept an exc_info argument to include exception information (including traceback), which is expected to be a tuple containing the exception's class, the exception itself and the exception's traceback. The trickiest part is to get hold of the traceback, but it turns out that since Python 3.0, exceptions have a __traceback__ attribute:

logger = logging.getLogger()
exc_info = (type(exc), exc, exc.__traceback__)
logger.error('Exception occurred', exc_info=exc_info)
Sign up to request clarification or add additional context in comments.

3 Comments

For Python 2.7 you can use sys.exc_info() to get the traceback of the exception currently being handled.
@LukasGraf I know, but this question deals with general exception objects.
You can simply use: logger.error('Exception occurred', exc_info=exc). Python itself will extract exception type/traceback info.
0

Honestly I don't know if I'm contributing in the slightest by doing this, but I did find this resource that I thought pertinent to your question and I hope useful.

http://www.alexconrad.org/2013/02/loggingexception.html

The gist of it being, if you place logging.exception() inside of an except block, then you can log all of your errors.

1 Comment

The problem is it's not inside an exception handler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.