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.