def load(dsn, scope=None, transport_registry=None):
    """
    Parses a Sentry compatible DSN and loads it
    into the given scope.

    >>> import raven

    >>> dsn = 'https://*****:*****@sentry.local/project_id'

    >>> # Apply configuration to local scope
    >>> raven.load(dsn, locals())

    >>> # Return DSN configuration
    >>> options = raven.load(dsn)
    """

    if not transport_registry:
        from raven.transport import TransportRegistry, default_transports
        transport_registry = TransportRegistry(default_transports)

    url = urlparse(dsn)

    if not transport_registry.supported_scheme(url.scheme):
        raise ValueError('Unsupported Sentry DSN scheme: %r' % url.scheme)

    if scope is None:
        scope = {}
    scope_extras = transport_registry.compute_scope(url, scope)
    scope.update(scope_extras)

    return scope
def load(dsn, scope=None, transport_registry=None):
    """
    Parses a Sentry compatible DSN and loads it
    into the given scope.

    >>> import raven

    >>> dsn = 'https://*****:*****@sentry.local/project_id'

    >>> # Apply configuration to local scope
    >>> raven.load(dsn, locals())

    >>> # Return DSN configuration
    >>> options = raven.load(dsn)
    """

    if not transport_registry:
        from raven.transport import TransportRegistry, default_transports
        transport_registry = TransportRegistry(default_transports)

    url = urlparse(dsn)

    if not transport_registry.supported_scheme(url.scheme):
        raise ValueError('Unsupported Sentry DSN scheme: %r' % url.scheme)

    if scope is None:
        scope = {}
    scope_extras = transport_registry.compute_scope(url, scope)
    scope.update(scope_extras)

    return scope
Beispiel #3
0
 def from_string(cls, value, transport=None, transport_registry=None):
     if PY2:
         value = to_string(value)
     url = urlparse(value)
     if url.scheme not in ('http', 'https'):
         warnings.warn(
             'Transport selection via DSN is deprecated. You should explicitly pass the transport class to Client() instead.'
         )
     if transport is None:
         if not transport_registry:
             from raven.transport import TransportRegistry, default_transports
             transport_registry = TransportRegistry(default_transports)
         if not transport_registry.supported_scheme(url.scheme):
             raise InvalidDsn(ERR_UNKNOWN_SCHEME.format(url.scheme, value))
         transport = transport_registry.get_transport_cls(url.scheme)
     netloc = url.hostname
     if url.port:
         netloc += ':%s' % url.port
     path_bits = url.path.rsplit('/', 1)
     if len(path_bits) > 1:
         path = path_bits[0]
     else:
         path = ''
     project = path_bits[-1]
     if not all([netloc, project, url.username, url.password]):
         raise InvalidDsn('Invalid Sentry DSN: %r' % url.geturl())
     base_url = '%s://%s%s' % (url.scheme.rsplit('+', 1)[-1], netloc, path)
     return cls(base_url=base_url,
                project=project,
                public_key=url.username,
                secret_key=url.password,
                options=dict(parse_qsl(url.query)),
                transport=transport)
Beispiel #4
0
    def from_string(cls, value, transport=None, transport_registry=None):
        # in Python 2.x sending the DSN as a unicode value will eventually
        # cause issues in httplib
        if PY2:
            value = to_string(value)

        url = urlparse(value.strip())

        if url.scheme not in ("http", "https"):
            warnings.warn(
                "Transport selection via DSN is deprecated. You should explicitly pass the transport class to Client() instead."
            )

        if transport is None:
            if not transport_registry:
                from raven.transport import TransportRegistry, default_transports

                transport_registry = TransportRegistry(default_transports)

            if not transport_registry.supported_scheme(url.scheme):
                raise InvalidDsn(ERR_UNKNOWN_SCHEME.format(url.scheme, value))

            transport = transport_registry.get_transport_cls(url.scheme)

        netloc = url.hostname
        if url.port:
            netloc += ":%s" % url.port

        path_bits = url.path.rsplit("/", 1)
        if len(path_bits) > 1:
            path = path_bits[0]
        else:
            path = ""
        project = path_bits[-1]

        if not all([netloc, project, url.username, url.password]):
            raise InvalidDsn("Invalid Sentry DSN: %r" % url.geturl())

        base_url = "%s://%s%s" % (url.scheme.rsplit("+", 1)[-1], netloc, path)

        return cls(
            base_url=base_url,
            project=project,
            public_key=url.username,
            secret_key=url.password,
            options=dict(parse_qsl(url.query)),
            transport=transport,
        )
Beispiel #5
0
    def from_string(cls, value, transport=None, transport_registry=None):
        url = urlparse(value)

        if url.scheme not in ('http', 'https'):
            warnings.warn('Transport selection via DSN is deprecated. You should explicitly pass the transport class to Client() instead.')

        if transport is None:
            if not transport_registry:
                from raven.transport import TransportRegistry, default_transports
                transport_registry = TransportRegistry(default_transports)

            if not transport_registry.supported_scheme(url.scheme):
                raise InvalidDsn(ERR_UNKNOWN_SCHEME.format(url.scheme))

            transport = transport_registry.get_transport_cls(url.scheme)

        netloc = url.hostname
        if url.port:
            netloc += ':%s' % url.port

        path_bits = url.path.rsplit('/', 1)
        if len(path_bits) > 1:
            path = path_bits[0]
        else:
            path = ''
        project = path_bits[-1]

        if not all([netloc, project, url.username, url.password]):
            raise InvalidDsn('Invalid Sentry DSN: %r' % url.geturl())

        base_url = '%s://%s%s' % (url.scheme.rsplit('+', 1)[-1], netloc, path)

        return cls(
            base_url=base_url,
            project=project,
            public_key=url.username,
            secret_key=url.password,
            options=dict(parse_qsl(url.query)),
            transport=transport,
        )
Beispiel #6
0
def setup_handlers():
    if 'sentry_handler' not in __opts__:
        log.debug('No \'sentry_handler\' key was found in the configuration')
        return False
    options = {}
    dsn = get_config_value('dsn')
    if dsn is not None:
        try:
            # support raven ver 5.5.0
            from raven.transport import TransportRegistry, default_transports
            from raven.utils.urlparse import urlparse
            transport_registry = TransportRegistry(default_transports)
            url = urlparse(dsn)
            if not transport_registry.supported_scheme(url.scheme):
                raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(
                    url.scheme))
            dsn_config = {}
            conf_extras = transport_registry.compute_scope(url, dsn_config)
            dsn_config.update(conf_extras)
            options.update({
                'project': dsn_config['SENTRY_PROJECT'],
                'servers': dsn_config['SENTRY_SERVERS'],
                'public_key': dsn_config['SENTRY_PUBLIC_KEY'],
                'secret_key': dsn_config['SENTRY_SECRET_KEY']
            })
        except ValueError as exc:
            log.info('Raven failed to parse the configuration provided '
                     'DSN: {0}'.format(exc))

    # Allow options to be overridden if previously parsed, or define them
    for key in ('project', 'servers', 'public_key', 'secret_key'):
        config_value = get_config_value(key)
        if config_value is None and key not in options:
            log.debug('The required \'sentry_handler\' configuration key, '
                      '\'{0}\', is not properly configured. Not configuring '
                      'the sentry logging handler.'.format(key))
            return
        elif config_value is None:
            continue
        options[key] = config_value

    # site: An optional, arbitrary string to identify this client installation.
    options.update({
        # site: An optional, arbitrary string to identify this client
        # installation
        'site': get_config_value('site'),

        # name: This will override the server_name value for this installation.
        # Defaults to socket.gethostname()
        'name': get_config_value('name'),

        # exclude_paths: Extending this allow you to ignore module prefixes
        # when sentry attempts to discover which function an error comes from
        'exclude_paths': get_config_value('exclude_paths', ()),

        # include_paths: For example, in Django this defaults to your list of
        # INSTALLED_APPS, and is used for drilling down where an exception is
        # located
        'include_paths': get_config_value('include_paths', ()),

        # list_max_length: The maximum number of items a list-like container
        # should store.
        'list_max_length': get_config_value('list_max_length'),

        # string_max_length: The maximum characters of a string that should be
        # stored.
        'string_max_length': get_config_value('string_max_length'),

        # auto_log_stacks: Should Raven automatically log frame stacks
        # (including locals) all calls as it would for exceptions.
        'auto_log_stacks': get_config_value('auto_log_stacks'),

        # timeout: If supported, the timeout value for sending messages to
        # remote.
        'timeout': get_config_value('timeout', 1),

        # processors: A list of processors to apply to events before sending
        # them to the Sentry server. Useful for sending additional global state
        # data or sanitizing data that you want to keep off of the server.
        'processors': get_config_value('processors'),

        # dsn: Ensure the DSN is passed into the client
        'dsn': dsn
    })

    client = raven.Client(**options)
    context = get_config_value('context')
    context_dict = {}
    if context is not None:
        for tag in context:
            tag_value = __salt__['grains.get'](tag)
            if len(tag_value) > 0:
                context_dict[tag] = tag_value
        if len(context_dict) > 0:
            client.context.merge({'tags': context_dict})
    try:
        handler = SentryHandler(client)
        handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
        return handler
    except ValueError as exc:
        log.debug(
            'Failed to setup the sentry logging handler: {0}'.format(exc),
            exc_info=exc)
Beispiel #7
0
def setup_handlers():
    """
    sets up the sentry handler
    """
    if not __opts__.get("sentry_handler"):
        log.debug("'sentry_handler' config is empty or not defined")
        return False

    # Regenerating dunders can be expensive, so only do it if the user enables
    # `sentry_handler` as checked above
    __grains__ = salt.loader.grains(__opts__)
    __salt__ = salt.loader.minion_mods(__opts__)

    options = {}
    dsn = get_config_value("dsn")
    if dsn is not None:
        try:
            # support raven ver 5.5.0
            from raven.transport import TransportRegistry, default_transports
            from raven.utils.urlparse import urlparse

            transport_registry = TransportRegistry(default_transports)
            url = urlparse(dsn)
            if not transport_registry.supported_scheme(url.scheme):
                raise ValueError("Unsupported Sentry DSN scheme: {}".format(
                    url.scheme))
        except ValueError as exc:
            log.info(
                "Raven failed to parse the configuration provided DSN: %s",
                exc)

    if not dsn:
        for key in ("project", "servers", "public_key", "secret_key"):
            config_value = get_config_value(key)
            if config_value is None and key not in options:
                log.debug(
                    "The required 'sentry_handler' configuration key, "
                    "'%s', is not properly configured. Not configuring "
                    "the sentry logging handler.",
                    key,
                )
                return
            elif config_value is None:
                continue
            options[key] = config_value

    # site: An optional, arbitrary string to identify this client installation.
    options.update({
        # site: An optional, arbitrary string to identify this client
        # installation
        "site": get_config_value("site"),
        # name: This will override the server_name value for this installation.
        # Defaults to socket.gethostname()
        "name": get_config_value("name"),
        # exclude_paths: Extending this allow you to ignore module prefixes
        # when sentry attempts to discover which function an error comes from
        "exclude_paths": get_config_value("exclude_paths", ()),
        # include_paths: For example, in Django this defaults to your list of
        # INSTALLED_APPS, and is used for drilling down where an exception is
        # located
        "include_paths": get_config_value("include_paths", ()),
        # list_max_length: The maximum number of items a list-like container
        # should store.
        "list_max_length": get_config_value("list_max_length"),
        # string_max_length: The maximum characters of a string that should be
        # stored.
        "string_max_length": get_config_value("string_max_length"),
        # auto_log_stacks: Should Raven automatically log frame stacks
        # (including locals) all calls as it would for exceptions.
        "auto_log_stacks": get_config_value("auto_log_stacks"),
        # timeout: If supported, the timeout value for sending messages to
        # remote.
        "timeout": get_config_value("timeout", 1),
        # processors: A list of processors to apply to events before sending
        # them to the Sentry server. Useful for sending additional global state
        # data or sanitizing data that you want to keep off of the server.
        "processors": get_config_value("processors"),
        # dsn: Ensure the DSN is passed into the client
        "dsn": dsn,
    })

    client = raven.Client(**options)
    context = get_config_value("context")
    context_dict = {}
    if context is not None:
        for tag in context:
            try:
                tag_value = __grains__[tag]
            except KeyError:
                log.debug("Sentry tag '%s' not found in grains.", tag)
                continue
            if tag_value:
                context_dict[tag] = tag_value
        if context_dict:
            client.context.merge({"tags": context_dict})
    try:
        handler = SentryHandler(client)

        exclude_patterns = get_config_value("exclude_patterns", None)
        if exclude_patterns:
            filter_regexes = [
                re.compile(pattern) for pattern in exclude_patterns
            ]

            class FilterExcludedMessages:
                @staticmethod
                def filter(record):
                    m = record.getMessage()
                    return not any(regex.search(m) for regex in filter_regexes)

            handler.addFilter(FilterExcludedMessages())

        handler.setLevel(LOG_LEVELS[get_config_value("log_level", "error")])
        return handler
    except ValueError as exc:
        log.debug("Failed to setup the sentry logging handler", exc_info=True)
Beispiel #8
0
def setup_handlers():
    '''
    sets up the sentry handler
    '''
    __grains__ = salt.loader.grains(__opts__)
    __salt__ = salt.loader.minion_mods(__opts__)
    if 'sentry_handler' not in __opts__:
        log.debug('No \'sentry_handler\' key was found in the configuration')
        return False
    options = {}
    dsn = get_config_value('dsn')
    if dsn is not None:
        try:
            # support raven ver 5.5.0
            from raven.transport import TransportRegistry, default_transports
            from raven.utils.urlparse import urlparse
            transport_registry = TransportRegistry(default_transports)
            url = urlparse(dsn)
            if not transport_registry.supported_scheme(url.scheme):
                raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(
                    url.scheme))
        except ValueError as exc:
            log.info(
                'Raven failed to parse the configuration provided DSN: %s',
                exc)

    if not dsn:
        for key in ('project', 'servers', 'public_key', 'secret_key'):
            config_value = get_config_value(key)
            if config_value is None and key not in options:
                log.debug(
                    'The required \'sentry_handler\' configuration key, '
                    '\'%s\', is not properly configured. Not configuring '
                    'the sentry logging handler.', key)
                return
            elif config_value is None:
                continue
            options[key] = config_value

    # site: An optional, arbitrary string to identify this client installation.
    options.update({
        # site: An optional, arbitrary string to identify this client
        # installation
        'site': get_config_value('site'),

        # name: This will override the server_name value for this installation.
        # Defaults to socket.gethostname()
        'name': get_config_value('name'),

        # exclude_paths: Extending this allow you to ignore module prefixes
        # when sentry attempts to discover which function an error comes from
        'exclude_paths': get_config_value('exclude_paths', ()),

        # include_paths: For example, in Django this defaults to your list of
        # INSTALLED_APPS, and is used for drilling down where an exception is
        # located
        'include_paths': get_config_value('include_paths', ()),

        # list_max_length: The maximum number of items a list-like container
        # should store.
        'list_max_length': get_config_value('list_max_length'),

        # string_max_length: The maximum characters of a string that should be
        # stored.
        'string_max_length': get_config_value('string_max_length'),

        # auto_log_stacks: Should Raven automatically log frame stacks
        # (including locals) all calls as it would for exceptions.
        'auto_log_stacks': get_config_value('auto_log_stacks'),

        # timeout: If supported, the timeout value for sending messages to
        # remote.
        'timeout': get_config_value('timeout', 1),

        # processors: A list of processors to apply to events before sending
        # them to the Sentry server. Useful for sending additional global state
        # data or sanitizing data that you want to keep off of the server.
        'processors': get_config_value('processors'),

        # dsn: Ensure the DSN is passed into the client
        'dsn': dsn
    })

    client = raven.Client(**options)
    context = get_config_value('context')
    context_dict = {}
    if context is not None:
        for tag in context:
            try:
                tag_value = __grains__[tag]
            except KeyError:
                log.debug('Sentry tag \'%s\' not found in grains.', tag)
                continue
            if len(tag_value) > 0:
                context_dict[tag] = tag_value
        if len(context_dict) > 0:
            client.context.merge({'tags': context_dict})
    try:
        handler = SentryHandler(client)

        exclude_patterns = get_config_value('exclude_patterns', None)
        if exclude_patterns:
            filter_regexes = [
                re.compile(pattern) for pattern in exclude_patterns
            ]

            class FilterExcludedMessages(object):
                @staticmethod
                def filter(record):
                    m = record.getMessage()
                    return not any(regex.search(m) for regex in filter_regexes)

            handler.addFilter(FilterExcludedMessages())

        handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
        return handler
    except ValueError as exc:
        log.debug('Failed to setup the sentry logging handler', exc_info=True)
Beispiel #9
0
def setup_handlers():
    if 'sentry_handler' not in __opts__:
        log.debug('No \'sentry_handler\' key was found in the configuration')
        return False
    options = {}
    dsn = get_config_value('dsn')
    if dsn is not None:
        try:
            # support raven ver 5.5.0
            from raven.transport import TransportRegistry, default_transports
            from raven.utils.urlparse import urlparse
            transport_registry = TransportRegistry(default_transports)
            url = urlparse(dsn)
            if not transport_registry.supported_scheme(url.scheme):
                raise ValueError('Unsupported Sentry DSN scheme: {0}'.format(url.scheme))
            dsn_config = {}
            conf_extras = transport_registry.compute_scope(url, dsn_config)
            dsn_config.update(conf_extras)
            options.update({
                'project': dsn_config['SENTRY_PROJECT'],
                'servers': dsn_config['SENTRY_SERVERS'],
                'public_key': dsn_config['SENTRY_PUBLIC_KEY'],
                'secret_key': dsn_config['SENTRY_SECRET_KEY']
            })
        except ValueError as exc:
            log.info(
                'Raven failed to parse the configuration provided '
                'DSN: {0}'.format(exc)
            )

    # Allow options to be overridden if previously parsed, or define them
    for key in ('project', 'servers', 'public_key', 'secret_key'):
        config_value = get_config_value(key)
        if config_value is None and key not in options:
            log.debug(
                'The required \'sentry_handler\' configuration key, '
                '\'{0}\', is not properly configured. Not configuring '
                'the sentry logging handler.'.format(key)
            )
            return
        elif config_value is None:
            continue
        options[key] = config_value

    # site: An optional, arbitrary string to identify this client installation.
    options.update({
        # site: An optional, arbitrary string to identify this client
        # installation
        'site': get_config_value('site'),

        # name: This will override the server_name value for this installation.
        # Defaults to socket.gethostname()
        'name': get_config_value('name'),

        # exclude_paths: Extending this allow you to ignore module prefixes
        # when sentry attempts to discover which function an error comes from
        'exclude_paths': get_config_value('exclude_paths', ()),

        # include_paths: For example, in Django this defaults to your list of
        # INSTALLED_APPS, and is used for drilling down where an exception is
        # located
        'include_paths': get_config_value('include_paths', ()),

        # list_max_length: The maximum number of items a list-like container
        # should store.
        'list_max_length': get_config_value('list_max_length'),

        # string_max_length: The maximum characters of a string that should be
        # stored.
        'string_max_length': get_config_value('string_max_length'),

        # auto_log_stacks: Should Raven automatically log frame stacks
        # (including locals) all calls as it would for exceptions.
        'auto_log_stacks': get_config_value('auto_log_stacks'),

        # timeout: If supported, the timeout value for sending messages to
        # remote.
        'timeout': get_config_value('timeout', 1),

        # processors: A list of processors to apply to events before sending
        # them to the Sentry server. Useful for sending additional global state
        # data or sanitizing data that you want to keep off of the server.
        'processors': get_config_value('processors'),

        # dsn: Ensure the DSN is passed into the client
        'dsn': dsn
    })

    client = raven.Client(**options)
    context = get_config_value('context')
    context_dict = {}
    if context is not None:
        for tag in context:
            tag_value = __salt__['grains.get'](tag)
            if len(tag_value) > 0:
                context_dict[tag] = tag_value
        if len(context_dict) > 0:
            client.context.merge({'tags': context_dict})
    try:
        handler = SentryHandler(client)
        handler.setLevel(LOG_LEVELS[get_config_value('log_level', 'error')])
        return handler
    except ValueError as exc:
        log.debug(
            'Failed to setup the sentry logging handler: {0}'.format(exc),
            exc_info=exc
        )