def init_rollbar(): rollbar.init(cfg["rollbar"]["token"], cfg["rollbar"]["environment"], root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): rollbar.init(TOKEN, 'flasktest', root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=True) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def _connect_signals(): rs_counter = Counter("web_request_started", "HTTP requests received") request_started.connect(lambda s, *a, **e: rs_counter.inc(), weak=False) rf_counter = Counter("web_request_finished", "HTTP requests successfully handled") request_finished.connect(lambda s, *a, **e: rf_counter.inc(), weak=False) re_counter = Counter("web_request_exception", "Failed HTTP requests") got_request_exception.connect(lambda s, *a, **e: re_counter.inc(), weak=False)
def set_up_rollbar(): class CustomRequest(Request): @property def rollbar_person(self): if g.user: user = g.user return { 'id': user.id, 'username': user.get_username(), 'email': user.email } rollbar.init( app.config['ROLLBAR_ACCESS_TOKEN'], app.config['ROLLBAR_ENVIRONMENT'], root=app.config['ROLLBAR_ROOT'], handler='blocking', allow_logging_basic_config=False, timeout=5 ) got_request_exception.connect(report_exception, app) app.request_class = CustomRequest
def main(args=None): defaultdb = get_default_dbconfig() import argparse parser = argparse.ArgumentParser() parser.add_argument("--db", default=defaultdb) parser.add_argument("-d", "--debug", action="store_true", default=False) parser.add_argument("--pdb", action="store_true", default=False) parser.add_argument("-H", "--host", default=os.environ.get("CURIELOGSERVER_HOST", "127.0.0.1")) parser.add_argument("-p", "--port", type=int, default=int( os.environ.get("CURIELOGSERVER_PORT", "5000"))) options = parser.parse_args(args) app.config['postgreSQL_pool'] = psycopg2.pool.ThreadedConnectionPool( 1, 20, options.db) if options.pdb: got_request_exception.connect(drop_into_pdb) app.run(debug=options.debug, host=options.host, port=options.port)
def _conf_logging_errors(app): def log_exception(sender, exception, **extra): sender.logger.error(str(exception)) from flask import got_request_exception got_request_exception.connect(log_exception, app)
def create_api(app): api = Api(app, catch_all_404s=True, errors=errors) api.representations['application/xml'] = output_xml got_request_exception.connect(log_exception, app) api.add_resource(Recipes, '/recipes', endpoint='recipes') api.add_resource(Recipes, '/recipes/<int:recipe_id>', endpoint='recipe')
def create_app(): """create flask-sports app""" app = Flask(__name__) app.secret_key = '4A8BF09E6732FDC682988A8SYZ666AB7CF53176D08631E' config = load_config(CONFIGS['2']) # 选择环境 # load logger setup_log(config) # load config app.config.from_object(config) # register blueprint # app.register_blueprint(test) celery_app.init_app(app) # 注册celery应用 redis_app.init_app(app) # 注册redis应用 sms.init_app(app) # 注册阿里云短信服务 signal.init_app(app) # 注册发送验证码信号 db.init_app(app) # 注册mongodb实例 oss.init_app(app) # 注册OSS服务 with app.app_context(): # 手动推送上下文 # get_user_model(app) # 注册用户模型表 pass got_request_exception.connect(log_exception, app) # 记录请求的异常 return app
def setup_signals(cls, app): app.before_first_request(before_first_request_handler) request_started.connect(request_started_handler, app) app.before_request(before_request_handler) got_request_exception.connect(got_request_exception_handler, app) request_finished.connect(request_finished_handler, app) app.teardown_request(teardown_request_handler)
def init_app(self, app): """ Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks. """ # If no version path was provided in the init of the Dockerflow # class we'll use the parent directory of the app root path. if self.version_path is None: self.version_path = os.path.dirname(app.root_path) for view in ( ('/__version__', 'version', self._version_view), ('/__heartbeat__', 'heartbeat', self._heartbeat_view), ('/__lbheartbeat__', 'lbheartbeat', self._lbheartbeat_view), ): self._blueprint.add_url_rule(*view) self._blueprint.before_app_request(self._before_request) self._blueprint.after_app_request(self._after_request) self._blueprint.app_errorhandler(HeartbeatFailure)( self._heartbeat_exception_handler) app.register_blueprint(self._blueprint) got_request_exception.connect(self._got_request_exception, sender=app) if not hasattr(app, 'extensions'): # pragma: nocover app.extensions = {} app.extensions['dockerflow'] = self
def create_app(name=__name__, config=None, skip_defaults=False): """ app factory If config is not passed, env is inspected for 'APP_CONFIG'. If not present, the base defaults from settings.BaseConfig apply (local server, etc) """ app = Flask(name) if not config: log.warning("Using default config") config = Config() app.config.from_object(config) blueprint = Blueprint('api', __name__, url_prefix='/api') api.add_namespace(healthcheck_namespace) api.add_namespace(activities_namespace) api.add_namespace(blobs_namespace) api.add_namespace(items_namespace) init_app(app) api.init_app(blueprint) blueprint.before_request(setup_db) app.register_blueprint(blueprint) got_request_exception.connect(drop_into_pdb) try: if '-echo' in str(subprocess.check_output("stty", shell=True)): log.debug("Re-enabling echo w/ stty") subprocess.check_call("stty echo", shell=True) except subprocess.CalledProcessError: pass return app
def init_app(app): if "pybrake" in app.extensions: raise ValueError("pybrake is already injected") if "PYBRAKE" not in app.config: raise ValueError("app.config['PYBRAKE'] is not defined") notifier = Notifier(**app.config["PYBRAKE"]) apm_disabled = notifier._apm_disabled notifier.add_filter(request_filter) app.extensions["pybrake"] = notifier got_request_exception.connect(_handle_exception, sender=app) if not apm_disabled: before_render_template.connect(_before_render_template, sender=app) template_rendered.connect(_template_rendered, sender=app) app.before_request(_before_request(notifier)) app.after_request(_after_request(notifier)) if _sqla_available: _sqla_instrument(app) return app
def configure_app(app): log_msg_format = app.config['API_LOG_MSG_FORMAT'] log_date_format = app.config['API_LOG_DATE_FORMAT'] sqla_logger = logging.getLogger('sqlalchemy') pool_logger = logging.getLogger('sqlalchemy.pool') # Set the message formatter for the default log handler current_handlers = app.logger.handlers default_handler = current_handlers[0] if current_handlers else None if default_handler: # A newline is included before the log message to visually separate them better default_handler.setFormatter(logging.Formatter("\n" + log_msg_format, datefmt=log_date_format)) pool_logger.addHandler(default_handler) # Setup the log handlers if not testing if not app.testing: # Rotating file handler file_handler = handlers.RotatingFileHandler( app.config['API_LOG_FILE_PATH'], mode='a', maxBytes=1 * 1024 * 1024, backupCount=10) file_handler.setLevel(logging.INFO) file_handler.setFormatter(logging.Formatter(log_msg_format, datefmt=log_date_format)) # Add handlers to loggers loggers = [app.logger, sqla_logger] for logger in loggers: logger.addHandler(file_handler) # Set the log level if 'LOG_LEVEL' in app.config: # Log at the level specified in the app config app.logger.setLevel(app.config['LOG_LEVEL']) else: # Log at the DEBUG level when testing/debugging, otherwise log INFO and above if app.debug or app.testing: app.logger.setLevel(logging.DEBUG) else: app.logger.setLevel(logging.INFO) # Configure connection pool debug logging if app.config.get('POOL_DEBUG_LOGGING'): pool_logger.setLevel(logging.DEBUG) # Include this extra information in all log messages (lambda functions get executed at log time) if app.config.get('API_LOG_VERBOSE_DEV_MESSAGES', False): extra_info = lu.ExtraInfo() extra_info['ip'] = lambda: has_request_context() and ah.get_remote_addr() or None extra_info['uid'] = lambda: str(g.user.id).upper() if hasattr(g, 'user') and g.user.id else None extra_info['ua'] = lambda: has_request_context() and ah.get_user_agent_summary() or None extra_info['url'] = lambda: has_request_context() and request.url or None app._logger = lu.ExtraInfoLogger(app.logger, extra_info) # Connect the exception logging functions to the `got_request_exception` signal got_request_exception.connect(lu.log_api_exception, app) got_request_exception.connect(lu.log_api_exception_to_browser_console, app)
def setUp(self): self.exception_msg = "There is a nasty gremlin in this system" self.exception = RequestException(self.exception_msg) self.test_app = AirbrakeTestApp(self.exception) self.client = self.test_app.app.test_client() got_request_exception.connect( self.test_app.ab.process_exception, sender=self.test_app.app )
def init_rollbar(): rollbar.init( ROLLBAR_KEY, ROLLBAR_APP, root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False) got_request_exception.connect(rollbar.contrib.flask.report_exception, app) rollbar.report_message('App booted', 'warning')
def init_rollbar(): """init rollbar module""" rollbar.init('6b773c84e86041798a513ba8ef73bb74', 'petchat-flask', root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): rollbar.init( cfg["rollbar"]["token"], cfg["rollbar"]["environment"], root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False ) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(app): from flask import got_request_exception rollbar.init(TOKEN, 'flasktest', root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=True, capture_email=True, capture_username=True) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def full_dispatch_request_with_instana(wrapped, instance, argv, kwargs): got_request_exception.connect(log_exception_with_signoz, instance) request_started.connect(request_started_with_signoz, instance) request_finished.connect(request_finished_with_signoz, instance) instance.teardown_request(teardown_request_with_signoz) return wrapped(*argv, **kwargs)
def _conf_logging_errors(app): def log_exception(sender, exception, **extra): print("log_exception.exception : ", exception) print("log_exception;extra : ", extra) sender.logger.error(str(exception)) from flask import got_request_exception got_request_exception.connect(log_exception, app)
def full_dispatch_request_with_instana(wrapped, instance, argv, kwargs): if not hasattr(instance, '_stan_wuz_here'): logger.debug("Applying flask before/after instrumentation funcs") setattr(instance, "_stan_wuz_here", True) got_request_exception.connect(log_exception_with_instana, instance) request_started.connect(request_started_with_instana, instance) request_finished.connect(request_finished_with_instana, instance) return wrapped(*argv, **kwargs)
def setup_rollbar(): if ROLLBAR_ACCESS_TOKEN: rollbar.init(ROLLBAR_ACCESS_TOKEN, BRICKY_ENV, root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): """init rollbar module""" if app.config['ENV'] in ('production',) and app.config['ROLLBAR_API']: rollbar.init(access_token=app.config['ROLLBAR_API'], environment=app.config['ENV'], root=app.config['APP_DIR'], allow_logging_basic_config=False) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): """init rollbar module""" rollbar.init( 'c6393fb20bf5493bbd0cc0d667ccc863', 'local', root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(self, app): rollbar.init( app.config['ROLLBAR_TOKEN'], app.config['FLASK_ENV'], root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False) got_request_exception.connect( rollbar.contrib.flask.report_exception, app)
def register_rollbar(app): rollbar.init( access_token=app.config['ROLLBAR_ACCESS_TOKEN'], environment=app.config['ROLLBAR_ENV_NAME'], root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False, ) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def __init__(self, config): self._thread = None self._stop = threading.Event() self.config = config LOGGER.debug("Initializing flask instance") self.flask_app = flask.Flask(pih2o.__name__) self.flask_app.config.from_object('pih2o.config') got_request_exception.connect(self.log_exception, self.flask_app) @self.flask_app.route('/pih2o') def say_hello(): return flask.jsonify({ "name": pih2o.__name__, "version": pih2o.__version__, "running": self.is_running() }) LOGGER.debug("Initializing the database for measurements") models.db.init_app(self.flask_app) with self.flask_app.app_context(): models.db.create_all() LOGGER.debug("Initializing the RESTful API") self.api = Api(self.flask_app, catch_all_404s=True) root = '/pih2o/api/v1' self.api.add_resource(ApiConfig, root + '/config', root + '/config/<string:section>', root + '/config/<string:section>/<string:key>', endpoint='config', resource_class_args=(config, )) self.api.add_resource(ApiPump, root + '/pump', root + '/pump/<int:duration>', endpoint='pump', resource_class_args=(self, )) self.api.add_resource(ApiSensors, root + '/sensors', root + '/sensors/<int:pin>', endpoint='sensors', resource_class_args=(self, )) self.api.add_resource(ApiMeasurements, root + '/measurements', endpoint='measurements', resource_class_args=(models.db, )) # The HW connection of the controls GPIO.setmode(GPIO.BOARD) # GPIO in physical pins mode self.pump = None self.sensors = [] self._pump_timer = None self.init_controls() atexit.register(self.shutdown_daemon)
def init_rollbar(): if not app.debug: if os.environ.get('ROLLBAR_ACCESS_TOKEN'): rollbar.init(os.environ.get('ROLLBAR_ACCESS_TOKEN'), 'python-blog-dev', root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False) got_request_exception.connect( rollbar.contrib.flask.report_exception, app) rollbar.report_message('Rollbar configured for python-blog')
def init_rollbar(): rollbar.init(access_token='8026b336e7e4475482765f8b119d4049', environment='flask_test', root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basics_config=False, code_version=get_git_sha()) rollbar.report_message('Rollbar initialized succesfully', level='debug') got_request_exception.connect(rb_flask.report_exception, app) got_request_exception.connect(rb_flask.report_exception, bp_error_handler)
def init_rollbar(): if not hasattr(config, 'TESTMODE'): env = 'production' if request.remote_addr == '127.0.0.1': env = 'development' rollbar.init(config.ROLLBAR_TOKEN, environment=env) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): """init rollbar module""" rollbar.init( app.config["ROLLBAR_TOKEN"], app.config["ENV"], root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False, ) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_app(self, app): assert self.STATE_KEY not in app.extensions app.extensions[self.STATE_KEY] = HealthTester(self.configs) app.before_request(self.before_request) request_finished.connect(self.handle_request_finished, app) request_tearing_down.connect(self.handle_request_tearing_down, app) got_request_exception.connect(self.handle_got_request_exception, app) from huskar_api.models.signals import session_load_user_failed session_load_user_failed.connect(self.handle_load_user_failed)
def init_rollbar(): """Initialize Rollbar.""" rollbar.init( os.environ['ROLLBAR_ACCESS_TOKEN'], os.environ['STAGE'], # Flask already sets up logging. allow_logging_basic_config=False) # Send exceptions from `app` to Rollbar, using Flask's signal system. got_request_exception.connect(report_exception, app)
def init_app(self, app): werkzeug = logging.getLogger("werkzeug") werkzeug.disabled = True formatter = logging.Formatter("[%(asctime)s.%(msecs)03d] (%(levelname)s) %(message)s","%m-%d-%Y %H:%M:%S") default_handler.setFormatter(formatter) app.logger.setLevel(app.config['LOG_LEVEL']) app.after_request(self.cleanup) got_request_exception.connect(self.bailout, app)
def main(): app = Flask('rj_worker') app.debug = True api = Api(app) api.add_resource(Run, '/run') app.logger.setLevel(logging.DEBUG) got_request_exception.connect(log_exception, app) app.logger.info('Starting RJ Worker') app.run(host='0.0.0.0', port=5000, use_reloader=False)
def init_rollbar(): """init rollbar module""" rollbar.init( config.ROLLBAR_KEY, config.ROLLBAR_ENV, # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False ) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(report_exception, current_app._get_current_object())
def setup_app(app): #setup syslog app.logger.addFilter(app_logging.ContextFilter()) syslog_handler = app_logging.get_syslog_handler() if syslog_handler: app.logger.addHandler(syslog_handler) #send application error exception message to log def log_exception(sender, exception, **extra): sender.logger.error(exception) got_request_exception.connect(log_exception, app)
def create_app(config_pyfile=None): """ Create a Flask application using the app factory pattern. :param settings_override: Override settings :return: Flask app """ # app = Flask(__name__, instance_relative_config=True) app = Flask(__name__) # add global CORS support # https://flask-cors.readthedocs.io/en/latest/ CORS(app) # only support config/settings files for config # app.config.from_object('config.settings') app.config.from_object(config_pyfile) # app.config.from_pyfile('settings.py', silent=True) # app.config.from_pyfile(config_pyfile, silent=True) # app.config.from_pyfile(config_pyfile, silent=False) # if settings_override: # app.config.update(settings_override) # now log config being used app.logger.info("Debug status is: " + str(app.config["DEBUG"])) app.logger.info("Testing status is: " + str(app.config["TESTING"])) app.logger.info("Development status is: " + str(app.config["DEVELOPMENT"])) app.logger.info("Server Name is: " + str(app.config["SERVER_NAME"])) # @app.before_first_request # def init_rollbar(): # init rollbar module rollbar.init( # access token for the app str(app.config["ROLLBAR_TOKEN"]), # environment name str(app.config["ROLLBAR_ENVIRONMENT"]), # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False, ) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app) rollbar.report_message("Starting app for flask-api2", "info") app.register_blueprint(page) app.register_blueprint(raw) app.register_blueprint(search) app.register_blueprint(api) extensions(app) return app
def init_rollbar(): if self._enabled: # Example taken from https://github.com/rollbar/rollbar-flask-example/blob/master/hello.py self._rb = init( self._server_key, self._environment, root=os.path.dirname(os.path.realpath(__file__)), # server root directory, makes tracebacks prettier allow_logging_basic_config=False) # flask already sets up logging got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_flask_signals(_app): from fw.db.sql_base import db as sqldb def finish_db_transaction(sender, **extra): sqldb.session.commit() def rollback(sender, **extra): sqldb.session.rollback() from flask import request_finished, got_request_exception request_finished.connect(finish_db_transaction, _app) got_request_exception.connect(rollback, _app)
def init_rollbar(): token = app.config.get('ROLLBAR_ACCESS_TOKEN') if token is None: return rollbar.init( token, 'production', root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False ) got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): if app.config['ROLLBAR_TOKEN']: rollbar.init( app.config['ROLLBAR_TOKEN'], app.config['ENVIRONMENT'], # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logger allow_logger_basic_config=False) logger.debug("Rollbar intiated") # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): rollbar.init( # access token for the demo app: https://rollbar.com/demo app.config['ROLLBAR_ACCESS_TOKEN'], # environment name 'production', # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): """init rollbar module""" rollbar.init( # access token for the demo app: https://rollbar.com/demo '4007dbacf03f426ab291c36da97da1e6', # environment name 'production', # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def __init__(self, app): self.app = app if 'BLUEOX_HOST' in app.config: self.blueox_host = app.config['BLUEOX_HOST'] if self.blueox_host: blueox.default_configure(self.blueox_host) else: blueox.default_configure() self.app.before_request(self.before_request) self.app.after_request(self.after_request) got_request_exception.connect(self.handle_exception, self.app)
def init_rollbar(): """init rollbar module""" rollbar.init( os.environ['ROLLBAR_SERVER_TOKEN'], # environment name os.environ['ENV'], # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect( rollbar.contrib.flask.report_exception, app)
def init_rollbar(): """init rollbar module""" rollbar.init( # access token for the demo app: https://rollbar.com/demo core.config.config["ROLLBAR_DASHB0ARD_KEY"], # environment name core.config.config["ROLLBAR_ENV"], # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_rollbar(): """init rollbar module""" rollbar.init( # access token for the demo app: https://rollbar.com/demo 'fc316ac1f7404dc28af26d5baed1416c', # environment name 'flasktest', # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_app(self, app): self.app = app app.extensions['rollbar'] = self ignored = [(exc, 'ignored') for exc in self.ignore_exc] rollbar.init( app.config['ROLLBAR_TOKEN'], environment=app.config.get('ROLLBAR_ENV', 'dev'), root=os.path.dirname(os.path.realpath(__file__)), allow_logging_basic_config=False, exception_level_filters=ignored, **self.init_kwargs ) # send exceptions from `app` to rollbar using flask's signal system. got_request_exception.connect(report_exception)
def init_rollbar(): """init rollbar module""" if config.DEBUG is not True: rollbar.init( # access token for the demo app: https://rollbar.com/demo '90a56a42d47d4343a45b1105338d47c8', # environment name 'heroku_development', # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def subscribe_logging_helpers(app): """ Configure functions that log in response to Flask signals emitted by app. Flask signal function invoked ------------ ------------------- request_started log_request template_rendered log_template_rendered request_finished log_response got_request_exception log_exception """ request_started.connect(log_request, app) template_rendered.connect(log_template_rendered, app) request_finished.connect(log_response, app) got_request_exception.connect(log_exception, app)
def init_rollbar(): """Initialize rollbar module. It also allows person tracking. https://github.com/rollbar/rollbar-flask-example/blob/master/hello.py """ rollbar.init( '2deae0df9d884836ab6eb7ea3057b992', # environment name 'development', # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False) # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def init_app(app): if app.config.get('ROLLBAR_TOKEN') and not app.config.get('DEBUG', True): rollbar.init( # access token for the demo app: https://rollbar.com/demo app.config['ROLLBAR_TOKEN'], # environment name app.config['DM_ENVIRONMENT'], # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False) # supplement base data collected by rollbar rollbar.BASE_DATA_HOOK = _hook # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(report_exception, app)
def init_rollbar(): """init rollbar module""" rollbar.init( # access token os.environ.get('ROLLBAR_TOKEN', ''), # environment name os.environ.get('ROLLBAR_ENV', 'development'), # server root directory, makes tracebacks prettier root=os.path.dirname(os.path.realpath(__file__)), # flask already sets up logging allow_logging_basic_config=False, # Use HTTP as GAE does not allow the use of the SSL package endpoint='http://api.rollbar.com/api/1/') # send exceptions from `app` to rollbar, using flask's signal system. got_request_exception.connect(rollbar.contrib.flask.report_exception, app)
def setup_app(app): #setup syslog app.logger.addFilter(app_logging.ContextFilter()) syslog_handler = app_logging.get_syslog_handler() if syslog_handler: app.logger.addHandler(syslog_handler) #send application error exception message to log def log_exception(sender, exception, **extra): sender.logger.error(exception) got_request_exception.connect(log_exception, app) #setup bugsnag bugsnag_api_key = os.getenv('SS_SORAYA_RECO_BUGSNAG_API_KEY') if bugsnag_api_key: bugsnag.configure( api_key= bugsnag_api_key, project_root=os.path.abspath(os.path.dirname(__file__)), release_stage=os.getenv('SS_SORAYA_RECO_RELEASE_STAGE')) handle_exceptions(app)
def use_storm(app): """Setup Storm.""" app.after_request(close_connection) #アプリが例外を投げるとafter_request呼ばれないので #処理の開始前にもコネクションのロールバックをさせることで #デッドロックを防止する。念のため、シグナルもキャッチして同様に処理する。 app.before_request(close_connection) from flask import request_finished, got_request_exception def request_finished_handler(sender, response): close_connection(response) request_finished.connect(request_finished_handler, app) def got_request_exception_handler(sender, exception): close_connection() got_request_exception.connect(got_request_exception_handler, app)
def init_app(self, app): self.app = app # read config db_args = {'minconn': app.config.get('DB_MIN_CONNECTIONS', 2), 'maxconn': app.config.get('DB_MAX_CONNECTIONS', 20), 'database': app.config.get('DB_NAME'), 'user': app.config.get('DB_USER'), 'password': app.config.get('DB_PASSWORD', ''), } if 'DB_HOST' in app.config: db_args['host'] = app.config.get('DB_HOST') if 'DB_PORT' in app.config: db_args['port'] = app.config.get('DB_PORT') self.pool = PersistentConnectionPool(**db_args) app.after_request(self.cleanup) got_request_exception.connect(self.bailout, app)
def init_rollbar(app): if 'ROLLBAR_ACCESS_TOKEN' in app.config: import rollbar.contrib.flask import rollbar rollbar.init( app.config['ROLLBAR_ACCESS_TOKEN'], app.config['ENV'], root=os.path.dirname(os.path.realpath(hah.__file__)), allow_logging_basic_config=False, exception_level_filters=[ (werkzeug.exceptions.HTTPException, 'warning'), ] ) got_request_exception.connect(rollbar.contrib.flask.report_exception, app) app.logger.info('[rollbar.init_rollbar] Rollbar enabled') else: app.logger.info('[rollbar.init_rollbar] Rollbar disabled')