#settings.py
TRAC_URL = 'http://user:password@domain.tld/login/xmlrpc'

#middleware.py
from django.conf import settings
from django import http
from django.core import exceptions
import xmlrpclib
import sys

class TracTicketMiddleware(object):
    """ This middleware will catch exceptions and creates a ticket in an existing
    Trac environment

    To install, be sure to place this middleware near the beginning
    of the MIDDLEWARE_CLASSES setting in your settings file.
    This will make sure that it doesn't accidentally catch errors
    you were meaning to catch with other middleware.
    """
    IGNORE_EXCEPTIONS = (http.Http404, SystemExit, exceptions.PermissionDenied)

    def process_exception(self, request, exception):
        # If this is an error we don't want to hear about, just return.
        if isinstance(exception, self.IGNORE_EXCEPTIONS) or \
                exception in self.IGNORE_EXCEPTIONS:
            return
        
        try:
            subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)
            
            try:
                request_repr = repr(request)
            except:
                request_repr = "Request repr() unavailable"
            
            message = "{{{\n%s\n}}}\n\n{{{\n%s\n}}}" % (self._get_traceback(sys.exc_info()), request_repr)
            attrs = {
                'type': 'defect',
                'status': 'new',
                'priority': 'major',
            }
            server = xmlrpclib.ServerProxy(settings.TRAC_URL)
            server.ticket.create(subject, message, attrs)            
        except:
            pass
        
        return   

    def _get_traceback(self, exc_info=None):
        "Helper function to return the traceback as a string"
        import traceback
        return '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info())))