Login

Log Django exceptions to Apache error log in mod_wsgi

Author:
simon
Posted:
September 17, 2009
Language:
Python
Version:
1.1
Score:
3 (after 4 ratings)

Add this to your middleware to log errors to the Apache error log when running under mod_wsgi.

1
2
3
4
5
6
7
import traceback

class WsgiLogErrors(object):
    def process_exception(self, request, exception):
        tb_text = traceback.format_exc()
        url = request.build_absolute_uri()
        request.META['wsgi.errors'].write(url + '\n' + str(tb_text) + '\n')

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

adroffner (on October 2, 2009):

This WSGI middleware is not necessary to get mod_wsgi to use the Python logging module.

mod_wsgi (version 2.5) sends sys.stderr to the Apache2 virtual host's error_log. Therefore, one only needs to create a logging.StreamHandler() on the sys.stderr stream (the default).

Create a site_logging.py module to do this (see below). Then, just import site_logging into the settings.py on start-up.

After that, write logging statements in any module.

import logging

logging.warn('WSGI sends to the Apache2 error_log.')

MOD_WSGI site_logging.py

import logging

import sys

logger = logging.getLogger('')

logger.setLevel(logging.DEBUG)

handler = logging.StreamHandler(sys.stderr)

handler.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(levelname)-8s %(message)s')

handler.setFormatter(formatter)

logger.addHandler(handler)

#

Please login first before commenting.