Exception message best practices
Question:
I’ve written a small production-level Flask application in Python with standard exception handling. Most of the time I’m just logging the exception message and it looks like this
try:
#Do something
except Exception, e:
logger.error('Exception in LoadValidationDocs in main.py : %s' % str(e.args))
return None
I was wondering if I should keep all such error messages in a separate strings.py
file like
standard_exception_message = 'Exception in %s in %s, Exception Args : %s'
and get function and module name at run time like
import inspect
function_name = inspect.stack()[0][3]
file_name = os.path.basename(__file__)
logger.error(strings. standard_exception_message % (function_name, file_name, str(e.args)))
I just want to know whether it’s necessary to do that and is it even the correct way of doing it considering my current scenario.
Answers:
You can use logging.exception
instead of logging.error
. It will take care of looking for the function, module name etc. for you in a formatted way:
import logging
try:
# Do something that will fail
x = 1 / 0
except Exception as e:
logging.exception("This is my message when an error happens here.")
It gives:
ERROR:root:This is my message when an error happens here.
Traceback (most recent call last):
File "question39724934.py", line 5, in compute
x = 1 / 0
ZeroDivisionError: division by zero
I’ve written a small production-level Flask application in Python with standard exception handling. Most of the time I’m just logging the exception message and it looks like this
try:
#Do something
except Exception, e:
logger.error('Exception in LoadValidationDocs in main.py : %s' % str(e.args))
return None
I was wondering if I should keep all such error messages in a separate strings.py
file like
standard_exception_message = 'Exception in %s in %s, Exception Args : %s'
and get function and module name at run time like
import inspect
function_name = inspect.stack()[0][3]
file_name = os.path.basename(__file__)
logger.error(strings. standard_exception_message % (function_name, file_name, str(e.args)))
I just want to know whether it’s necessary to do that and is it even the correct way of doing it considering my current scenario.
You can use logging.exception
instead of logging.error
. It will take care of looking for the function, module name etc. for you in a formatted way:
import logging
try:
# Do something that will fail
x = 1 / 0
except Exception as e:
logging.exception("This is my message when an error happens here.")
It gives:
ERROR:root:This is my message when an error happens here.
Traceback (most recent call last):
File "question39724934.py", line 5, in compute
x = 1 / 0
ZeroDivisionError: division by zero