Login

Log Django exceptions to Apache error log in mod_wsgi

Author:
simon
Posted:
September 17, 2009
Language:
Python
Version:
1.1
Tags:
middleware apache errors modwsgi exceptions
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. Log errors to a file by kcarnold 7 years ago
  2. Middleware to log username into apache logs with mod_python by kahless 8 years ago
  3. Extensible exception handling middleware by kcarnold 7 years ago
  4. Log username in Apache access logs by arthur 5 years ago
  5. Mail logged errors to administrators by jmillikin 6 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)

#

Please login first before commenting.