Python/Django: automatically log when exceptions occur, including request info
Question: 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](http://stackoverflow.com/questions/4941543/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.


Answer: 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.

