[ADD] core: utility to easily enable logging on a cursor

Enabling sql logging for a specific section of code is currently a
pain in the ass as it requires updating both the cursor and the
logger. This utility does that.

This CM is *not* thread-safe as it updates and resets the cursor
without using CAS or anything, so if cursor 1 gets enabled, then
cursor 2, then cursor 1 stops, then cursor 2, cursor 2 will reset the
logger to `logging.DEBUG` which cursor 1 had set, rather than the
probable `logging.NOTSET` it originally was.

Should be possible to fix by e.g. storing the levels in a static
stack (and setting whatever gets popped) buuut... the logging is
already a bit of a mess when multithreaded so I'm unsure it matters
much.

Part-of: odoo/odoo#76243
This commit is contained in:
Xavier Morel
2021-10-01 15:26:50 +00:00
parent 38f37fe442
commit 128db519c2
+15
View File
@@ -371,6 +371,21 @@ class Cursor(BaseCursor):
self.sql_log_count = 0
self.sql_log = False
@contextmanager
def _enable_logging(self):
""" Forcefully enables logging for this cursor, restores it afterwards.
Updates the logger in-place, so not thread-safe.
"""
previous, self.sql_log = self.sql_log, True
level = _logger.level
_logger.setLevel(logging.DEBUG)
try:
yield
finally:
_logger.setLevel(level)
self.sql_log = previous
@check
def close(self):
return self._close(False)