jenkins-bot has submitted this change. ( 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1329611?usp=email )

Change subject: logging: Prevent recursive handler initialization
......................................................................

logging: Prevent recursive handler initialization

File logging creates a Throttle whose debug output can re-enter the
pending logging initialization routine. This installs two rotating
handlers for the same file.

Guard handler setup against re-entry and cover both -log and -debug.

Bug: T436130
Change-Id: I21b3cd4c0ee7e629736a028c3ffd097d0041b115
---
M pywikibot/bot.py
M tests/bot_tests.py
2 files changed, 63 insertions(+), 0 deletions(-)

Approvals:
  Ivan-r: Looks good to me, but someone else must approve
  jenkins-bot: Verified
  Mahveotm: Looks good to me, approved




diff --git a/pywikibot/bot.py b/pywikibot/bot.py
index d827660..f724ddf 100644
--- a/pywikibot/bot.py
+++ b/pywikibot/bot.py
@@ -308,6 +308,7 @@


 _handlers_initialized = []  # we can have a script and the script wrapper
+_handlers_initializing = False


 def handler_namer(name: str) -> str:
@@ -372,6 +373,21 @@
        Different logfiles are used if multiple processes of the same
        script are running.
     """
+    global _handlers_initializing
+
+    # Throttle logs during setup and can invoke this pending routine again.
+    if _handlers_initializing:
+        return
+
+    _handlers_initializing = True
+    try:
+        _init_handlers()
+    finally:
+        _handlers_initializing = False
+
+
+def _init_handlers() -> None:
+    """Initialize logging handlers without a re-entrancy check."""
     module_name = calledModuleName()
     if not module_name:
         module_name = 'terminal-interface'
diff --git a/tests/bot_tests.py b/tests/bot_tests.py
index 8c1048b..bc829d5 100755
--- a/tests/bot_tests.py
+++ b/tests/bot_tests.py
@@ -10,11 +10,58 @@
 import sys
 import unittest
 from contextlib import suppress
+from tempfile import TemporaryDirectory
+from textwrap import dedent

 import pywikibot
 import pywikibot.bot
 from pywikibot import i18n
 from tests.aspects import DefaultSiteTestCase, SiteAttributeTestCase, TestCase
+from tests.utils import execute
+
+
+class LoggingTestCase(TestCase):
+
+    """Test logging initialization."""
+
+    net = False
+
+    def test_file_handler_initialized_once(self) -> None:
+        """Test that logging options create one rotating file handler."""
+        code = dedent("""
+            import logging.handlers
+            import os
+            import sys
+
+            os.environ['PYWIKIBOT_NO_USER_CONFIG'] = '2'
+            import pywikibot
+
+            pywikibot.argvu = ['logging_test', sys.argv[2]]
+            pywikibot.config.base_dir = sys.argv[1]
+            pywikibot.Site = lambda: None
+            pywikibot.bot.writeToCommandLogFile = lambda: None
+            headers = []
+            pywikibot.bot.writelogheader = lambda: headers.append(None)
+            pywikibot.handle_args([sys.argv[2]], do_help=False)
+
+            handlers = [
+                handler
+                for handler in logging.getLogger('pywiki').handlers
+                if isinstance(handler, logging.handlers.RotatingFileHandler)
+            ]
+            print(len(handlers), len(headers))
+        """)
+
+        with TemporaryDirectory() as directory:
+            for option in ('-log', '-debug'):
+                with self.subTest(option=option):
+                    result = execute(
+                        [sys.executable, '-c', code, directory, option],
+                        timeout=10)
+                    self.assertIsNone(result['timeout'])
+                    self.assertEqual(result['exit_code'], 0,
+                                     result['stderr'])
+                    self.assertEqual(result['stdout'].strip(), '1 1')


 class TWNBotTestCase(TestCase):

--
To view, visit 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1329611?usp=email
To unsubscribe, or for help writing mail filters, visit 
https://gerrit.wikimedia.org/r/settings?usp=email

Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I21b3cd4c0ee7e629736a028c3ffd097d0041b115
Gerrit-Change-Number: 1329611
Gerrit-PatchSet: 3
Gerrit-Owner: Mahveotm <[email protected]>
Gerrit-Reviewer: Ivan-r <[email protected]>
Gerrit-Reviewer: Mahveotm <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
_______________________________________________
Pywikibot-commits mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to