I would like to use it to generate html log files inside the process_exception() method of my custom middleware class, e.g:
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.
When DEBUG is False , Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater). This gives the administrators immediate notification of any errors.
If you don't want to configure logging at all (or you want to manually configure logging using your own approach), you can set LOGGING_CONFIG to None . This will disable the configuration process for Django's default logging.
First off check the Apache error log. If there is nothing in Apache error log, due to it being an internal error to your code or Django while handling a request, set DEBUG to True in Django site settings file and restart Apache so details of error display in the browser.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With