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

Comments

adroffner (on October 2, 2009):
<p>This WSGI middleware is not necessary to get mod_wsgi to use the Python logging module.</p> <p>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).</p> <p>Create a site_logging.py module to do this (see below). Then, just import site_logging into the settings.py on start-up.</p> <p>After that, write logging statements in any module.</p> <p>import logging</p> <p>logging.warn('WSGI sends to the Apache2 error_log.')</p> <h1>MOD_WSGI site_logging.py</h1> <p>import logging</p> <p>import sys</p> <p>logger = logging.getLogger('')</p> <p>logger.setLevel(logging.DEBUG)</p> <p>handler = logging.StreamHandler(sys.stderr)</p> <p>handler.setLevel(logging.DEBUG)</p> <p>formatter = logging.Formatter('%(levelname)-8s %(message)s')</p> <p>handler.setFormatter(formatter)</p> <p>logger.addHandler(handler)</p>

#

Please login first before commenting.