Question

i want to check every line or process of my code and if is not success, then log the error. like this:

try:
   handle = open('file.txt', 'r+')
   txt = handle.read()
except:
   logger.info("SOME DESCRIPTION OF ERROR")

it works but it seems this solution is not the best way. or is this a good way of using a lots of try... except statement? is there an alternative solution?

Was it helpful?

Solution

First off. As @Bakuriu said you must avoid using a bare except.

Second off. Django (from 1.4 onward) comes with logging configured for you.

Take a loog at https://docs.djangoproject.com/en/dev/topics/logging/. In production (ie: DEBUG = False) it will catch every exception and send it to you via email. Provided you have correctly setup the ADMIN key in your settings.py.

For instance, this logger:

LOGGING = {
    'version': 1,
    'formatters':{ 'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
    },
    'handlers': {
        'error_file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': 'errors.log',
            'formatter': 'verbose'
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['error_file'],
            'level': 'INFO',
            'propagate': False,
        },
    }
}

Will log anything with level ERROR and upper to the error.log file at the root of your project. That includes exception tracebacks and full stack information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top