Beispiel #1
0
    def format(self, record):
        """Format exception object as a string"""
        data = record._raw.copy()

        data['extra'] = self.prepare_data(data.get('extra'))


        if 'exc_info' in data and data['exc_info']:
            if DJANGO_ENABLE:
                er = ExceptionReporter(None, *data['exc_info'])
                data['exc_extra_info'] = self.prepare_data(er.get_traceback_frames())
            data['exc_info'] = self.formatException(data['exc_info'])

        data['msg'] = logging.Formatter.format(self, record)
        data['format'] = data['msg']
        del data['args']

        # hack for normalize unicode data for soap fault
        for key in ['exc_info', 'format']:
            if isinstance(data[key], basestring):
                try:
                    data[key] = data[key].decode("unicode_escape")
                except UnicodeEncodeError:
                    pass
        return data
Beispiel #2
0
def handler500(request):
    if hasattr(request, 'urlconf'):
        urlconf = request.urlconf
        set_urlconf(urlconf)
        resolver = get_resolver(urlconf)
    else:
        resolver = get_resolver()

    resolver_match = resolver.resolve(request.path_info)
    callback, callback_args, callback_kwargs = resolver_match
    request.resolver_match = resolver_match

    obj = base.BaseHandler
    wrapped_callback = obj.make_view_atomic(obj, callback)

    try:
        response = wrapped_callback(request, *callback_args, **callback_kwargs)
    except Exception as e:

        exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        frames = reporter.get_traceback_frames()

        traceback_string = ""
        for frame in frames:
            traceback_string += "({},{})".format(str(frame['lineno']),
                                                 str(frame['filename']))

        logger.critical("|URL->| {} |ERROR->| {} |TRACEBACK->| {}".format(request,\
                                                                            e, traceback_string))

        return HttpResponse(status=500)
Beispiel #3
0
    def create_from_exception(self, exception=None, traceback=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exception:
            exc_type, exc_value, traceback = sys.exc_info()
        elif not traceback:
            warnings.warn('Using just the ``exception`` argument is deprecated, send ``traceback`` in addition.', DeprecationWarning)
            exc_type, exc_value, traceback = sys.exc_info()
        else:
            exc_type = exception.__class__
            exc_value = exception

        def to_unicode(f):
            if isinstance(f, dict):
                nf = dict()
                for k, v in f.iteritems():
                    nf[str(k)] = to_unicode(v)
                f = nf
            elif isinstance(f, (list, tuple)):
                f = [to_unicode(f) for f in f]
            else:
                try:
                    f = smart_unicode(f)
                except (UnicodeEncodeError, UnicodeDecodeError):
                    f = '(Error decoding value)'
            return f

        def shorten(var):
            if not isinstance(var, basestring):
                var = to_unicode(var)
            if len(var) > 500:
                var = var[:500] + '...'
            return var

        reporter = ExceptionReporter(None, exc_type, exc_value, traceback)
        frames = varmap(shorten, reporter.get_traceback_frames())

        data = kwargs.pop('data', {}) or {}
        data['__sentry__'] = {
            'exc': map(to_unicode, [exc_type.__class__.__module__, exc_value.args, frames]),
        }

        if isinstance(exc_value, TemplateSyntaxError) and hasattr(exc_value, 'source'):
            origin, (start, end) = exc_value.source
            data['__sentry__'].update({
                'template': (origin.reload(), start, end, origin.name),
            })
        
        tb_message = '\n'.join(traceback_mod.format_exception(exc_type, exc_value, traceback))

        kwargs.setdefault('message', to_unicode(exc_value))

        return self._create(
            class_name=exc_type.__name__,
            traceback=tb_message,
            data=data,
            **kwargs
        )
Beispiel #4
0
    def create_from_exception(self, exception=None, traceback=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exception:
            exc_type, exc_value, traceback = sys.exc_info()
        elif not traceback:
            warnings.warn(
                "Using just the ``exception`` argument is deprecated, send ``traceback`` in addition.",
                DeprecationWarning,
            )
            exc_type, exc_value, traceback = sys.exc_info()
        else:
            exc_type = exception.__class__
            exc_value = exception

        def to_unicode(f):
            if isinstance(f, dict):
                nf = dict()
                for k, v in f.iteritems():
                    nf[str(k)] = to_unicode(v)
                f = nf
            elif isinstance(f, (list, tuple)):
                f = [to_unicode(f) for f in f]
            else:
                try:
                    f = smart_unicode(f)
                except (UnicodeEncodeError, UnicodeDecodeError):
                    f = "(Error decoding value)"
                except Exception:  # in some cases we get a different exception
                    f = smart_unicode(type(f))
            return f

        def shorten(var):
            if not isinstance(var, basestring):
                var = to_unicode(var)
            if len(var) > 500:
                var = var[:500] + "..."
            return var

        reporter = ExceptionReporter(None, exc_type, exc_value, traceback)
        frames = varmap(shorten, reporter.get_traceback_frames())

        data = kwargs.pop("data", {}) or {}
        data["__sentry__"] = {"exc": map(to_unicode, [exc_type.__class__.__module__, exc_value.args, frames])}

        if isinstance(exc_value, TemplateSyntaxError) and hasattr(exc_value, "source"):
            origin, (start, end) = exc_value.source
            data["__sentry__"].update({"template": (origin.reload(), start, end, origin.name)})

        tb_message = "\n".join(traceback_mod.format_exception(exc_type, exc_value, traceback))

        kwargs.setdefault("message", to_unicode(exc_value))

        return self.process(class_name=exc_type.__name__, traceback=tb_message, data=data, **kwargs)
Beispiel #5
0
    def create_from_exception(self, exception=None, traceback=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exception:
            exc_type, exc_value, traceback = sys.exc_info()
        elif not traceback:
            warnings.warn(
                'Using just the ``exception`` argument is deprecated, send ``traceback`` in addition.',
                DeprecationWarning)
            exc_type, exc_value, traceback = sys.exc_info()
        else:
            exc_type = exception.__class__
            exc_value = exception

        def to_unicode(f):
            if isinstance(f, dict):
                nf = dict()
                for k, v in f.iteritems():
                    nf[str(k)] = to_unicode(v)
                f = nf
            elif isinstance(f, (list, tuple)):
                f = [to_unicode(f) for f in f]
            else:
                try:
                    f = smart_unicode(f)
                except (UnicodeEncodeError, UnicodeDecodeError):
                    f = '(Error decoding value)'
            return f

        reporter = ExceptionReporter(None, exc_type, exc_value, traceback)
        frames = reporter.get_traceback_frames()

        data = kwargs.pop('data', {}) or {}
        data['exc'] = base64.b64encode(
            pickle.dumps(
                map(to_unicode,
                    [exc_type.__class__.__module__, exc_value.args, frames
                     ])).encode('zlib'))

        tb_message = '\n'.join(
            traceback_mod.format_exception(exc_type, exc_value, traceback))

        kwargs.setdefault('message', to_unicode(exc_value))

        return self._create(class_name=exc_type.__name__,
                            traceback=tb_message,
                            data=data,
                            **kwargs)
Beispiel #6
0
    def create_from_exception(self, exception=None, traceback=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exception:
            exc_type, exc_value, traceback = sys.exc_info()
        elif not traceback:
            warnings.warn('Using just the ``exception`` argument is deprecated, send ``traceback`` in addition.', DeprecationWarning)
            exc_type, exc_value, traceback = sys.exc_info()
        else:
            exc_type = exception.__class__
            exc_value = exception

        def to_unicode(f):
            if isinstance(f, dict):
                nf = dict()
                for k, v in f.iteritems():
                    nf[str(k)] = to_unicode(v)
                f = nf
            elif isinstance(f, (list, tuple)):
                f = [to_unicode(f) for f in f]
            else:
                try:
                    f = smart_unicode(f)
                except (UnicodeEncodeError, UnicodeDecodeError):
                    f = '(Error decoding value)'
            return f

        reporter = ExceptionReporter(None, exc_type, exc_value, traceback)
        frames = reporter.get_traceback_frames()

        data = kwargs.pop('data', {}) or {}
        try:
            data['exc'] = base64.b64encode(pickle.dumps(map(to_unicode, [exc_type.__class__.__module__, exc_value.args, frames])).encode('zlib'))
        except:
            data['exc'] = base64.b64encode(pickle.dumps(map(to_unicode, [exc_type.__class__.__module__, exc_value.args, []])).encode('zlib'))
        
        tb_message = '\n'.join(traceback_mod.format_exception(exc_type, exc_value, traceback))

        kwargs.setdefault('message', to_unicode(exc_value))

        return self._create(
            class_name=exc_type.__name__,
            traceback=tb_message,
            data=data,
            **kwargs
        )
Beispiel #7
0
 def test_reporting_frames_without_source(self):
     try:
         source = "def funcName():\n    raise Error('Whoops')\nfuncName()"
         namespace = {}
         code = compile(source, 'generated', 'exec')
         exec(code, namespace)
     except Exception:
         exc_type, exc_value, tb = sys.exc_info()
     request = self.rf.get('/test_view/')
     reporter = ExceptionReporter(request, exc_type, exc_value, tb)
     frames = reporter.get_traceback_frames()
     last_frame = frames[-1]
     self.assertEqual(last_frame['context_line'], '<source code not available>')
     self.assertEqual(last_frame['filename'], 'generated')
     self.assertEqual(last_frame['function'], 'funcName')
     self.assertEqual(last_frame['lineno'], 2)
     html = reporter.get_traceback_html()
     self.assertIn('generated in funcName', html)
     text = reporter.get_traceback_text()
     self.assertIn('"generated" in funcName', text)
Beispiel #8
0
    def create_from_exception(self, exc_info=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exc_info:
            exc_info = sys.exc_info()
        exc_type, exc_value, exc_traceback = exc_info

        def to_unicode(f):
            if isinstance(f, dict):
                nf = dict()
                for k, v in f.iteritems():
                    nf[str(k)] = to_unicode(v)
                f = nf
            elif isinstance(f, (list, tuple)):
                f = [to_unicode(f) for f in f]
            else:
                try:
                    f = smart_unicode(f)
                except (UnicodeEncodeError, UnicodeDecodeError):
                    f = '(Error decoding value)'
                except Exception: # in some cases we get a different exception
                    f = smart_unicode(type(f))
            return f

        def shorten(var):
            if not isinstance(var, basestring):
                var = to_unicode(var)
            if len(var) > 200:
                var = var[:200] + '...'
            return var

        reporter = ExceptionReporter(None, exc_type, exc_value, exc_traceback)
        frames = varmap(shorten, reporter.get_traceback_frames())

        if not kwargs.get('view'):
            # This should be cached
            modules = get_installed_apps()
            if conf.INCLUDE_PATHS:
                modules = set(list(modules) + conf.INCLUDE_PATHS)

            def iter_tb_frames(tb):
                while tb:
                    yield tb.tb_frame
                    tb = tb.tb_next
            
            def contains(iterator, value):
                for k in iterator:
                    if value.startswith(k):
                        return True
                return False
                
            # We iterate through each frame looking for an app in INSTALLED_APPS
            # When one is found, we mark it as last "best guess" (best_guess) and then
            # check it against SENTRY_EXCLUDE_PATHS. If it isnt listed, then we
            # use this option. If nothing is found, we use the "best guess".
            best_guess = None
            view = None
            for frame in iter_tb_frames(exc_traceback):
                view = '.'.join([frame.f_globals['__name__'], frame.f_code.co_name])
                if contains(modules, view):
                    if not (contains(conf.EXCLUDE_PATHS, view) and best_guess):
                        best_guess = view
                elif best_guess:
                    break
            if best_guess:
                view = best_guess
            
            if view:
                kwargs['view'] = view

        data = kwargs.pop('data', {}) or {}
        data['__sentry__'] = {
            'exc': map(to_unicode, [exc_type.__class__.__module__, exc_value.args, frames]),
        }

        if isinstance(exc_value, TemplateSyntaxError) and hasattr(exc_value, 'source'):
            origin, (start, end) = exc_value.source
            data['__sentry__'].update({
                'template': (origin.reload(), start, end, origin.name),
            })
            kwargs['view'] = origin.loadname
        
        tb_message = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_traceback))

        kwargs.setdefault('message', to_unicode(exc_value))

        return self.process(
            class_name=exc_type.__name__,
            traceback=tb_message,
            data=data,
            **kwargs
        )
Beispiel #9
0
    def create_from_exception(self, exc_info=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exc_info:
            exc_info = sys.exc_info()

        exc_type, exc_value, exc_traceback = exc_info

        def shorten(var):
            var = transform(var)
            if isinstance(var, basestring) and len(var) > 200:
                var = var[:200] + '...'
            return var

        reporter = ExceptionReporter(None, exc_type, exc_value, exc_traceback)
        frames = varmap(shorten, reporter.get_traceback_frames())

        if not kwargs.get('view'):
            # This should be cached
            modules = get_installed_apps()
            if conf.INCLUDE_PATHS:
                modules = set(list(modules) + conf.INCLUDE_PATHS)

            def iter_tb_frames(tb):
                while tb:
                    yield tb.tb_frame
                    tb = tb.tb_next

            def contains(iterator, value):
                for k in iterator:
                    if value.startswith(k):
                        return True
                return False

            # We iterate through each frame looking for an app in INSTALLED_APPS
            # When one is found, we mark it as last "best guess" (best_guess) and then
            # check it against SENTRY_EXCLUDE_PATHS. If it isnt listed, then we
            # use this option. If nothing is found, we use the "best guess".
            best_guess = None
            view = None
            for frame in iter_tb_frames(exc_traceback):
                try:
                    view = '.'.join(
                        [frame.f_globals['__name__'], frame.f_code.co_name])
                except:
                    continue
                if contains(modules, view):
                    if not (contains(conf.EXCLUDE_PATHS, view) and best_guess):
                        best_guess = view
                elif best_guess:
                    break
            if best_guess:
                view = best_guess

            if view:
                kwargs['view'] = view

        data = kwargs.pop('data', {}) or {}
        if hasattr(exc_type, '__class__'):
            exc_module = exc_type.__class__.__module__
        else:
            exc_module = None
        data['__sentry__'] = {
            'exc': map(transform, [exc_module, exc_value.args, frames]),
        }

        if (isinstance(exc_value, TemplateSyntaxError) and \
            isinstance(getattr(exc_value, 'source', None), (tuple, list)) and isinstance(exc_value.source[0], LoaderOrigin)):
            origin, (start, end) = exc_value.source
            data['__sentry__'].update({
                'template': (origin.reload(), start, end, origin.name),
            })
            kwargs['view'] = origin.loadname

        tb_message = '\n'.join(
            traceback.format_exception(exc_type, exc_value, exc_traceback))

        kwargs.setdefault('message', transform(force_unicode(exc_value)))

        return self.process(class_name=exc_type.__name__,
                            traceback=tb_message,
                            data=data,
                            **kwargs)
Beispiel #10
0
    def create_from_exception(self, exc_info=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exc_info:
            exc_info = sys.exc_info()

        exc_type, exc_value, exc_traceback = exc_info

        reporter = ExceptionReporter(None, exc_type, exc_value, exc_traceback)
        frames = varmap(shorten, reporter.get_traceback_frames())

        if not kwargs.get('view'):
            # This should be cached
            modules = get_installed_apps()
            if conf.INCLUDE_PATHS:
                modules = set(list(modules) + conf.INCLUDE_PATHS)

            def iter_tb_frames(tb):
                while tb:
                    yield tb.tb_frame
                    tb = tb.tb_next

            def contains(iterator, value):
                for k in iterator:
                    if value.startswith(k):
                        return True
                return False

            # We iterate through each frame looking for an app in INSTALLED_APPS
            # When one is found, we mark it as last "best guess" (best_guess) and then
            # check it against SENTRY_EXCLUDE_PATHS. If it isnt listed, then we
            # use this option. If nothing is found, we use the "best guess".
            best_guess = None
            view = None
            for frame in iter_tb_frames(exc_traceback):
                try:
                    view = '.'.join([frame.f_globals['__name__'], frame.f_code.co_name])
                except:
                    continue
                if contains(modules, view):
                    if not (contains(conf.EXCLUDE_PATHS, view) and best_guess):
                        best_guess = view
                elif best_guess:
                    break
            if best_guess:
                view = best_guess

            if view:
                kwargs['view'] = view

        data = kwargs.pop('data', {}) or {}
        if hasattr(exc_type, '__class__'):
            exc_module = exc_type.__class__.__module__
        else:
            exc_module = None
        data['__sentry__'] = {
            'exc': map(transform, [exc_module, exc_value.args, frames]),
        }

        if (isinstance(exc_value, TemplateSyntaxError) and \
            isinstance(getattr(exc_value, 'source', None), (tuple, list)) and isinstance(exc_value.source[0], LoaderOrigin)):
            origin, (start, end) = exc_value.source
            data['__sentry__'].update({
                'template': (origin.reload(), start, end, origin.name),
            })
            kwargs['view'] = origin.loadname

        tb_message = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_traceback))

        kwargs.setdefault('message', transform(force_unicode(exc_value)))

        return self.process(
            class_name=exc_type.__name__,
            traceback=tb_message,
            data=data,
            **kwargs
        )
Beispiel #11
0
    def create_from_exception(self, exc_info=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exc_info:
            exc_info = sys.exc_info()

        exc_type, exc_value, exc_traceback = exc_info

        def shorten(var):
            var = transform(var)
            if isinstance(var, basestring) and len(var) > 200:
                var = var[:200] + "..."
            return var

        reporter = ExceptionReporter(None, exc_type, exc_value, exc_traceback)
        frames = varmap(shorten, reporter.get_traceback_frames())

        if not kwargs.get("view"):
            # This should be cached
            modules = get_installed_apps()
            if conf.INCLUDE_PATHS:
                modules = set(list(modules) + conf.INCLUDE_PATHS)

            def iter_tb_frames(tb):
                while tb:
                    yield tb.tb_frame
                    tb = tb.tb_next

            def contains(iterator, value):
                for k in iterator:
                    if value.startswith(k):
                        return True
                return False

            # We iterate through each frame looking for an app in INSTALLED_APPS
            # When one is found, we mark it as last "best guess" (best_guess) and then
            # check it against SENTRY_EXCLUDE_PATHS. If it isnt listed, then we
            # use this option. If nothing is found, we use the "best guess".
            best_guess = None
            view = None
            for frame in iter_tb_frames(exc_traceback):
                try:
                    view = ".".join([frame.f_globals["__name__"], frame.f_code.co_name])
                except:
                    continue
                if contains(modules, view):
                    if not (contains(conf.EXCLUDE_PATHS, view) and best_guess):
                        best_guess = view
                elif best_guess:
                    break
            if best_guess:
                view = best_guess

            if view:
                kwargs["view"] = view

        data = kwargs.pop("data", {}) or {}
        if hasattr(exc_type, "__class__"):
            exc_module = exc_type.__class__.__module__
        else:
            exc_module = None
        data["__sentry__"] = {"exc": map(transform, [exc_module, exc_value.args, frames])}

        if isinstance(exc_value, TemplateSyntaxError) and hasattr(exc_value, "source"):
            origin, (start, end) = exc_value.source
            data["__sentry__"].update({"template": (origin.reload(), start, end, origin.name)})
            kwargs["view"] = origin.loadname

        tb_message = "\n".join(traceback.format_exception(exc_type, exc_value, exc_traceback))

        kwargs.setdefault("message", transform(force_unicode(exc_value)))

        return self.process(class_name=exc_type.__name__, traceback=tb_message, data=data, **kwargs)
Beispiel #12
0
    def handle(self, exc_info=None):
        # TODO: remove Django specifics
        from django.template import TemplateSyntaxError
        from django.views.debug import ExceptionReporter

        if exc_info is None:
            exc_info = sys.exc_info()

        exc_type, exc_value, exc_traceback = exc_info

        result = {
            'tags': [('level', 'error')],
        }

        reporter = ExceptionReporter(None, exc_type, exc_value, exc_traceback)
        exc_frames = varmap(shorten, reporter.get_traceback_frames())

        # This should be cached
        # modules = get_installed_apps()
        modules = []
        if app.config['INCLUDE_PATHS']:
            modules = set(list(modules) + app.config['INCLUDE_PATHS'])

        def iter_tb_frames(tb):
            while tb:
                yield tb.tb_frame
                tb = tb.tb_next

        def contains(iterator, value):
            for k in iterator:
                if value.startswith(k):
                    return True
            return False

        # We iterate through each frame looking for an app in INSTALLED_APPS
        # When one is found, we mark it as last "best guess" (best_guess) and then
        # check it against SENTRY_EXCLUDE_PATHS. If it isnt listed, then we
        # use this option. If nothing is found, we use the "best guess".
        best_guess = None
        view = None
        for frame in iter_tb_frames(exc_traceback):
            try:
                view = '.'.join([frame.f_globals['__name__'], frame.f_code.co_name])
            except:
                continue
            if contains(modules, view):
                if not (contains(app.config['EXCLUDE_PATHS'], view) and best_guess):
                    best_guess = view
            elif best_guess:
                break
        if best_guess:
            view = best_guess

        if view:
            result['tags'].append(('view', view))

        if hasattr(exc_type, '__class__'):
            exc_module = exc_type.__class__.__module__
            if exc_module == '__builtin__':
                exc_type = exc_type.__name__
            else:
                exc_type = '%s.%s' % (exc_module, exc_type.__name__)
        else:
            exc_module = None
            exc_type = exc_type.__name__

        if isinstance(exc_value, TemplateSyntaxError) and hasattr(exc_value, 'source'):
            origin, (start, end) = exc_value.source
            result['exc_template'] = (origin.reload(), start, end, origin.name)
            result['tags'].append(('template', origin.loadname))

        result['exc_value'] = transform(exc_value)
        result['exc_type'] = exc_type
        result['exc_frames'] = self.get_traceback_frames(exc_traceback)

        return result
Beispiel #13
0
    def create_from_exception(self, exc_info=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exc_info:
            exc_info = sys.exc_info()
        exc_type, exc_value, exc_traceback = exc_info

        def to_unicode(f):
            if isinstance(f, dict):
                nf = dict()
                for k, v in f.iteritems():
                    nf[str(k)] = to_unicode(v)
                f = nf
            elif isinstance(f, (list, tuple)):
                f = [to_unicode(f) for f in f]
            else:
                try:
                    f = smart_unicode(f)
                except (UnicodeEncodeError, UnicodeDecodeError):
                    f = '(Error decoding value)'
                except Exception:  # in some cases we get a different exception
                    f = smart_unicode(type(f))
            return f

        def shorten(var):
            if not isinstance(var, basestring):
                var = to_unicode(var)
            if len(var) > 200:
                var = var[:200] + '...'
            return var

        reporter = ExceptionReporter(None, exc_type, exc_value, exc_traceback)
        frames = varmap(shorten, reporter.get_traceback_frames())

        if not kwargs.get('view'):
            # This should be cached
            modules = get_installed_apps()
            if settings.INCLUDE_PATHS:
                modules = set(list(modules) + settings.INCLUDE_PATHS)

            def iter_tb_frames(tb):
                while tb:
                    yield tb.tb_frame
                    tb = tb.tb_next

            def contains(iterator, value):
                for k in iterator:
                    if value.startswith(k):
                        return True
                return False

            # We iterate through each frame looking for an app in INSTALLED_APPS
            # When one is found, we mark it as last "best guess" (best_guess) and then
            # check it against SENTRY_EXCLUDE_PATHS. If it isnt listed, then we
            # use this option. If nothing is found, we use the "best guess".
            best_guess = None
            for frame in iter_tb_frames(exc_traceback):
                view = '.'.join(
                    [frame.f_globals['__name__'], frame.f_code.co_name])
                if contains(modules, view):
                    if not (contains(settings.EXCLUDE_PATHS, view)
                            and best_guess):
                        best_guess = view
                elif best_guess:
                    break
            if best_guess:
                view = best_guess

            kwargs['view'] = view

        data = kwargs.pop('data', {}) or {}
        data['__sentry__'] = {
            'exc':
            map(to_unicode,
                [exc_type.__class__.__module__, exc_value.args, frames]),
        }

        if isinstance(exc_value, TemplateSyntaxError) and hasattr(
                exc_value, 'source'):
            origin, (start, end) = exc_value.source
            data['__sentry__'].update({
                'template': (origin.reload(), start, end, origin.name),
            })
            kwargs['view'] = origin.loadname

        tb_message = '\n'.join(
            traceback.format_exception(exc_type, exc_value, exc_traceback))

        kwargs.setdefault('message', to_unicode(exc_value))

        return self.process(class_name=exc_type.__name__,
                            traceback=tb_message,
                            data=data,
                            **kwargs)
    def emit(self, record):

        if record.exc_info:
            exc_info = record.exc_info
            reporter = ExceptionReporter(record.request, *exc_info)

            # Create the SnowyEvening stack trace
            frames = [
                {
                    "file" : i['filename'],
                    "line" : i['lineno'],
                    "function" : i['function']
                }
                for i in reporter.get_traceback_frames()[::-1]
            ]

            error_type = exc_info[0].__name__
            error_message = exc_info[0].__name__ + ": " + unicode(exc_info[1])
            file_path = frames[0]['file']
            line = str(frames[0]['line'])
        else:
            exc_info = (None, record.getMessage(), None)
            reporter = ExceptionReporter(record.request, *exc_info)
            frames = []
            error_type = "Logger"
            error_message = "Logger: " + record.getMessage()
            file_path = record.pathname
            line = str(record.lineno)

        # Find visitor IP
        x_forwarded_for = record.request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            visitor_ip = x_forwarded_for.split(',')[0]
        else:
            visitor_ip = record.request.META.get('REMOTE_ADDR')

        # prepare request
        payload = {
            "application" : self.APPLICATION,
            "version_complete" : self.VERSION_COMPLETE,
            "version" : self.VERSION,
            "build" : self.BUILD,
            "date" : strftime("%Y-%m-%d %H:%M:%S"),
            "gmdate" : strftime("%Y-%m-%d %H:%M:%S", gmtime()),
            "visitor_ip" : visitor_ip,
            "referrer_url" : record.request.META.get("HTTP_REFERER", ""),
            "request_uri" : record.request.path,
            "user_agent" : record.request.META.get("HTTP_USER_AGENT", ""),
            "error_type" : error_type,
            "error_message" : error_message,
            "error_no" : 500,
            "file" : file_path,
            "line" : line,
            "trace" : frames,
            "additional_info" : reporter.get_traceback_text(),
        }

        # Optionally, you may provide a custom hash of the error that Snowy will
        # use to determine if it's a duplicate or not. By default, Snowy hashes
        # the application, error number, and error message and if that hash
        # matches existing errors, we append the error to that issue instead of
        # making a new one.

        # You may provide your own custom hash that we'll check against your
        # existing issues. The hash may be up to 255 characters long.

        # For example, this will require errors come from the same application,
        # file, and exact line.
        payload['hash'] = sha1(self.APPLICATION + file_path + line).hexdigest()

        params = {
            'payload' : json.dumps(payload),
            'api_key' :  self.API_KEY,
            'project_id' : self.PROJECT_ID,
        }

        # post
        urllib.urlopen(self.SNOWY_ERROR_URL, urllib.urlencode(params))
Beispiel #15
0
    def create_from_exception(self, exc_info=None, **kwargs):
        """
        Creates an error log from an exception.
        """
        if not exc_info:
            exc_info = sys.exc_info()
        exc_type, exc_value, exc_traceback = exc_info

        def to_unicode(f):
            if isinstance(f, dict):
                nf = dict()
                for k, v in f.iteritems():
                    nf[str(k)] = to_unicode(v)
                f = nf
            elif isinstance(f, (list, tuple)):
                f = [to_unicode(f) for f in f]
            else:
                try:
                    f = smart_unicode(f)
                except (UnicodeEncodeError, UnicodeDecodeError):
                    f = '(Error decoding value)'
                except Exception: # in some cases we get a different exception
                    f = smart_unicode(type(f))
            return f

        def shorten(var):
            if not isinstance(var, basestring):
                var = to_unicode(var)
            if len(var) > 500:
                var = var[:500] + '...'
            return var

        reporter = ExceptionReporter(None, exc_type, exc_value, exc_traceback)
        frames = varmap(shorten, reporter.get_traceback_frames())

        if not kwargs.get('view'):
            modules = get_installed_apps()

            def iter_tb_frames(tb):
                while tb:
                    yield tb.tb_frame
                    tb = tb.tb_next
                
            
            for frame in iter_tb_frames(exc_traceback):
                if frame.f_globals['__name__'].rsplit('.', 1)[0] in modules:
                    break

            kwargs['view'] = '%s.%s' % (frame.f_globals['__name__'], frame.f_code.co_name)

        data = kwargs.pop('data', {}) or {}
        data['__sentry__'] = {
            'exc': map(to_unicode, [exc_type.__class__.__module__, exc_value.args, frames]),
        }

        if isinstance(exc_value, TemplateSyntaxError) and hasattr(exc_value, 'source'):
            origin, (start, end) = exc_value.source
            data['__sentry__'].update({
                'template': (origin.reload(), start, end, origin.name),
            })
        
        tb_message = '\n'.join(traceback.format_exception(exc_type, exc_value, exc_traceback))

        kwargs.setdefault('message', to_unicode(exc_value))

        return self.process(
            class_name=exc_type.__name__,
            traceback=tb_message,
            data=data,
            **kwargs
        )