From df4c52815b6f89cc4c4f09463eb7b038d823a216 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A0=20Casaj=C3=BAs?= Date: Fri, 27 Sep 2024 08:00:25 +0200 Subject: [PATCH] Add monitoring for app connections to the db (#2235) --- events/event_source.py | 4 +++- monitoring.py | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/events/event_source.py b/events/event_source.py index cd7f9379c..3633ec742 100644 --- a/events/event_source.py +++ b/events/event_source.py @@ -72,7 +72,9 @@ def __listen(self, on_event: Callable[[SyncEvent], NoReturn]): Session.close() # Ensure we get a new connection and we don't leave a dangling tx def __connect(self): - self.__connection = psycopg2.connect(self.__connection_string) + self.__connection = psycopg2.connect( + self.__connection_string, application_name="sl-event-listen" + ) from app.db import Session diff --git a/monitoring.py b/monitoring.py index ed90ea469..72f4967aa 100644 --- a/monitoring.py +++ b/monitoring.py @@ -94,6 +94,20 @@ def log_nb_db_connection(): newrelic.agent.record_custom_metric("Custom/nb_db_connections", nb_connection) +@newrelic.agent.background_task() +def log_nb_db_connection_by_app_name(): + # get the number of connections to the DB + rows = Session.execute( + "SELECT application_name, count(datid) FROM pg_stat_activity group by application_name" + ) + for row in rows: + if row[0].find("sl-") == 0: + LOG.d("number of db connections for app %s = %s", row[0], row[1]) + newrelic.agent.record_custom_metric( + f"Custom/nb_db_app_connection/{row[0]}", row[1] + ) + + @newrelic.agent.background_task() def log_pending_to_process_events(): r = Session.execute("select count(*) from sync_event WHERE taken_time IS NULL;") @@ -148,6 +162,7 @@ def log_failed_events(): log_pending_to_process_events() log_events_pending_dead_letter() log_failed_events() + log_nb_db_connection_by_app_name() Session.close() exporter.run()