Ejemplo n.º 1
0
Archivo: base.py Proyecto: d1on/raven
    def create_from_record(self, record, **kwargs):
        """
        Creates an event for a ``logging`` module ``record`` instance.

        If the record contains an attribute, ``stack``, that evaluates to True,
        it will pass this information on to process in order to grab the stack
        frames.

        >>> class ExampleHandler(logging.Handler):
        >>>     def emit(self, record):
        >>>         self.format(record)
        >>>         client.create_from_record(record)
        """
        for k in ('url', 'view', 'data'):
            if not kwargs.get(k):
                kwargs[k] = record.__dict__.get(k)

        kwargs.update({
            'logger': record.name,
            'level': record.levelno,
            'message': force_unicode(record.msg),
            'server_name': self.name,
            'stack': getattr(record, 'stack', self.auto_log_stacks),
        })

        # construct the checksum with the unparsed message
        kwargs['checksum'] = construct_checksum(**kwargs)

        # save the message with included formatting
        kwargs['message'] = record.getMessage()

        # If there's no exception being processed, exc_info may be a 3-tuple of None
        # http://docs.python.org/library/sys.html#sys.exc_info
        if record.exc_info and all(record.exc_info):
            return self.create_from_exception(record.exc_info, **kwargs)

        return self.process(
            traceback=record.exc_text,
            **kwargs
        )
Ejemplo n.º 2
0
    def create_from_record(self, record, **kwargs):
        """
        Creates an event for a ``logging`` module ``record`` instance.

        If the record contains an attribute, ``stack``, that evaluates to True,
        it will pass this information on to process in order to grab the stack
        frames.

        >>> class ExampleHandler(logging.Handler):
        >>>     def emit(self, record):
        >>>         self.format(record)
        >>>         client.create_from_record(record)
        """
        for k in ('url', 'view', 'data'):
            if not kwargs.get(k):
                kwargs[k] = record.__dict__.get(k)

        kwargs.update({
            'logger': record.name,
            'level': record.levelno,
            'message': force_unicode(record.msg),
            'server_name': self.name,
            'stack': getattr(record, 'stack', self.auto_log_stacks),
        })

        # construct the checksum with the unparsed message
        kwargs['checksum'] = construct_checksum(**kwargs)

        # save the message with included formatting
        kwargs['message'] = record.getMessage()

        # If there's no exception being processed, exc_info may be a 3-tuple of None
        # http://docs.python.org/library/sys.html#sys.exc_info
        if record.exc_info and all(record.exc_info):
            return self.create_from_exception(record.exc_info, **kwargs)

        return self.process(traceback=record.exc_text, **kwargs)
Ejemplo n.º 3
0
    def process(self, **kwargs):
        """
        Processes the message before passing it on to the server.

        This includes:

        - extracting stack frames (for non exceptions)
        - identifying module versions
        - coercing data
        - generating message identifiers

        You may pass the ``stack`` parameter to specify an explicit stack,
        or simply to tell Raven that you want to capture the stacktrace.

        To automatically grab the stack from a non-exception:

        >>> client.process(message='test', stack=True)

        To capture an explicit stack (e.g. something from a different threadframe?):

        >>> import inspect
        >>> from raven.utils import iter_stack_frames
        >>> client.process(message='test', stack=iter_stack_frames(inspect.stack()))

        """

        if kwargs.get('data'):
            # Ensure we're not changing the original data which was passed
            # to Sentry
            data = kwargs.get('data').copy()
        else:
            data = {}

        if '__sentry__' not in data:
            data['__sentry__'] = {}

        get_stack = kwargs.pop('stack', self.auto_log_stacks)
        if get_stack and not data['__sentry__'].get('frames'):
            if get_stack is True:
                stack = []
                found = None
                for frame in iter_stack_frames():
                    # There are initial frames from Sentry that need skipped
                    name = frame.f_globals.get('__name__')
                    if found is None:
                        if name == 'logging':
                            found = False
                        continue
                    elif not found:
                        if name != 'logging':
                            found = True
                        else:
                            continue
                    stack.append(frame)
                stack.reverse()
            else:
                # assume stack was a list of frames
                stack = get_stack or []
            data['__sentry__']['frames'] = varmap(shorten,
                                                  get_stack_info(stack))

        kwargs.setdefault('level', logging.ERROR)
        kwargs.setdefault('server_name', self.name)
        kwargs.setdefault('site', self.site)

        versions = get_versions(self.include_paths)
        data['__sentry__']['versions'] = versions

        # Shorten lists/strings
        for k, v in data.iteritems():
            if k == '__sentry__':
                continue
            data[k] = shorten(v,
                              string_length=self.string_max_length,
                              list_length=self.list_max_length)

        # if we've passed frames, lets try to fetch the culprit
        if not kwargs.get('view') and data['__sentry__'].get('frames'):
            # 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".
            view = get_culprit(data['__sentry__']['frames'],
                               self.include_paths, self.exclude_paths)

            if view:
                kwargs['view'] = view

        # try to fetch the current version
        if kwargs.get('view'):
            # get list of modules from right to left
            parts = kwargs['view'].split('.')
            module_list = [
                '.'.join(parts[:idx]) for idx in xrange(1,
                                                        len(parts) + 1)
            ][::-1]
            version = None
            module = None
            for m in module_list:
                if m in versions:
                    module = m
                    version = versions[m]

            # store our "best guess" for application version
            if version:
                data['__sentry__'].update({
                    'version': version,
                    'module': module,
                })

        if 'checksum' not in kwargs:
            kwargs['checksum'] = checksum = construct_checksum(**kwargs)
        else:
            checksum = kwargs['checksum']

        # create ID client-side so that it can be passed to application
        message_id = uuid.uuid4().hex
        kwargs['message_id'] = message_id

        # Make sure all data is coerced
        kwargs['data'] = transform(data)

        if 'timestamp' not in kwargs:
            kwargs['timestamp'] = datetime.datetime.utcnow()

        self.send(**kwargs)

        return (message_id, checksum)
Ejemplo n.º 4
0
Archivo: base.py Proyecto: d1on/raven
    def process(self, **kwargs):
        """
        Processes the message before passing it on to the server.

        This includes:

        - extracting stack frames (for non exceptions)
        - identifying module versions
        - coercing data
        - generating message identifiers

        You may pass the ``stack`` parameter to specify an explicit stack,
        or simply to tell Raven that you want to capture the stacktrace.

        To automatically grab the stack from a non-exception:

        >>> client.process(message='test', stack=True)

        To capture an explicit stack (e.g. something from a different threadframe?):

        >>> import inspect
        >>> from raven.utils import iter_stack_frames
        >>> client.process(message='test', stack=iter_stack_frames(inspect.stack()))

        """

        if kwargs.get('data'):
            # Ensure we're not changing the original data which was passed
            # to Sentry
            data = kwargs.get('data').copy()
        else:
            data = {}

        if '__sentry__' not in data:
            data['__sentry__'] = {}

        get_stack = kwargs.pop('stack', self.auto_log_stacks)
        if get_stack and not data['__sentry__'].get('frames'):
            if get_stack is True:
                stack = []
                found = None
                for frame in iter_stack_frames():
                    # There are initial frames from Sentry that need skipped
                    name = frame.f_globals.get('__name__')
                    if found is None:
                        if name == 'logging':
                            found = False
                        continue
                    elif not found:
                        if name != 'logging':
                            found = True
                        else:
                            continue
                    stack.append(frame)
                stack.reverse()
            else:
                # assume stack was a list of frames
                stack = get_stack or []
            data['__sentry__']['frames'] = varmap(shorten, get_stack_info(stack))

        kwargs.setdefault('level', logging.ERROR)
        kwargs.setdefault('server_name', self.name)
        kwargs.setdefault('site', self.site)

        versions = get_versions(self.include_paths)
        data['__sentry__']['versions'] = versions

        # Shorten lists/strings
        for k, v in data.iteritems():
            if k == '__sentry__':
                continue
            data[k] = shorten(v, string_length=self.string_max_length, list_length=self.list_max_length)

        # if we've passed frames, lets try to fetch the culprit
        if not kwargs.get('view') and data['__sentry__'].get('frames'):
            # 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".
            view = get_culprit(data['__sentry__']['frames'], self.include_paths, self.exclude_paths)

            if view:
                kwargs['view'] = view

        # try to fetch the current version
        if kwargs.get('view'):
            # get list of modules from right to left
            parts = kwargs['view'].split('.')
            module_list = ['.'.join(parts[:idx]) for idx in xrange(1, len(parts) + 1)][::-1]
            version = None
            module = None
            for m in module_list:
                if m in versions:
                    module = m
                    version = versions[m]

            # store our "best guess" for application version
            if version:
                data['__sentry__'].update({
                    'version': version,
                    'module': module,
                })

        if 'checksum' not in kwargs:
            kwargs['checksum'] = checksum = construct_checksum(**kwargs)
        else:
            checksum = kwargs['checksum']

        # create ID client-side so that it can be passed to application
        message_id = uuid.uuid4().hex
        kwargs['message_id'] = message_id

        # Make sure all data is coerced
        kwargs['data'] = transform(data)

        if 'timestamp' not in kwargs:
            kwargs['timestamp'] = datetime.datetime.utcnow()

        self.send(**kwargs)

        return (message_id, checksum)