1

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.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Ahmed
  • 2,176
  • 5
  • 26
  • 40
  • you should use `except Exception as e:` instead of `except Exception, e:` [related answer](http://stackoverflow.com/questions/2535760/python-try-except-comma-vs-as-in-except) – Daniel Lee Sep 27 '16 at 12:43

1 Answers1

1

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
vvvvv
  • 25,404
  • 19
  • 49
  • 81