Question

I would like to use it to generate html log files inside the process_exception() method of my custom middleware class, e.g:

  • Exception caught.
  • process_exception(request) called.
  • process_exception calls whatever function returns default error html.
  • process_exception writes returned html to logs folder somewhere where django server is running.

I know that Django is capable of sending emails for these exceptions but i'd rather not use this. I'm working on a RESTful application using JSON and so it feels more appropriate to return a json string stating error 500 and then placing the html somewhere else.

Thanks in advance.

Sorry maybe I need to clarify: I don't want to create my own 500.html, I want to use the one that django uses when Debug=True. i.e. generate the error file and place it in a log folder.

Thanks to Mark for the help - here is my solution for anyone interested:

import logging
import os
import settings
import sys
import datetime

from response import get_json_response
from django.views.debug import ExceptionReporter

logging.config.dictConfig(settings.LOGGING)
LOGGER = logging.getLogger('console_logger')

class LoggingMiddleware(object):

    def process_exception(self,request,exception):
        exc_type, exc_value, exc_traceback = sys.exc_info()
        er = ExceptionReporter(request, exc_type, exc_value, exc_traceback)
        time = str(datetime.datetime.now())
        file_path = os.path.join(settings.LOG_FOLDER, "{}.html".format(time))
        LOGGER.error("Writing error 500 traceback to %s" % file_path)
        file_handle = open(file_path,'w')
        file_handle.write(er.get_traceback_html())
        file_handle.close()
        return get_json_response(500,"HTTP Error 500: Internal Server Error")

The code intercepts any exceptions, uses the sys module and djangos default error template to generate the nicely formatted traceback/exception info page and then places this in a log folder before returning a JSON object stating that there has been a http error 500.

Was it helpful?

Solution

The 500 traceback page uses a template string (TECHNICAL_500_TEMPLATE) which is hard coded into django.views.debug. The report is generated by an ExceptionReporter class which is also included in django.views.debug which you should be able to re-purpose for your own log generation.

OTHER TIPS

If we want to show the exceptions that are generated in your template (500.html) then we could write your own 500 view, grabbing the exception and passing it to your 500 template.

Steps:

In my_app.views.py

import sys
import traceback

from django.http.response import HttpResponseServerError
from django.template import loader
from django.template.context import Context, RequestContext


def custom_500(request):
    t = loader.get_template('500.html')
    type, value, tb = sys.exc_info()
    return HttpResponseServerError(
        t.render(
            Context({
                'exception_value': value,
                'value': type,
                'tb': traceback.format_exception(type, value, tb)
            }, RequestContext(request))
        )
    )

In Main Urls.py

from django.conf.urls.defaults import *
handler500 = 'my_app.views.custom_500'

In Template (500.html)

{{ exception_value }}{{value}}{{tb}}

More about it here: https://docs.djangoproject.com/en/dev/topics/http/views/#the-500-server-error-view

Duplicate: Template does not exist: 500.html

Basically just put a 500.html in your template folder and it will use that.

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