2

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?

Fcoder
  • 9,066
  • 17
  • 63
  • 100
  • 3
    You really should *not* use `try... except:` without specifying which exception you want to catch. See [this](http://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice) questions to understand why. – Bakuriu Feb 12 '14 at 12:40
  • https://github.com/getsentry/sentry, Isn't every error logged by your server with a full traceback? – dm03514 Feb 12 '14 at 12:59
  • yes, it logs, but i have to log a description of the error. – Fcoder Feb 12 '14 at 13:01
  • Which information you must include in that description that isn't covered by the default log? – tutuca Feb 12 '14 at 17:21

1 Answers1

3

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.

tutuca
  • 3,444
  • 6
  • 32
  • 54