Put simply, I have a piece of code that looks like this:
if some_condition_that_evals_to_True:
raise ValueError("Error message")
What I want to do is to insert a logging statement that logs this entire exception but doing it just this way only saves the logger message:
if some_condition_that_evals_to_True:
logger.error("Logged error message")
raise ValueError("Error message")
Any one know how to save the entire error message including the ValueError?
EDIT:
The following is what I am trying to recreate:
if some_condition_that_evals_to_True:
try:
raise ValueError("Error with value")
except ValueError:
logger.exception("Logging Error with Value")
raise
But this seems like a roundabout way to get the behavior I want, so another way to phrase my question: Is there a more elegant way get the same behavior as the above codeblock?
Try the stack_info keyword argument when using the logging module:
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
if True:
logging.error('Error Message', stack_info=True)
raise ValueError('Custom Error Message')
Running this shows the following:
J:\>python log_stack.py
Traceback (most recent call last):
File "log_stack.py", line 5, in <module>
raise ValueError('Custom Error Message')
ValueError: Custom Error Message
J:\>more example.log
ERROR:root:Error Message
Stack (most recent call last):
File "log_stack.py", line 4, in <module>
logging.error('Error Message', stack_info=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With