Exemplo n.º 1
0
    def capture(self, exc_info=None, **kwargs):
        new_exc_info = False
        if not exc_info or exc_info is True:
            new_exc_info = True
            exc_info = sys.exc_info()

        if not exc_info:
            raise ValueError('No exception found')

        try:
            exc_type, exc_value, exc_traceback = exc_info

            frames = varmap(
                lambda k, v: shorten(v,
                                     string_length=self.client.
                                     string_max_length,
                                     list_length=self.client.list_max_length),
                get_stack_info(iter_traceback_frames(exc_traceback)))

            culprit = get_culprit(frames, self.client.include_paths,
                                  self.client.exclude_paths)

            if hasattr(exc_type, '__module__'):
                exc_module = exc_type.__module__
                exc_type = exc_type.__name__
            else:
                exc_module = None
                exc_type = exc_type.__name__
        finally:
            if new_exc_info:
                try:
                    del exc_info
                    del exc_traceback
                except Exception, e:
                    self.logger.exception(e)
Exemplo n.º 2
0
 def filter_stacktrace(self, data):
     if 'frames' not in data:
         return
     for frame in data['frames']:
         if 'vars' not in frame:
             continue
         frame['vars'] = varmap(self.sanitize, frame['vars'])
Exemplo n.º 3
0
    def capture(self, exc_info=None, **kwargs):
        new_exc_info = False
        if not exc_info or exc_info is True:
            new_exc_info = True
            exc_info = sys.exc_info()

        if not exc_info:
            raise ValueError('No exception found')

        try:
            exc_type, exc_value, exc_traceback = exc_info

            frames = varmap(lambda k, v: shorten(v,
                string_length=self.client.string_max_length, list_length=self.client.list_max_length),
            get_stack_info(iter_traceback_frames(exc_traceback)))

            culprit = get_culprit(frames, self.client.include_paths, self.client.exclude_paths)

            if hasattr(exc_type, '__module__'):
                exc_module = exc_type.__module__
                exc_type = exc_type.__name__
            else:
                exc_module = None
                exc_type = exc_type.__name__
        finally:
            if new_exc_info:
                try:
                    del exc_info
                    del exc_traceback
                except Exception, e:
                    self.logger.exception(e)
Exemplo n.º 4
0
    def capture(self, exc_info=None, **kwargs):
        new_exc_info = False
        if not exc_info or exc_info is True:
            new_exc_info = True
            exc_info = sys.exc_info()

        if not exc_info:
            raise ValueError('No exception found')

        try:
            exc_type, exc_value, exc_traceback = exc_info

            frames = varmap(
                lambda k, v: shorten(v,
                                     string_length=self.client.string_max_length,
                                     list_length=self.client.list_max_length
                                     ),
                get_stack_info((iter_traceback_frames(exc_traceback)))
            )

            culprit = get_culprit(frames, self.client.include_paths,
                                  self.client.exclude_paths)

            if hasattr(exc_type, '__module__'):
                exc_module = exc_type.__module__
                exc_type = exc_type.__name__
            else:
                exc_module = None
                exc_type = exc_type.__name__
        finally:
            if new_exc_info:
                try:
                    del exc_info
                    del exc_traceback
                except Exception as e:
                    self.logger.exception(e)

        return {
            'level': logging.ERROR,
            'culprit': culprit,
            'exception': {
                'value': to_unicode(exc_value),
                'type': str(exc_type),
                'module': str(exc_module),
            },
            'stacktrace': {
                'frames': frames
            },
        }
Exemplo n.º 5
0
    def capture(self, exc_info=None, **kwargs):
        new_exc_info = False
        if not exc_info or exc_info is True:
            new_exc_info = True
            exc_info = sys.exc_info()

        if not exc_info:
            raise ValueError('No exception found')

        try:
            exc_type, exc_value, exc_traceback = exc_info

            frames = varmap(
                lambda k, v: shorten(v,
                                     string_length=self.client.
                                     string_max_length,
                                     list_length=self.client.list_max_length),
                get_stack_info((iter_traceback_frames(exc_traceback))))

            culprit = get_culprit(frames, self.client.include_paths,
                                  self.client.exclude_paths)

            if hasattr(exc_type, '__module__'):
                exc_module = exc_type.__module__
                exc_type = exc_type.__name__
            else:
                exc_module = None
                exc_type = exc_type.__name__
        finally:
            if new_exc_info:
                try:
                    del exc_info
                    del exc_traceback
                except Exception as e:
                    self.logger.exception(e)

        return {
            'level': logging.ERROR,
            'culprit': culprit,
            'exception': {
                'value': to_unicode(exc_value),
                'type': str(exc_type),
                'module': str(exc_module),
            },
            'stacktrace': {
                'frames': frames
            },
        }
Exemplo n.º 6
0
    def filter_http(self, data):
        for n in ('data', 'cookies', 'headers', 'env', 'query_string'):
            if n not in data:
                continue

            if isinstance(data[n], basestring) and '=' in data[n]:
                # at this point we've assumed it's a standard HTTP query
                querybits = []
                for bit in data[n].split('&'):
                    chunk = bit.split('=')
                    if len(chunk) == 2:
                        querybits.append((chunk[0], self.sanitize(*chunk)))
                    else:
                        querybits.append(chunk)

                data[n] = '&'.join('='.join(k) for k in querybits)
            else:
                data[n] = varmap(self.sanitize, data[n])
Exemplo n.º 7
0
    def filter_http(self, data):
        for n in ('data', 'cookies', 'headers', 'env', 'query_string'):
            if n not in data:
                continue

            if isinstance(data[n], (six.binary_type, ) + six.string_types):
                text_data = force_text(data[n], errors='replace')
                if '=' in text_data:
                    # at this point we've assumed it's a standard HTTP query
                    querybits = []
                    for bit in text_data.split('&'):
                        chunk = bit.split('=')
                        if len(chunk) == 2:
                            querybits.append((chunk[0], self.sanitize(*chunk)))
                        else:
                            querybits.append(chunk)

                    data[n] = '&'.join('='.join(k) for k in querybits)
                    continue
            data[n] = varmap(self.sanitize, data[n])
Exemplo n.º 8
0
    def filter_http(self, data):
        for n in ('data', 'cookies', 'headers', 'env', 'query_string'):
            if n not in data:
                continue

            if isinstance(data[n], (six.binary_type,) + six.string_types):
                text_data = force_text(data[n], errors='replace')
                if '=' in text_data:
                    # at this point we've assumed it's a standard HTTP query
                    querybits = []
                    for bit in text_data.split('&'):
                        chunk = bit.split('=')
                        if len(chunk) == 2:
                            querybits.append((chunk[0], self.sanitize(*chunk)))
                        else:
                            querybits.append(chunk)

                    data[n] = '&'.join('='.join(k) for k in querybits)
                    continue
            data[n] = varmap(self.sanitize, data[n])
Exemplo n.º 9
0
    def build_msg_for_logging(self, event_type, data=None, date=None,
            extra=None, stack=None,
            **kwargs):
        """
        Captures, processes and serializes an event into a dict object
        """
        # create ID client-side so that it can be passed to application
        event_id = uuid.uuid4().hex

        if data is None:
            data = {}
        if extra is None:
            extra = {}
        if not date:
            date = datetime.datetime.utcnow()
        if stack is None:
            stack = self.auto_log_stacks

        self.build_msg(data=data)

        # if '.' not in event_type:
            # Assume it's a builtin
        event_type = 'opbeat.events.%s' % event_type

        handler = self.get_handler(event_type)

        result = handler.capture(**kwargs)

        # data (explicit) culprit takes over auto event detection
        culprit = result.pop('culprit', None)
        if data.get('culprit'):
            culprit = data['culprit']

        for k, v in result.iteritems():
            if k not in data:
                data[k] = v

        if stack and 'stacktrace' not in data:
            if stack is True:
                frames = iter_stack_frames()
            else:
                frames = stack

            data.update({
                'stacktrace': {
                    'frames': varmap(lambda k, v: shorten(v,
                        string_length=self.string_max_length,
                        list_length=self.list_max_length),
                    get_stack_info(frames))
                },
            })

        if 'stacktrace' in data and not culprit:
            culprit = get_culprit(
                data['stacktrace']['frames'],
                self.include_paths, self.exclude_paths
            )

        if not data.get('level'):
            data['level'] = 'error'

        if isinstance( data['level'], ( int, long ) ):
            data['level'] = logging.getLevelName(data['level']).lower()

        data.setdefault('extra', {})

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

        if culprit:
            data['culprit'] = culprit

        # Run the data through processors
        for processor in self.get_processors():
            data.update(processor.process(data))

        # Make sure all data is coerced
        data = transform(data)

        if 'message' not in data:
            data['message'] = handler.to_string(data)

        # Make sure certain values are not too long
        for v in defaults.MAX_LENGTH_VALUES:
            if v in data:
                data[v] = shorten(data[v],
                            string_length=defaults.MAX_LENGTH_VALUES[v]
                          )

        data.update({
            'timestamp':  date,
            # 'time_spent': time_spent,
            'client_supplied_id': event_id,
        })

        return data
Exemplo n.º 10
0
    def build_msg_for_logging(self,
                              event_type,
                              data=None,
                              date=None,
                              extra=None,
                              stack=None,
                              **kwargs):
        """
        Captures, processes and serializes an event into a dict object
        """
        # create ID client-side so that it can be passed to application
        event_id = uuid.uuid4().hex

        if data is None:
            data = {}
        if extra is None:
            extra = {}
        if not date:
            date = datetime.datetime.utcnow()
        if stack is None:
            stack = self.auto_log_stacks

        self.build_msg(data=data)

        # if '.' not in event_type:
        # Assume it's a builtin
        event_type = 'opbeat.events.%s' % event_type

        handler = self.get_handler(event_type)

        result = handler.capture(**kwargs)

        # data (explicit) culprit takes over auto event detection
        culprit = result.pop('culprit', None)
        if data.get('culprit'):
            culprit = data['culprit']

        for k, v in result.iteritems():
            if k not in data:
                data[k] = v

        if stack and 'stacktrace' not in data:
            if stack is True:
                frames = iter_stack_frames()
            else:
                frames = stack

            data.update({
                'stacktrace': {
                    'frames':
                    varmap(
                        lambda k, v: shorten(v,
                                             string_length=self.
                                             string_max_length,
                                             list_length=self.list_max_length),
                        get_stack_info(frames))
                },
            })

        if 'stacktrace' in data and not culprit:
            culprit = get_culprit(data['stacktrace']['frames'],
                                  self.include_paths, self.exclude_paths)

        if not data.get('level'):
            data['level'] = 'error'

        if isinstance(data['level'], (int, long)):
            data['level'] = logging.getLevelName(data['level']).lower()

        data.setdefault('extra', {})

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

        if culprit:
            data['culprit'] = culprit

        # Run the data through processors
        for processor in self.get_processors():
            data.update(processor.process(data))

        # Make sure all data is coerced
        data = transform(data)

        if 'message' not in data:
            data['message'] = handler.to_string(data)

        # Make sure certain values are not too long
        for v in defaults.MAX_LENGTH_VALUES:
            if v in data:
                data[v] = shorten(data[v],
                                  string_length=defaults.MAX_LENGTH_VALUES[v])

        data.update({
            'timestamp': date,
            # 'time_spent': time_spent,
            'client_supplied_id': event_id,
        })

        return data