From 128db519c2f41098fdd475d19af5929ec9953013 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Wed, 8 Sep 2021 11:03:39 +0000 Subject: [PATCH] [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 --- odoo/sql_db.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/odoo/sql_db.py b/odoo/sql_db.py index ad0d4534aa9..082044f1e32 100644 --- a/odoo/sql_db.py +++ b/odoo/sql_db.py @@ -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)