Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send django exception log manually?

I have a specific view in my app which should return HttpResponse('') if everything was done successfully and smth like HttpResponseBadRequest() otherwise.

This view works with external data so some unexpected exceptions can be raised. Of course I need to know what happened. So I have smth like that:

def my_view(request):
    try:
        # a lot of code
        return HttpResponse('')
    except:
        import logging
        logger = logging.getLogger('django.request')
        # logger.error(extra={'request': request}) or logger.exception()
        return HttpResponseBadRequest('')

I have a default logging config if it matters (django 1.5).

logger.exception sends only a small traceback and no request data. logger.error sends only request data.

So the question is how to get exactly the same traceback as django sends (with the same subject/body)). I think there must be some clean and simple solution that i just can't find.

UPDATE

So with the patched exception method i ended up with the following code:

logger.exception('Internal Server Error: %s', request.path,
                 extra={'status_code': 500, 'request': request})

which produces equal email traceback as built-in django logging.

like image 363
alTus Avatar asked Sep 30 '13 20:09

alTus


Video Answer


1 Answers

This problem is due to a bug which has been fixed in recent versions of Python 2.7. This bug meant that the exception method did not accept the extra argument.

If you can't upgrade to a suitably recent Python 2.7, then you can perhaps patch your Python with the fix referenced in the issue I've linked to. If you can't do that, you'll need to subclass Logger and override the exception method to do the right thing (which is basically to add a **kwargs to the exception method's signature, which is passed through to its call to the error method.

like image 110
Vinay Sajip Avatar answered Oct 13 '22 00:10

Vinay Sajip