#!/usr/bin/python
# -*- coding: utf-8 -*-

from inspect import getouterframes, currentframe, getinnerframes
from raven.handlers.logging import SentryHandler
from ZConfig.components.logger.factory import Factory
import logging

from raven.utils.stacks import iter_stack_frames

logger = logging.getLogger(__name__)


class ZopeSentryHandlerFactory(Factory):

    def getLevel(self):
        return self.section.level

    def create(self):
        return ZopeSentryHandler(**self.section.__dict__)

    def __init__(self, section):
        Factory.__init__(self)
        self.section = section


class ZopeSentryHandler(SentryHandler):
    '''
    Zope unfortunately eats the stack trace information.
    To get the stack trace information and other useful information
    from the request object, this class looks into the different stack
    frames when the emit method is invoked.
    '''

    def __init__(self, *args, **kw):
        super(ZopeSentryHandler, self).__init__(*args, **kw)
        level = kw.get('level', logging.ERROR)
        self.setLevel(level)

    def emit(self, record):
        if record.levelno <= logging.ERROR:
            request = None
            exc_info = None
            for frame_info in getouterframes(currentframe()):
                frame = frame_info[0]
                if not request:
                    request = frame.f_locals.get('request', None)
                    if not request:
                        view = frame.f_locals.get('self', None)
                        request = getattr(view, 'request', None)
                if not exc_info:
                    exc_info = frame.f_locals.get('exc_info', None)
                    if not hasattr(exc_info, '__getitem__'):
                        exc_info = None
                if request and exc_info:
                    break

            if exc_info:
                record.exc_info = exc_info
                record.stack = \
                    iter_stack_frames(getinnerframes(exc_info[2]))
            if request:
                try:
                    body_pos = request.stdin.tell()
                    request.stdin.seek(0)
                    body = request.stdin.read()
                    request.stdin.seek(body_pos)
                    http = dict(headers=request.environ,
                                url=request.getURL(),
                                method=request.method,
                                host=request.environ.get('REMOTE_ADDR',
                                ''), data=body)
                    if 'HTTP_USER_AGENT' in http['headers']:
                        if 'User-Agent' not in http['headers']:
                            http['headers']['User-Agent'] = \
                                http['headers']['HTTP_USER_AGENT']
                    if 'QUERY_STRING' in http['headers']:
                        http['query_string'] = http['headers'
                                ]['QUERY_STRING']
                    setattr(record, 'sentry.interfaces.Http', http)
                    user = request.get('AUTHENTICATED_USER', None)
                    if user is not None:
                        userid = user.getId()
                        is_authenticated = user.has_role('Authenticated')
                        email = user.getProperty('email') or ''
                    else:
                        userid = 'Anonymous User'
                        is_authenticated = False
                        email = ''
                    user_dict = dict(id=userid,
                                     is_authenticated=is_authenticated,
                                     email=email)
                    setattr(record, 'sentry.interfaces.User', user_dict)
                except (AttributeError, KeyError):
                    logger.warning('Could not extract data from request', exc_info=True)
        return super(ZopeSentryHandler, self).emit(record)

@@ -3138,21 +3138,32 @@
     user
-id = 
+_dict = dict(id=
 user.get
@@ -3166,17 +3166,24 @@
 .getId()
-%0A
+,%0A      
         
@@ -3190,32 +3190,43 @@
                 
+           
 is_authenticated
@@ -3225,19 +3225,17 @@
 nticated
- = 
+=
 user.has
@@ -3256,17 +3256,23 @@
 icated')
-%0A
+,%0A     
         
@@ -3287,24 +3287,34 @@
         
+            
 email
- = 
+=
 user.get
@@ -3336,16 +3336,17 @@
 ') or ''
+)
 %0A       
@@ -3396,283 +3396,43 @@
 user
-id = 'Anonymous User'%0A                        is_authenticated = False%0A                        email = ''%0A                    user_dict = dict(id=userid,%0A                                     is_authenticated=is_authenticated,%0A                                     email=email)
+_dict = %7B'is_authenticated': False%7D
 %0A   

Simplify the anon userdict