Example #1
0
class AirbrakeLogObserver(object):
    def __init__(self, settings):
        if not settings.get('AIRBRAKE', False) or \
                settings['AIRBRAKE'].get('DISABLE', False):
            return

        self.enabled = True
        project_id = settings['AIRBRAKE'].get('PROJECT_ID', None)
        api_key = settings['AIRBRAKE'].get('API_KEY', None)
        host = settings['AIRBRAKE'].get('HOST', None)
        timeout = settings['AIRBRAKE'].get('TIMEOUT', None)
        environment = settings['AIRBRAKE'].get('ENVIRONMENT', None)
        self.ab = Airbrake(project_id,
                           api_key,
                           host,
                           timeout,
                           environment=environment,
                           send_uncaught_exc=False)

    def __call__(self, event):
        if not event["log_failure"] or not self.ab:
            return

        error = build_error(event["log_failure"].value,
                            message=event["log_failure"].getErrorMessage())
        notice = self.ab.build_notice(error)

        self.ab.notify(notice)
Example #2
0
class AirbrakeHandler(logging.Handler):

    """
    A handler class which ships logs to airbrake.io

    Requires one:
        * `project_id` AND `api_key`
        * an instance of airbrake.Airbrake
    """

    def __init__(self, airbrake=None, level=logging.ERROR, **kwargs):
        """Initialize the Airbrake handler with a default logging level.

        Default level of logs handled by this class are >= ERROR,
        which includes ERROR and CRITICAL. To change this behavior
        supply a different arguement for 'level'.

        All 'kwargs' will be passed to notifier.Airbrake to instantiate
        a notifier client.
        """

        logging.Handler.__init__(self, level=level)

        if isinstance(airbrake, Airbrake):
            self.airbrake = airbrake
        else:
            self.airbrake = Airbrake(**kwargs)

    def emit(self, record):
        """Log the record airbrake.io style.

        To prevent method calls which invoke this handler from using the
        global exception context in sys.exc_info(), exc_info must be passed
        as False.

        E.g. To prevent AirbrakeHandler from reading the global exception
        context, (which it may do to find a traceback and error type), make
        logger method calls like this:

            LOG.error("Bad math.", exc_info=False)

        Otherwise, provide exception context directly, though the following
        contrived example would be a strange way to use the handler:

            exc_info = sys.exc_info()
            ...
            LOG.error("Bad math.", exc_info=exc_info)
        """
        try:
            airbrakeerror = airbrake_error_from_logrecord(record)
            self.airbrake.log(**airbrakeerror)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
Example #3
0
class AirbrakeHandler(logging.Handler):
    """
    A handler class which ships logs to airbrake.io

    Requires one:
        * `project_id` AND `api_key`
        * an instance of airbrake.Airbrake
    """
    def __init__(self,
                 airbrake=None,
                 level=logging.ERROR,
                 project_id=None,
                 api_key=None,
                 environment=None):
        """Initialize the Airbrake handler with a default logging level.

        Default level of logs handled by this class are >= ERROR,
        which includes ERROR and CRITICAL. To change this behavior
        supply a different argument for 'level'.
        """

        logging.Handler.__init__(self, level=level)

        if isinstance(airbrake, Airbrake):
            self.airbrake = airbrake
        else:
            self.airbrake = Airbrake(project_id, api_key, environment)

    def emit(self, record):
        """Log the record airbrake.io style.

        To prevent method calls which invoke this handler from using the
        global exception context in sys.exc_info(), exc_info must be passed
        as False.

        E.g. To prevent AirbrakeHandler from reading the global exception
        context, (which it may do to find a traceback and error type), make
        logger method calls like this:

            LOG.error("Bad math.", exc_info=False)

        Otherwise, provide exception context directly, though the following
        contrived example would be a strange way to use the handler:

            exc_info = sys.exc_info()
            ...
            LOG.error("Bad math.", exc_info=exc_info)
        """
        try:
            airbrakeerror = airbrake_error_from_logrecord(record)
            self.airbrake.log(**airbrakeerror)
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
 def init_app(self, app=None):
     project_id = app.config.get('AIRBRAKE_PROJECT_ID', None)
     api_key = app.config.get('AIRBRAKE_API_KEY', None)
     host = app.config.get('AIRBRAKE_HOST', None)
     environment = app.config.get('AIRBRAKE_ENVIRONMENT', None)
     if project_id and api_key:
         self.ab = Airbrake(project_id,
                            api_key,
                            host,
                            environment=environment)
         got_request_exception.connect(self.process_exception, sender=app)
Example #5
0
    def __init__(self, project_id=None, api_key=None, environment="dev",
                 notifier=None, use_ssl=True, airbrake=None):

        logging.Handler.__init__(self)

        if isinstance(airbrake, Airbrake):
            airbrake.auto_notify = True
            self.airbrake = airbrake
        else:
            self.airbrake = Airbrake(project_id=project_id, api_key=api_key,
                                     environment=environment, notifier=notifier,
                                     use_ssl=use_ssl, auto_notify=True)
 def __init__(self, *args, **kwargs):
     super(AirbrakeNotifierMiddleware, self).__init__(*args, **kwargs)
     self.enabled = False
     if hasattr(settings, 'AIRBRAKE') \
             and not settings.AIRBRAKE.get('DISABLE', False):
         self.enabled = True
         project_id = settings.AIRBRAKE.get('PROJECT_ID', None)
         api_key = settings.AIRBRAKE.get('API_KEY', None)
         host = settings.AIRBRAKE.get('HOST', None)
         timeout = settings.AIRBRAKE.get('TIMEOUT', None)
         environment = settings.AIRBRAKE.get('ENVIRONMENT', None)
         self.ab = Airbrake(project_id, api_key, host, timeout,
                            environment=environment)
Example #7
0
    def __init__(self, settings):
        if not settings.get('AIRBRAKE', False) or \
                settings['AIRBRAKE'].get('DISABLE', False):
            return

        self.enabled = True
        project_id = settings['AIRBRAKE'].get('PROJECT_ID', None)
        api_key = settings['AIRBRAKE'].get('API_KEY', None)
        host = settings['AIRBRAKE'].get('HOST', None)
        timeout = settings['AIRBRAKE'].get('TIMEOUT', None)
        environment = settings['AIRBRAKE'].get('ENVIRONMENT', None)
        self.ab = Airbrake(project_id,
                           api_key,
                           host,
                           timeout,
                           environment=environment,
                           send_uncaught_exc=False)
Example #8
0
    def __init__(self,
                 airbrake=None,
                 level=logging.ERROR,
                 project_id=None,
                 api_key=None,
                 environment=None):
        """Initialize the Airbrake handler with a default logging level.

        Default level of logs handled by this class are >= ERROR,
        which includes ERROR and CRITICAL. To change this behavior
        supply a different argument for 'level'.
        """

        logging.Handler.__init__(self, level=level)

        if isinstance(airbrake, Airbrake):
            self.airbrake = airbrake
        else:
            self.airbrake = Airbrake(project_id, api_key, environment)
Example #9
0
class AirbrakeHandler(logging.Handler):
    """
    A handler class which ships logs to airbrake.io

    Requires one:
        * `project_id` AND `api_key`
        * an instance of airbrake.Airbrake
    """
    def __init__(self, project_id=None, api_key=None, environment="dev",
                 notifier=None, use_ssl=True, airbrake=None):

        logging.Handler.__init__(self)

        if isinstance(airbrake, Airbrake):
            airbrake.auto_notify = True
            self.airbrake = airbrake
        else:
            self.airbrake = Airbrake(project_id=project_id, api_key=api_key,
                                     environment=environment, notifier=notifier,
                                     use_ssl=use_ssl, auto_notify=True)

    def emit(self, record):
        try:
            # exception
            exc = None
            if record.exc_info:
                exc = record.exc_info[1]
            if not exc:
                exc = sys.exc_info()[1]
            if exc:
                self.airbrake.log(exc=exc)
                return

            # record
            record = record.getMessage()
            if record:
                self.airbrake.log(record=record)

        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
class AirbrakeNotifierMiddleware(MiddlewareMixin):
    """Send an error to airbrake for all exceptions"""

    def __init__(self, *args, **kwargs):
        super(AirbrakeNotifierMiddleware, self).__init__(*args, **kwargs)
        self.enabled = False
        if hasattr(settings, 'AIRBRAKE') \
                and not settings.AIRBRAKE.get('DISABLE', False):
            self.enabled = True
            project_id = settings.AIRBRAKE.get('PROJECT_ID', None)
            api_key = settings.AIRBRAKE.get('API_KEY', None)
            host = settings.AIRBRAKE.get('HOST', None)
            timeout = settings.AIRBRAKE.get('TIMEOUT', None)
            environment = settings.AIRBRAKE.get('ENVIRONMENT', None)
            self.ab = Airbrake(project_id, api_key, host, timeout,
                               environment=environment)

    def process_exception(self, request, exception):
        if self.enabled:
            self.ab.notify(exception)
class AirbrakeApp(object):
    def __init__(self, app=None):
        self.app = app
        if app is not None:
            self.init_app(app)

    def init_app(self, app=None):
        project_id = app.config.get('AIRBRAKE_PROJECT_ID', None)
        api_key = app.config.get('AIRBRAKE_API_KEY', None)
        host = app.config.get('AIRBRAKE_HOST', None)
        environment = app.config.get('AIRBRAKE_ENVIRONMENT', None)
        if project_id and api_key:
            self.ab = Airbrake(project_id,
                               api_key,
                               host,
                               environment=environment)
            got_request_exception.connect(self.process_exception, sender=app)

    def process_exception(self, *args, **kwargs):
        if not self.ab:
            return
        self.ab.notify(kwargs["exception"])
Example #12
0
    def __init__(self, airbrake=None, level=logging.ERROR, project_id=None, api_key=None, environment=None):
        """Initialize the Airbrake handler with a default logging level.

        Default level of logs handled by this class are >= ERROR,
        which includes ERROR and CRITICAL. To change this behavior
        supply a different argument for 'level'.
        """

        logging.Handler.__init__(self, level=level)

        if isinstance(airbrake, Airbrake):
            self.airbrake = airbrake
        else:
            self.airbrake = Airbrake(project_id, api_key, environment)
Example #13
0
    def __init__(self, airbrake=None, level=logging.ERROR, **kwargs):
        """Initialize the Airbrake handler with a default logging level.

        Default level of logs handled by this class are >= ERROR,
        which includes ERROR and CRITICAL. To change this behavior
        supply a different arguement for 'level'.

        All 'kwargs' will be passed to notifier.Airbrake to instantiate
        a notifier client.
        """

        logging.Handler.__init__(self, level=level)

        if isinstance(airbrake, Airbrake):
            self.airbrake = airbrake
        else:
            self.airbrake = Airbrake(**kwargs)
Example #14
0
lm = LoginManager(app)
lm.init_app(app)
csrf = CsrfProtect()
csrf.init_app(app)

if config.PRODUCTION:
    log_file_handler = RotatingFileHandler(config.WEB_LOG, maxBytes=10000000)
    logging.getLogger().addHandler(log_file_handler)
    logging.getLogger('werkzeug').addHandler(log_file_handler)
    app.logger.addHandler(log_file_handler)

    airbrakelogger = logging.getLogger('airbrake')

    # Airbrake
    airbrake = Airbrake(
        project_id=config.AIRBRAKE_ID,
        api_key=config.AIRBRAKE_KEY
    )
    # ugly hack to make this work for our errbit
    airbrake._api_url = "{}/api/v3/projects/{}/notices".format(config.AIRBRAKE_BASE_URL, airbrake.project_id)

    airbrakelogger.addHandler(
        AirbrakeHandler(airbrake=airbrake)
    )
    app.logger.addHandler(
        AirbrakeHandler(airbrake=airbrake)
    )


app.before_request(lambda: Session.remove())

from battlebots.web import views  # NOQA
Example #15
0
    lambda text: jinja2.Markup(markdown.markdown(text)))
app.jinja_env.tests['not_equalto'] = lambda value, other: value != other

lm = LoginManager(app)
lm.init_app(app)
csrf = CsrfProtect()
csrf.init_app(app)

if config.PRODUCTION:
    log_file_handler = RotatingFileHandler(config.WEB_LOG, maxBytes=10000000)
    logging.getLogger().addHandler(log_file_handler)
    logging.getLogger('werkzeug').addHandler(log_file_handler)
    app.logger.addHandler(log_file_handler)

    airbrakelogger = logging.getLogger('airbrake')

    # Airbrake
    airbrake = Airbrake(project_id=config.AIRBRAKE_ID,
                        api_key=config.AIRBRAKE_KEY)
    # ugly hack to make this work for our errbit
    airbrake._api_url = "{}/api/v3/projects/{}/notices".format(
        config.AIRBRAKE_BASE_URL, airbrake.project_id)

    airbrakelogger.addHandler(AirbrakeHandler(airbrake=airbrake))
    app.logger.addHandler(AirbrakeHandler(airbrake=airbrake))

app.before_request(lambda: Session.remove())

from battlebots.web import views  # NOQA
from battlebots.web.views import bots  # NOQA
Example #16
0
def register_plugins(app: Flask) -> Manager:
    "Register all the plugins to Haldis"
    # pylint: disable=W0612
    # Register Airbrake and enable the logrotation
    if not app.debug:
        timedFileHandler = TimedRotatingFileHandler(
            app.config["LOGFILE"], when="midnight", backupCount=100
        )
        timedFileHandler.setLevel(logging.DEBUG)

        loglogger = logging.getLogger("werkzeug")
        loglogger.setLevel(logging.DEBUG)
        loglogger.addHandler(timedFileHandler)
        app.logger.addHandler(timedFileHandler)

        airbrakelogger = logging.getLogger("airbrake")

        # Airbrake
        airbrake = Airbrake(project_id=app.config["AIRBRAKE_ID"],
                            api_key=app.config["AIRBRAKE_KEY"])
        # ugly hack to make this work for out errbit
        airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format(  # pylint: disable=W0212
            airbrake.project_id
        )

        airbrakelogger.addHandler(AirbrakeHandler(airbrake=airbrake))
        app.logger.addHandler(AirbrakeHandler(airbrake=airbrake))

    # Initialize SQLAlchemy
    db.init_app(app)

    # Initialize Flask-Migrate
    migrate = Migrate(app, db)
    app_manager = Manager(app)
    app_manager.add_command("db", MigrateCommand)
    app_manager.add_command("runserver", Server(port=8000))

    # Add admin interface
    init_admin(app, db)

    # Init login manager
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.anonymous_user = AnonymouseUser
    init_login(app)

    # Add oauth
    zeus = init_oauth(app)
    app.zeus = zeus

    # Load the bootstrap local cdn
    Bootstrap(app)
    app.config["BOOTSTRAP_SERVE_LOCAL"] = True

    # use our own bootstrap theme
    app.extensions["bootstrap"]["cdns"]["bootstrap"] = StaticCDN()

    # Load the flask debug toolbar
    toolbar = DebugToolbarExtension(app)

    # Make cookies more secure
    app.config.update(
        SESSION_COOKIE_HTTPONLY=True,
        SESSION_COOKIE_SAMESITE='Lax',
    )

    if not app.debug:
        app.config.update(SESSION_COOKIE_SECURE=True)

    return app_manager
Example #17
0
Bootstrap(app)

# use our own bootstrap theme
app.extensions['bootstrap']['cdns']['bootstrap'] = StaticCDN()

db = SQLAlchemy(app)

toolbar = DebugToolbarExtension(app)

if not app.debug:
    timedFileHandler = TimedRotatingFileHandler(app.config['LOGFILE'],
                                                when='midnight',
                                                backupCount=100)
    timedFileHandler.setLevel(logging.DEBUG)

    loglogger = logging.getLogger('werkzeug')
    loglogger.setLevel(logging.DEBUG)
    loglogger.addHandler(timedFileHandler)
    app.logger.addHandler(timedFileHandler)

    airbrakelogger = logging.getLogger('airbrake')

    # Airbrake
    airbrake = Airbrake(project_id=app.config['AIRBRAKE_ID'],
                        api_key=app.config['AIRBRAKE_KEY'])
    # ugly hack to make this work for out errbit
    airbrake._api_url = "http://errbit.awesomepeople.tv/api/v3/projects/{}/notices".format(
        airbrake.project_id)

    airbrakelogger.addHandler(AirbrakeHandler(airbrake=airbrake))
    app.logger.addHandler(AirbrakeHandler(airbrake=airbrake))