7

I have created a function log_error(request, traceback), which I call in my exceptions. This writes error information to the database. Now, before I open up every one of my views and add this in an exception handler, is there a way to automatically have all exceptions raise to a function, which then calls this?

I have seen this Python error logging, which says to write your own version of sys.excepthook. This function is automatically called when there is an exception. I tried this, but my_excepthook was not called even though I copy-pasted the solution into views.py and raised an error. However, I didn't try too hard because it's not getting all the information that I need, anyway. I also need request so I can log information abut the user, url, etc.

Maybe that's asking too much?

(I'm using Django, but this does not seem like a Django-specific thing) Edit: yes, it is.

3
  • sys.excepthook is only called for unhandled exceptions, or those that are re-raised by their handler -- which may be why it didn't appear to work when you tried it. For the most part the only information it has is what it's passed as arguments. You could store additional information someplace and have your version look there for it there. Commented Nov 8, 2012 at 8:41
  • Django can be configured to report all unhandled exceptions Commented Nov 8, 2012 at 9:05
  • @J.F. Sebastian. The error way works. I wrote up a solution. Thanks. Commented Nov 8, 2012 at 10:19

1 Answer 1

7

J.F Sebastian's suggestion worked. This is a Django solution.

In settings.py MIDDLEWARE_CLASSES:

(I added it as the last one, not sure if this is right or will cause errors down the line. Works for now.)

'myapp.middleware.ExceptionMiddleware',

In myapp.middleware.py:

import traceback
class ExceptionMiddleware(object):
    def process_exception(self, request, exception):
        log_error(traceback, request)

That's it. log_error is my function and writes to the database. It also appears from the documentation https://docs.djangoproject.com/en/dev/howto/error-reporting/ that I can get the local variables as well as the request attributes.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please share, how's your log_error function implemented ? do you log request.META and traceback both as two TextFields(models.TextField) ? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.