From 1092718cac3800080bb766b251ae472282aef751 Mon Sep 17 00:00:00 2001
From: Erik Johnston <erik@matrix.org>
Date: Tue, 8 Jun 2021 13:49:29 +0100
Subject: [PATCH] Fix logging context when opening new DB connection (#10141)

Fixes #10140
---
 changelog.d/10141.feature   |  1 +
 synapse/storage/database.py | 12 +++++++++---
 2 files changed, 10 insertions(+), 3 deletions(-)
 create mode 100644 changelog.d/10141.feature

diff --git a/changelog.d/10141.feature b/changelog.d/10141.feature
new file mode 100644
index 0000000000..2658ab8918
--- /dev/null
+++ b/changelog.d/10141.feature
@@ -0,0 +1 @@
+Report OpenTracing spans for database activity.
diff --git a/synapse/storage/database.py b/synapse/storage/database.py
index b77368a460..d470cdacde 100644
--- a/synapse/storage/database.py
+++ b/synapse/storage/database.py
@@ -91,12 +91,18 @@ def make_pool(
     db_args = dict(db_config.config.get("args", {}))
     db_args.setdefault("cp_reconnect", True)
 
+    def _on_new_connection(conn):
+        # Ensure we have a logging context so we can correctly track queries,
+        # etc.
+        with LoggingContext("db.on_new_connection"):
+            engine.on_new_connection(
+                LoggingDatabaseConnection(conn, engine, "on_new_connection")
+            )
+
     return adbapi.ConnectionPool(
         db_config.config["name"],
         cp_reactor=reactor,
-        cp_openfun=lambda conn: engine.on_new_connection(
-            LoggingDatabaseConnection(conn, engine, "on_new_connection")
-        ),
+        cp_openfun=_on_new_connection,
         **db_args,
     )
 
-- 
GitLab