Example #1
0
def configure_raven(app):
    if 'SENTRY_DSN' in os.environ:
        import raven
        from raven.contrib.flask import Sentry

        raven.load(os.environ['SENTRY_DSN'], app.config)
        return Sentry(app)
Example #2
0
    def __init__(self, dsn_file):
        try:
            loaded = unserialize_yaml(dsn_file, critical=True)
            sentry_dsn = loaded["dsn"]
            self._sentry_dsn = sentry_dsn
            logger.debug("sentry_dsn: %s", sentry_dsn)
        except IOError as err:
            logger.error(
                "Sentry monitoring DSN file %s does not exist"
                "or is unreadable. Error: %s",
                dsn_file, err)
            raise nagiosplugin.CheckError(
                "Invalid sentry monitoring DSN file: {}".format(dsn_file))

        dsn_parsed = raven.load(sentry_dsn)
        self._public_key = dsn_parsed["SENTRY_PUBLIC_KEY"]
        self._secret_key = dsn_parsed["SENTRY_SECRET_KEY"]
        transport_options = dsn_parsed["SENTRY_TRANSPORT_OPTIONS"]
        self._verify_ssl = False if ("verify_ssl" in transport_options
                                     and transport_options["verify_ssl"] == "0"
                                     ) else True

        # API format: GET /api/0/projects/{project_id}/groups/
        server = dsn_parsed["SENTRY_SERVERS"][0]
        project_id = dsn_parsed["SENTRY_PROJECT"]
        parsed = urlparse.urlparse(server)
        self._url = urlparse.urlunparse((
            parsed.scheme,
            parsed.netloc,
            "/api/0/projects/{}/groups/".format(project_id),
            parsed.params,
            parsed.query,
            parsed.fragment,
        ))
Example #3
0
    def __init__(self, dsn_file):
        try:
            loaded = unserialize_yaml(dsn_file, critical=True)
            sentry_dsn = loaded["dsn"]
            self._sentry_dsn = sentry_dsn
            logger.debug("sentry_dsn: %s", sentry_dsn)
        except IOError as err:
            logger.error(
                "Sentry monitoring DSN file %s does not exist"
                "or is unreadable. Error: %s", dsn_file, err)
            raise nagiosplugin.CheckError(
                "Invalid sentry monitoring DSN file: {}".format(dsn_file))

        dsn_parsed = raven.load(sentry_dsn)
        self._public_key = dsn_parsed["SENTRY_PUBLIC_KEY"]
        self._secret_key = dsn_parsed["SENTRY_SECRET_KEY"]
        transport_options = dsn_parsed["SENTRY_TRANSPORT_OPTIONS"]
        self._verify_ssl = False if (
            "verify_ssl" in transport_options
            and transport_options["verify_ssl"] == "0") else True

        # API format: GET /api/0/projects/{project_id}/groups/
        server = dsn_parsed["SENTRY_SERVERS"][0]
        project_id = dsn_parsed["SENTRY_PROJECT"]
        parsed = urlparse.urlparse(server)
        self._url = urlparse.urlunparse((
            parsed.scheme,
            parsed.netloc,
            "/api/0/projects/{}/groups/".format(project_id),
            parsed.params,
            parsed.query,
            parsed.fragment,
        ))
Example #4
0
    def __init__(self, dsn=None, **options):
        o = options

        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger('%s.%s' % (cls.__module__,
            cls.__name__))
        self.error_logger = logging.getLogger('sentry.errors')

        if dsn is None and os.environ.get('SENTRY_DSN'):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.debug(msg)
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options werent sent?
            urlparts = urlparse(dsn)
            msg = "Configuring Raven for host: %s://%s:%s" % (urlparts.scheme,
                    urlparts.netloc, urlparts.path)
            self.logger.debug(msg)
            dsn_config = raven.load(dsn, transport_registry=self._registry)
            servers = dsn_config['SENTRY_SERVERS']
            project = dsn_config['SENTRY_PROJECT']
            public_key = dsn_config['SENTRY_PUBLIC_KEY']
            secret_key = dsn_config['SENTRY_SECRET_KEY']
        else:
            servers = o.get('servers')
            project = o.get('project')
            public_key = o.get('public_key')
            secret_key = o.get('secret_key')

        self.servers = servers
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT

        self.include_paths = set(o.get('include_paths') or [])
        self.exclude_paths = set(o.get('exclude_paths') or [])
        self.name = unicode(o.get('name') or defaults.NAME)
        self.auto_log_stacks = bool(o.get('auto_log_stacks') or
                defaults.AUTO_LOG_STACKS)
        self.string_max_length = int(o.get('string_max_length') or
                defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(o.get('list_max_length') or defaults.MAX_LENGTH_LIST)
        self.site = o.get('site', defaults.SITE)
        self.processors = o.get('processors')
        if self.processors is None:
            self.processors = defaults.PROCESSORS

        context = o.get('context')
        if context is None:
            context = {'sys.argv': sys.argv[:]}
        self.extra = context

        self.module_cache = ModuleProxyCache()

        # servers may be set to a NoneType (for Django)
        if not self.is_enabled():
            self.logger.info('Raven is not configured (disabled). Please see documentation for more information.')
Example #5
0
def configure_heroku(app):
    import os
    import traceback
    if 'SENTRY_DSN' in os.environ:
        try:
            import raven
            from raven.contrib.flask import Sentry
            raven.load(os.environ['SENTRY_DSN'], app.config)
            sentry = Sentry(app)
            return sentry
        except Exception, e:
            print "Unexpected error:", e
            traceback.print_exc()

        if 'MEMCACHE_SERVERS' in os.environ:
            mc = dict(servers=[os.environ.get('MEMCACHE_SERVERS')],
                      username=os.environ.get('MEMCACHE_USERNAME'),
                      password=os.environ.get('MEMCACHE_PASSWORD'),
                      binary=True)
Example #6
0
    def __init__(self, servers=None, include_paths=None, exclude_paths=None, timeout=None,
                 name=None, auto_log_stacks=None, key=None, string_max_length=None,
                 list_max_length=None, site=None, public_key=None, secret_key=None,
                 processors=None, project=None, dsn=None, **kwargs):
        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger('%s.%s' % (cls.__module__, cls.__name__))
        self.error_logger = logging.getLogger('sentry.errors')

        if isinstance(servers, basestring):
            # must be a DSN:
            if dsn:
                raise ValueError("You seem to be incorrectly instantiating the raven Client class.")
            dsn = servers
            servers = None

        if dsn is None and os.environ.get('SENTRY_DSN'):
            self.logger.info("Configuring Raven from environment variable 'SENTRY_DSN'")
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options werent sent?
            urlparts = urlparse(dsn)
            self.logger.info("Configuring Raven for host: %s://%s:%s", urlparts.scheme, urlparts.netloc, urlparts.path)
            options = raven.load(dsn)
            servers = options['SENTRY_SERVERS']
            project = options['SENTRY_PROJECT']
            public_key = options['SENTRY_PUBLIC_KEY']
            secret_key = options['SENTRY_SECRET_KEY']

        # servers may be set to a NoneType (for Django)
        if servers and not (key or (secret_key and public_key)):
            raise TypeError('Missing configuration for client. Please see documentation.')

        self.servers = servers
        self.include_paths = set(include_paths or defaults.INCLUDE_PATHS)
        self.exclude_paths = set(exclude_paths or defaults.EXCLUDE_PATHS)
        self.timeout = int(timeout or defaults.TIMEOUT)
        self.name = unicode(name or defaults.NAME)
        self.auto_log_stacks = bool(auto_log_stacks or defaults.AUTO_LOG_STACKS)
        self.key = str(key or defaults.KEY)
        self.string_max_length = int(string_max_length or defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(list_max_length or defaults.MAX_LENGTH_LIST)
        if (site or defaults.SITE):
            self.site = unicode(site or defaults.SITE)
        else:
            self.site = None
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT

        self.processors = processors or defaults.PROCESSORS
        self.module_cache = ModuleProxyCache()
        self.udp_socket = None
Example #7
0
def configure_heroku(app):
    import os
    import traceback
    if 'SENTRY_DSN' in os.environ:
        try:
            import raven
            from raven.contrib.flask import Sentry
            raven.load(os.environ['SENTRY_DSN'], app.config)
            sentry = Sentry(app)
            return sentry
        except Exception, e:
            print "Unexpected error:", e
            traceback.print_exc()

        if 'MEMCACHE_SERVERS' in os.environ:
            mc = dict(
            servers=[os.environ.get('MEMCACHE_SERVERS')],
            username=os.environ.get('MEMCACHE_USERNAME'),
            password=os.environ.get('MEMCACHE_PASSWORD'),
            binary=True)
Example #8
0
    def __init__(self, servers=None, include_paths=None, exclude_paths=None, timeout=None,
                 name=None, auto_log_stacks=None, key=None, string_max_length=None,
                 list_max_length=None, site=None, public_key=None, secret_key=None,
                 processors=None, project=None, dsn=None, **kwargs):
        if isinstance(servers, basestring):
            # must be a DSN:
            if dsn:
                raise ValueError("You seem to be incorrectly instantiating the raven Client class.")
            dsn = servers
            servers = None

        if dsn is None and os.environ.get('SENTRY_DSN'):
            self.logger.info("Configuring Raven from environment variable 'SENTRY_DSN'")
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options werent sent?
            self.logger.info("Configuring Raven from DSN: %r", dsn)
            options = raven.load(dsn)
            servers = options['SENTRY_SERVERS']
            project = options['SENTRY_PROJECT']
            public_key = options['SENTRY_PUBLIC_KEY']
            secret_key = options['SENTRY_SECRET_KEY']

        # servers may be set to a NoneType (for Django)
        if servers and not (key or (secret_key and public_key)):
            raise TypeError('Missing configuration for client. Please see documentation.')

        self.servers = servers
        self.include_paths = set(include_paths or defaults.INCLUDE_PATHS)
        self.exclude_paths = set(exclude_paths or defaults.EXCLUDE_PATHS)
        self.timeout = int(timeout or defaults.TIMEOUT)
        self.name = unicode(name or defaults.NAME)
        self.auto_log_stacks = bool(auto_log_stacks or defaults.AUTO_LOG_STACKS)
        self.key = str(key or defaults.KEY)
        self.string_max_length = int(string_max_length or defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(list_max_length or defaults.MAX_LENGTH_LIST)
        if (site or defaults.SITE):
            self.site = unicode(site or defaults.SITE)
        else:
            self.site = None
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = int(project or defaults.PROJECT)

        self.processors = processors or defaults.PROCESSORS
        self.logger = logging.getLogger(__name__)
        self.module_cache = ModuleProxyCache()
        self.udp_socket = None
Example #9
0
    def set_dsn(self, dsn=None, **options):
        o = options

        if dsn is None and os.environ.get('SENTRY_DSN'):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.debug(msg)
            dsn = os.environ['SENTRY_DSN']

        try:
            servers, public_key, secret_key, project, transport_options = self.dsns[
                dsn]
        except KeyError:
            if dsn:
                # TODO: should we validate other options weren't sent?
                urlparts = urlparse(dsn)
                self.logger.debug(
                    "Configuring Raven for host: %s://%s:%s" %
                    (urlparts.scheme, urlparts.netloc, urlparts.path))
                dsn_config = raven.load(dsn, transport_registry=self._registry)
                servers = dsn_config['SENTRY_SERVERS']
                project = dsn_config['SENTRY_PROJECT']
                public_key = dsn_config['SENTRY_PUBLIC_KEY']
                secret_key = dsn_config['SENTRY_SECRET_KEY']
                transport_options = dsn_config.get('SENTRY_TRANSPORT_OPTIONS',
                                                   {})
            else:
                if o.get('servers'):
                    warnings.warn(
                        'Manually configured connections are deprecated. Switch to a DSN.',
                        DeprecationWarning)
                servers = o.get('servers')
                project = o.get('project')
                public_key = o.get('public_key')
                secret_key = o.get('secret_key')
                transport_options = {}
            self.dsns[
                dsn] = servers, public_key, secret_key, project, transport_options

        self.servers = servers
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT
        self.transport_options = transport_options
Example #10
0
    def __init__(self, servers=None, include_paths=None, exclude_paths=None, timeout=None,
                 name=None, auto_log_stacks=None, key=None, string_max_length=None,
                 list_max_length=None, site=None, public_key=None, secret_key=None,
                 processors=None, project=None, dsn=None, **kwargs):
        if dsn is None and os.environ.get('SENTRY_DSN'):
            self.logger.info("Configuring Raven from environment variable 'SENTRY_DSN'")
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options werent sent?
            self.logger.info("Configuring Raven from DSN: %r", dsn)
            options = raven.load(dsn)
            servers = [options['SENTRY_SERVERS']]
            project = options['SENTRY_PROJECT']
            public_key = options['PUBLIC_KEY']
            secret_key = options['SECRET_KEY']

        # servers may be set to a NoneType (for Django)
        if servers and not (key or (secret_key and public_key)):
            raise TypeError('Missing configuration for client. Please see documentation.')

        self.servers = servers
        self.include_paths = set(include_paths or defaults.INCLUDE_PATHS)
        self.exclude_paths = set(exclude_paths or defaults.EXCLUDE_PATHS)
        self.timeout = int(timeout or defaults.TIMEOUT)
        self.name = unicode(name or defaults.NAME)
        self.auto_log_stacks = bool(auto_log_stacks or defaults.AUTO_LOG_STACKS)
        self.key = str(key or defaults.KEY)
        self.string_max_length = int(string_max_length or defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(list_max_length or defaults.MAX_LENGTH_LIST)
        if (site or defaults.SITE):
            self.site = unicode(site or defaults.SITE)
        else:
            self.site = None
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = int(project or defaults.PROJECT)

        self.processors = processors or defaults.PROCESSORS
        self.logger = logging.getLogger(__name__)
        self.module_cache = ModuleProxyCache()
        self.udp_socket = None
Example #11
0
    def set_dsn(self, dsn=None, **options):
        o = options

        if dsn is None and os.environ.get('SENTRY_DSN'):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.debug(msg)
            dsn = os.environ['SENTRY_DSN']

        try:
            servers, public_key, secret_key, project, transport_options = self.dsns[dsn]
        except KeyError:
            if dsn:
                # TODO: should we validate other options weren't sent?
                urlparts = urlparse(dsn)
                self.logger.debug(
                    "Configuring Raven for host: %s://%s:%s" % (urlparts.scheme,
                    urlparts.netloc, urlparts.path))
                dsn_config = raven.load(dsn, transport_registry=self._registry)
                servers = dsn_config['SENTRY_SERVERS']
                project = dsn_config['SENTRY_PROJECT']
                public_key = dsn_config['SENTRY_PUBLIC_KEY']
                secret_key = dsn_config['SENTRY_SECRET_KEY']
                transport_options = dsn_config.get('SENTRY_TRANSPORT_OPTIONS', {})
            else:
                if o.get('servers'):
                    warnings.warn('Manually configured connections are deprecated. Switch to a DSN.', DeprecationWarning)
                servers = o.get('servers')
                project = o.get('project')
                public_key = o.get('public_key')
                secret_key = o.get('secret_key')
                transport_options = {}
            self.dsns[dsn] = servers, public_key, secret_key, project, transport_options

        self.servers = servers
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT
        self.transport_options = transport_options
Example #12
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:
            dsn_config = raven.load(dsn)
            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!r}, 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)

    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
        )
    def __init__(self,
                 servers=None,
                 include_paths=None,
                 exclude_paths=None,
                 timeout=None,
                 name=None,
                 auto_log_stacks=None,
                 key=None,
                 string_max_length=None,
                 list_max_length=None,
                 site=None,
                 public_key=None,
                 secret_key=None,
                 processors=None,
                 project=None,
                 dsn=None,
                 **kwargs):
        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger('%s.%s' %
                                        (cls.__module__, cls.__name__))
        self.error_logger = logging.getLogger('sentry.errors')

        if isinstance(servers, basestring):
            # must be a DSN:
            if dsn:
                # TODO: this should indicate what the caller can do to correct
                # the constructor
                msg = "You seem to be incorrectly instantiating the " + \
                      "raven Client class"
                raise ValueError(msg)
            dsn = servers
            servers = None

        if dsn is None and os.environ.get('SENTRY_DSN'):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.info(msg)
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options werent sent?
            urlparts = urlparse(dsn)
            msg = "Configuring Raven for host: %s://%s:%s" % (
                urlparts.scheme, urlparts.netloc, urlparts.path)
            self.logger.info(msg)
            options = raven.load(dsn, transport_registry=self._registry)
            servers = options['SENTRY_SERVERS']
            project = options['SENTRY_PROJECT']
            public_key = options['SENTRY_PUBLIC_KEY']
            secret_key = options['SENTRY_SECRET_KEY']

        # servers may be set to a NoneType (for Django)
        if servers and not (key or (secret_key and public_key)):
            msg = 'Missing configuration for client. Please see documentation.'
            raise TypeError(msg)

        self.servers = servers
        self.include_paths = set(include_paths or defaults.INCLUDE_PATHS)
        self.exclude_paths = set(exclude_paths or defaults.EXCLUDE_PATHS)
        self.timeout = int(timeout or defaults.TIMEOUT)
        self.name = unicode(name or defaults.NAME)
        self.auto_log_stacks = bool(auto_log_stacks
                                    or defaults.AUTO_LOG_STACKS)
        self.key = str(key or defaults.KEY)
        self.string_max_length = int(string_max_length
                                     or defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(list_max_length or defaults.MAX_LENGTH_LIST)
        if (site or defaults.SITE):
            self.site = unicode(site or defaults.SITE)
        else:
            self.site = None
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT

        self.processors = processors or defaults.PROCESSORS
        self.module_cache = ModuleProxyCache()
Example #14
0
    def __init__(self, dsn=None, raise_send_errors=False, **options):
        global Raven

        o = options

        self.configure_logging()

        self.raise_send_errors = raise_send_errors

        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger(
            '%s.%s' % (cls.__module__, cls.__name__))
        self.error_logger = logging.getLogger('sentry.errors')

        if dsn is None and os.environ.get('SENTRY_DSN'):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.debug(msg)
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options weren't sent?
            urlparts = urlparse(dsn)
            self.logger.debug(
                "Configuring Raven for host: %s://%s:%s" % (urlparts.scheme,
                urlparts.netloc, urlparts.path))
            dsn_config = raven.load(dsn, transport_registry=self._registry)
            servers = dsn_config['SENTRY_SERVERS']
            project = dsn_config['SENTRY_PROJECT']
            public_key = dsn_config['SENTRY_PUBLIC_KEY']
            secret_key = dsn_config['SENTRY_SECRET_KEY']
            transport_options = dsn_config.get('SENTRY_TRANSPORT_OPTIONS', {})
        else:
            if o.get('servers'):
                warnings.warn('Manually configured connections are deprecated. Switch to a DSN.', DeprecationWarning)
            servers = o.get('servers')
            project = o.get('project')
            public_key = o.get('public_key')
            secret_key = o.get('secret_key')
            transport_options = {}

        self.servers = servers
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT
        self.transport_options = transport_options

        self.include_paths = set(o.get('include_paths') or [])
        self.exclude_paths = set(o.get('exclude_paths') or [])
        self.name = six.text_type(o.get('name') or defaults.NAME)
        self.auto_log_stacks = bool(
            o.get('auto_log_stacks') or defaults.AUTO_LOG_STACKS)
        self.capture_locals = bool(
            o.get('capture_locals', defaults.CAPTURE_LOCALS))
        self.string_max_length = int(
            o.get('string_max_length') or defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(
            o.get('list_max_length') or defaults.MAX_LENGTH_LIST)
        self.site = o.get('site', defaults.SITE)
        self.include_versions = o.get('include_versions', True)
        self.processors = o.get('processors')
        if self.processors is None:
            self.processors = defaults.PROCESSORS

        context = o.get('context')
        if context is None:
            context = {'sys.argv': sys.argv[:]}
        self.extra = context
        self.tags = o.get('tags') or {}

        self.module_cache = ModuleProxyCache()

        # servers may be set to a NoneType (for Django)
        if not self.is_enabled():
            self.logger.info(
                'Raven is not configured (logging is disabled). Please see the'
                ' documentation for more information.')

        if Raven is None:
            Raven = self

        self._context = Context()
Example #15
0
    def __init__(self, servers=None, include_paths=None, exclude_paths=None,
            name=None, auto_log_stacks=None, key=None,
            string_max_length=None, list_max_length=None, site=None,
            public_key=None, secret_key=None, processors=None, project=None,
            dsn=None, **kwargs):
        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger('%s.%s' % (cls.__module__,
            cls.__name__))
        self.error_logger = logging.getLogger('sentry.errors')

        if isinstance(servers, basestring):
            # must be a DSN:
            if dsn:
                # TODO: this should indicate what the caller can do to correct
                # the constructor
                msg = "You seem to be incorrectly instantiating the " + \
                      "raven Client class"
                raise ValueError(msg)
            dsn = servers
            servers = None

        if dsn is None and os.environ.get('SENTRY_DSN'):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.info(msg)
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options werent sent?
            urlparts = urlparse(dsn)
            msg = "Configuring Raven for host: %s://%s:%s" % (
                urlparts.scheme, urlparts.netloc, urlparts.path)
            self.logger.info(msg)
            options = raven.load(dsn, transport_registry=self._registry)
            servers = options['SENTRY_SERVERS']
            project = options['SENTRY_PROJECT']
            public_key = options['SENTRY_PUBLIC_KEY']
            secret_key = options['SENTRY_SECRET_KEY']

        # servers may be set to a NoneType (for Django)
        if servers and not (key or (secret_key and public_key)):
            self.logger.info('Raven is not configured (disabled). Please see documentation for more information.')

        if kwargs.get('timeout') is not None:
            warnings.warn('The ``timeout`` option no longer does anything. Pass the option to your transport instead.')

        self.servers = servers
        self.include_paths = set(include_paths or defaults.INCLUDE_PATHS)
        self.exclude_paths = set(exclude_paths or defaults.EXCLUDE_PATHS)
        self.name = unicode(name or defaults.NAME)
        self.auto_log_stacks = bool(auto_log_stacks or
                defaults.AUTO_LOG_STACKS)
        self.key = str(key or defaults.KEY)
        self.string_max_length = int(string_max_length or
                defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(list_max_length or defaults.MAX_LENGTH_LIST)
        if (site or defaults.SITE):
            self.site = unicode(site or defaults.SITE)
        else:
            self.site = None
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT

        self.processors = processors or defaults.PROCESSORS
        self.module_cache = ModuleProxyCache()
Example #16
0
        'gmail.com', 'hotmail.com', 'live.com', 'msn.com', 'yahoo.com',
        'googlemail.com', 'facebookmail.com'
    ]
    MAIL_SERVER = 'smtp.sendgrid.net'
    MAIL_PORT = 25
    MAIL_USERNAME = os.environ.get('SENDGRID_USERNAME')
    MAIL_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
    MAIL_USE_TLS = True
    MAIL_DOMAIN = os.environ.get('SENDGRID_DOMAIN', 'codebox.cc')
    DEFAULT_MAIL_SENDER = '*****@*****.**'


if os.environ.has_key('SENTRY_DSN'):
    try:
        import raven
        raven.load(os.environ['SENTRY_DSN'], Config.__dict__)
    except:
        print "Unexpected error:", sys.exc_info()

if os.environ.has_key('REDISTOGO_URL'):
    # 'redis://*****:*****@my.host:6789'
    urlparse.uses_netloc.append('redis')
    url = urlparse.urlparse(os.environ['REDISTOGO_URL'])
    Config.REDIS_PASSWORD = url.password
    Config.REDIS_HOST = url.hostname
    Config.REDIS_PORT = url.port


class TestingConfig(Config):
    REDIS_DB = 9
    TESTING = True
Example #17
0
    SECRET_KEY = os.environ.get('SECRET_KEY', '\x89\x1d\xec\x8eJ\xda=C`\xf3<X\x81\xff\x1e\r{+\x1b\xe1\xd1@ku')
    REDIS_DB = 0
    JANRAIN_API_KEY = os.environ.get('JANRAIN_API_KEY')
    DOMAIN_BLACKLIST = ['gmail.com', 'hotmail.com', 'live.com', 'msn.com', 'yahoo.com', 'googlemail.com', 'facebookmail.com']
    MAIL_SERVER = 'smtp.sendgrid.net'
    MAIL_PORT = 25
    MAIL_USERNAME = os.environ.get('SENDGRID_USERNAME')
    MAIL_PASSWORD = os.environ.get('SENDGRID_PASSWORD')
    MAIL_USE_TLS = True
    MAIL_DOMAIN = os.environ.get('SENDGRID_DOMAIN', 'codebox.cc')
    DEFAULT_MAIL_SENDER = '*****@*****.**'

if os.environ.has_key('SENTRY_DSN'):
    try:
        import raven
        raven.load(os.environ['SENTRY_DSN'], Config.__dict__)
    except:
        print "Unexpected error:", sys.exc_info()

if os.environ.has_key('REDISTOGO_URL'):
    # 'redis://*****:*****@my.host:6789' 
    urlparse.uses_netloc.append('redis')
    url = urlparse.urlparse(os.environ['REDISTOGO_URL'])
    Config.REDIS_PASSWORD = url.password
    Config.REDIS_HOST = url.hostname
    Config.REDIS_PORT = url.port

class TestingConfig(Config):
    REDIS_DB = 9
    TESTING = True
Example #18
0
    def __init__(self, dsn=None, **options):
        global Raven

        o = options

        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger('%s.%s' % (cls.__module__,
            cls.__name__))
        self.error_logger = logging.getLogger('sentry.errors')

        if dsn is None and os.environ.get('SENTRY_DSN'):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.debug(msg)
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options werent sent?
            urlparts = urlparse(dsn)
            msg = "Configuring Raven for host: %s://%s:%s" % (urlparts.scheme,
                    urlparts.netloc, urlparts.path)
            self.logger.debug(msg)
            dsn_config = raven.load(dsn, transport_registry=self._registry)
            servers = dsn_config['SENTRY_SERVERS']
            project = dsn_config['SENTRY_PROJECT']
            public_key = dsn_config['SENTRY_PUBLIC_KEY']
            secret_key = dsn_config['SENTRY_SECRET_KEY']
        else:
            servers = o.get('servers')
            project = o.get('project')
            public_key = o.get('public_key')
            secret_key = o.get('secret_key')

        self.servers = servers
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT

        self.include_paths = set(o.get('include_paths') or [])
        self.exclude_paths = set(o.get('exclude_paths') or [])
        self.name = unicode(o.get('name') or defaults.NAME)
        self.auto_log_stacks = bool(o.get('auto_log_stacks') or
                defaults.AUTO_LOG_STACKS)
        self.string_max_length = int(o.get('string_max_length') or
                defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(o.get('list_max_length') or defaults.MAX_LENGTH_LIST)
        self.site = o.get('site', defaults.SITE)
        self.include_versions = o.get('include_versions', True)
        self.processors = o.get('processors')
        if self.processors is None:
            self.processors = defaults.PROCESSORS

        context = o.get('context')
        if context is None:
            context = {'sys.argv': sys.argv[:]}
        self.extra = context

        self.module_cache = ModuleProxyCache()

        # servers may be set to a NoneType (for Django)
        if not self.is_enabled():
            self.logger.info('Raven is not configured (disabled). Please see documentation for more information.')

        if Raven is None:
            Raven = self
Example #19
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:
            dsn_config = raven.load(dsn)
            options.update({
                'project': dsn_config['SENTRY_PROJECT'],
                'servers': dsn_config['SENTRY_SERVERS'],
                'public_key': dsn_config['SENTRY_PUBLIC_KEY'],
                'private_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', 'private_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!r}, 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)

    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)
Example #20
0
    def __init__(self, dsn=None, **options):
        global Raven

        o = options

        self.configure_logging()

        # configure loggers first
        cls = self.__class__
        self.state = ClientState()
        self.logger = logging.getLogger(
            '%s.%s' % (cls.__module__, cls.__name__))
        self.error_logger = logging.getLogger('sentry.errors')

        if dsn is None and os.environ.get('SENTRY_DSN'):
            msg = "Configuring Raven from environment variable 'SENTRY_DSN'"
            self.logger.debug(msg)
            dsn = os.environ['SENTRY_DSN']

        if dsn:
            # TODO: should we validate other options werent sent?
            urlparts = urlparse(dsn)
            self.logger.debug(
                "Configuring Raven for host: %s://%s:%s" % (urlparts.scheme,
                urlparts.netloc, urlparts.path))
            dsn_config = raven.load(dsn, transport_registry=self._registry)
            servers = dsn_config['SENTRY_SERVERS']
            project = dsn_config['SENTRY_PROJECT']
            public_key = dsn_config['SENTRY_PUBLIC_KEY']
            secret_key = dsn_config['SENTRY_SECRET_KEY']
            transport_options = dsn_config.get('SENTRY_TRANSPORT_OPTIONS', {})
        else:
            if o.get('servers'):
                warnings.warn('Manually configured connections are deprecated. Switch to a DSN.', DeprecationWarning)
            servers = o.get('servers')
            project = o.get('project')
            public_key = o.get('public_key')
            secret_key = o.get('secret_key')
            transport_options = {}

        self.servers = servers
        self.public_key = public_key
        self.secret_key = secret_key
        self.project = project or defaults.PROJECT
        self.transport_options = transport_options

        self.include_paths = set(o.get('include_paths') or [])
        self.exclude_paths = set(o.get('exclude_paths') or [])
        self.name = six.text_type(o.get('name') or defaults.NAME)
        self.auto_log_stacks = bool(
            o.get('auto_log_stacks') or defaults.AUTO_LOG_STACKS)
        self.capture_locals = bool(
            o.get('capture_locals', defaults.CAPTURE_LOCALS))
        self.string_max_length = int(
            o.get('string_max_length') or defaults.MAX_LENGTH_STRING)
        self.list_max_length = int(
            o.get('list_max_length') or defaults.MAX_LENGTH_LIST)
        self.site = o.get('site', defaults.SITE)
        self.include_versions = o.get('include_versions', True)
        self.processors = o.get('processors')
        if self.processors is None:
            self.processors = defaults.PROCESSORS

        context = o.get('context')
        if context is None:
            context = {'sys.argv': sys.argv[:]}
        self.extra = context
        self.tags = o.get('tags') or {}

        self.module_cache = ModuleProxyCache()

        # servers may be set to a NoneType (for Django)
        if not self.is_enabled():
            self.logger.info(
                'Raven is not configured (logging is disabled). Please see the'
                ' documentation for more information.')

        if Raven is None:
            Raven = self

        self._context = Context()