Skip to content

Commit 6a7fbd3

Browse files
authored
Remove the query logger when the query_logger() block raises (#1373)
query_logger() removed its callback after a bare yield, so any exception in the with-block, such as a failing query, left the logger attached to the connection. Pooled connections then kept reporting later, unrelated queries to it.
1 parent 1bd643e commit 6a7fbd3

2 files changed

Lines changed: 16 additions & 2 deletions

File tree

‎asyncpg/connection.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1932,8 +1932,10 @@ def __call__(self, record):
19321932
.. versionadded:: 0.29.0
19331933
"""
19341934
self.add_query_logger(callback)
1935-
yield
1936-
self.remove_query_logger(callback)
1935+
try:
1936+
yield
1937+
finally:
1938+
self.remove_query_logger(callback)
19371939

19381940
@contextlib.contextmanager
19391941
def _time_and_log(self, query, args, timeout):

‎tests/test_logging.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,15 @@ async def test_error_logging(self):
4949
type(log.records[0].exception),
5050
exceptions.UndefinedColumnError
5151
)
52+
53+
async def test_logging_context_removed_on_error(self):
54+
log = LogCollector()
55+
with self.assertRaises(exceptions.UndefinedColumnError):
56+
with self.con.query_logger(log):
57+
await self.con.execute("SELECT x")
58+
59+
self.assertEqual(len(self.con._query_loggers), 0)
60+
61+
await self.con.execute("SELECT 1")
62+
await asyncio.sleep(0) # wait for logging
63+
self.assertEqual(len(log.records), 1)

0 commit comments

Comments
 (0)