debugpythonCriticalCanonical
How do I log a Python error with debug information?
Viewed 0 times
errorwithhowinformationlogpythondebug
Problem
I am printing Python exception messages to a log file with
Is it possible to print more detailed information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great.
logging.error:import logging
try:
1/0
except ZeroDivisionError as e:
logging.error(e) # ERROR:root:division by zeroIs it possible to print more detailed information about the exception and the code that generated it than just the exception string? Things like line numbers or stack traces would be great.
Solution
logger.exception will output a stack trace alongside the error message.For example:
import logging
try:
1/0
except ZeroDivisionError:
logging.exception("message")Output:
ERROR:root:message
Traceback (most recent call last):
File "", line 2, in
ZeroDivisionError: integer division or modulo by zero@Paulo Cheque notes, "be aware that in Python 3 you must call the
logging.exception method just inside the except part. If you call this method in an arbitrary place you may get a bizarre exception. The docs alert about that."Code Snippets
import logging
try:
1/0
except ZeroDivisionError:
logging.exception("message")ERROR:root:message
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zeroContext
Stack Overflow Q#5191830, score: 1205
Revisions (0)
No revisions yet.