Log Django exceptions to Apache error log in 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. Log errors to a file by kcarnold 6 years, 1 month ago
  2. Middleware to log username into apache logs with mod_python by kahless 7 years, 1 month ago
  3. Extensible exception handling middleware by kcarnold 6 years, 1 month ago
  4. Log username in Apache access logs by arthur 4 years, 1 month ago
  5. Mail logged errors to administrators by jmillikin 5 years, 10 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)

#

(Forgotten your password?)