Hi,

I attached a HandleExceptionMiddleware I use. You need to modify it
to your needs. It attaches the html page of cgitb and the django
debug page to the email.

  Thomas


George Lund schrieb:
> We have a live server crash issues for which we are receiving emails
> from Django from our server, which is great.
> 
> But I'm having trouble debugging the problem because the local
> variables don't seem to be included in the email.  All I can see is
> call stack followed by a <WSGIRequest .. > object - but nothing else.
> 
> Does anyone know how to make Django supply all the variables in the
> email?
>

-- 
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

# -*- coding: iso-8859-1 -*-
# $Id: HandleExceptionMiddleware.py 246 2009-01-21 15:13:09Z tguettler $
# $HeadURL: svn+ssh://svnserver/svn/djangotools/trunk/middleware/HandleExceptionMiddleware.py $

# Python Imports
import os
import re
import logging

# Django
import django.http
from django.utils.encoding import force_unicode, smart_unicode

from django.conf import settings
from djangotools.utils import responseutils

EMAIL_HOST='localhost'

class HandleExceptionMiddleware:

    def process_response(self, request, response):
        if response.status_code in [404]: # "Page not found" ist für uns wie eine Exception
            self.error(request, msg='Page not found')
        return response

    def process_exception(self, request, exception):
        '''
        Im Fehlerfall: Email an uns verschicken.
        '''
        if isinstance(exception, responseutils.HttpResponseException):
            return exception.args[0]
        logging.error('Exception: %r %r' % (request.path, request.user), exc_info=True)
        logging.error('    GET: %s' % request.GET)
        logging.error('    POST: %s' % request.POST)
        #logging.info('connection.queries: %s' % connection.queries)
        try:
            self.error(request, exception)
        except Exception:
            logging.error('Fehler Email konnte nicht versendet werden: %s' % request.path, 
                          exc_info=True)
            
    def error(self, request, exception=None, msg=''):
        exception_str=smart_unicode(exception, errors='replace')
        logging.error('%s %r %r %r' % (
            request.user, request.path, exception_str, msg))

        import sys
        import datetime
        import django.views.debug

        if request.user:
            username=request.user.username
        else:
            username='user-unset'

        exception_dir=os.path.join(settings.HOME, 'log', 'exceptions')

        now=datetime.datetime.now()
        body=[]
        body.append(u'URL: %s' % (request.build_absolute_uri()))
        body.append(u'Uhrzeit: %s' % now)

        attachments=[]
        msgs=[]
        if exception:
            msgs.append(exception_str)
            try:
                html=force_unicode(django.views.debug.technical_500_response(request, *sys.exc_info()), errors='replace')
                attachments.append(('traceback-django.html', html, 'text/html'))
                logfile=os.path.join(exception_dir, '%s-%s-django.html' % (
                    now.isoformat(), username))
                fd=open(logfile, 'wt')
                fd.write(html.encode('utf8'))
                fd.close()
            except UnicodeError, exc:
                body.append(u'Django Debug Template failed: %s' % exc)
            class FD:
                def __init__(self):
                    self.content=[]
                def write(self, text):
                    self.content.append(text)
                def __str__(self):
                    return ''.join(self.content)
            import cgitb
            fd=FD()
            cgitb.Hook(file=fd).handle()
            html=str(fd)
            attachments.append(('traceback-cgitb.html', html, 'text/html'))
            logfile=os.path.join(exception_dir, '%s-%s-cgitb.html' % (
                now.isoformat(), username))
            fd=open(logfile, 'wt')
            fd.write(html)
            fd.close()

            import traceback
            import cStringIO
            (exc_type, exc_value, tb) = sys.exc_info()
            exc_file = cStringIO.StringIO()
            traceback.print_exception(exc_type, exc_value, tb, file=exc_file)
            body.append(u'Traceback:\n%s' % smart_unicode(exc_file.getvalue(), errors='replace'))


        # Bei Entwicklungssystemen keine Fehleremail
        # versenden.
        if settings.DEVEL:
            logging.info('    Versende keine Email, da settings.DEVEL gesetzt.')
            return

        from django.core import mail

        for d in ['GET', 'POST', 'META']:
            rows=[]
            for key, value in sorted(getattr(request, d).items()):
                rows.append('%s: %s' % (key, value))
            body.append(u'%s:\n%s' % (d, '\n'.join(rows)))
            
        body=u'\n\n'.join(body)
        logfile=os.path.join(exception_dir, '%s-%s.txt' % (
            now.isoformat(), username))
        fd=open(logfile, 'wt')
        fd.write(body.encode('utf8', 'replace'))
        fd.close()
        
        if msg:
            msgs.append(msg)
        msg=' '.join(msgs)
        subject=u'Error %s %s %s %s: %s' % (
            os.uname()[1], settings.DATABASE_NAME, username, request.path, msg)
        subject=subject.replace('\n', ' ')
        connection = mail.SMTPConnection(host=EMAIL_HOST)
        to=[settings.ERROR_MAIL]
        email=mail.EmailMessage(connection=connection,
                                subject=subject,
                                body=body,
                                to=to,
                                attachments=attachments)
        try:
            email.send()
        except:
            logging.error('Sending Mail failed: host: %s to: % subject: %s' % (
                    EMAIL_HOST, to, subject))

Reply via email to