Phil Sheard
Phil Sheard

Reputation: 2162

Sentry - Log Flask and Sentry at the same time / same DSN

Edit: Title and added some code samples.

I'm trying to work out how to send both Celery worker and Flask logging to Sentry using the same DSN.

Setup is as follows:

(The code has been simplified for demo purposes.)

celery = Celery(__name__, broker=config[config_name].CELERY_BROKER_URL)
client = Client(dsn={my_dsn}, transport=HTTPTransport, )
sentry = Sentry(client=client)
def create_app(config_filename): 
    app = Flask(__name__)
    app.config.from_pyfile(config_filename)
    celery.conf.update(app.config)
    # https://docs.getsentry.com/hosted/clients/python/integrations/flask/#extended-setup :
    sentry.init_app(app, logging=True, level=logging.INFO, )
    # https://docs.getsentry.com/hosted/clients/python/integrations/celery/ :
    register_logger_signal(client, loglevel=logging.INFO)
    register_signal(client)
    return app

By following the Sentry Celery instructions, Sentry (in their own words) "hijack(s) Celery error handling", and works well. However, this then drops the Flask error handling in the process.

Is there a way to register both loggers (Flask and Celery) so that they both send log entries up to Sentry? Or should the Celery registration take place in the separate celery_worker.py file that runs within the Celery container?

Upvotes: 1

Views: 1287

Answers (1)

user41951
user41951

Reputation: 191

I managed to do it like this:

app = Flask(__name__)
celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'], backend=app.config['CELERY_RESULT_BACKEND'], worker_send_task_events=True, task_send_sent_event=True)
celery.conf.update(app.config)

client = Client(dsn={my_dsn})
sentry = Sentry(app, dsn={my_dsn})
register_logger_signal(client)
register_logger_signal(client, loglevel=logging.INFO)
register_signal(client)
register_signal(client, ignore_expected=True)

Upvotes: 1

Related Questions