From 365cddd6e6c61cca47cc1d09c19cadb1cbc07510 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jean-No=C3=ABl=20Rouvignac?= Date: Mon, 5 Sep 2022 11:09:57 +0200 Subject: [PATCH] closes #11: use threading.current_thread() and name in Python versions post 2.6 Keep using the old names currentThread() and getName() for Python versions pre 2.6 --- robotbackgroundlogger.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/robotbackgroundlogger.py b/robotbackgroundlogger.py index cb1e8f8..e99da2b 100644 --- a/robotbackgroundlogger.py +++ b/robotbackgroundlogger.py @@ -26,7 +26,6 @@ __version__ = '1.3dev' - class BaseLogger(object): """Base class for custom loggers with same api as ``robot.api.logger``.""" @@ -80,12 +79,12 @@ def __init__(self): def write(self, msg, level, html=False): with self.lock: - thread = threading.currentThread().getName() - if thread in self.LOGGING_THREADS: + thread_name = current_thread_name() + if thread_name in self.LOGGING_THREADS: logger.write(msg, level, html) else: message = BackgroundMessage(msg, level, html) - self._messages.setdefault(thread, []).append(message) + self._messages.setdefault(thread_name, []).append(message) def log_background_messages(self, name=None): """Forwards messages logged on background to Robot Framework log. @@ -96,17 +95,25 @@ def log_background_messages(self, name=None): This method must be called from the main thread. """ - thread = threading.currentThread().getName() - if thread not in self.LOGGING_THREADS: + thread_name = current_thread_name() + if thread_name not in self.LOGGING_THREADS: raise RuntimeError( "Logging background messages is only allowed from the main " - "thread. Current thread name: %s" % thread) + "thread. Current thread name: %s" % thread_name) with self.lock: if name: self._log_messages_by_thread(name) else: self._log_all_messages() + def current_thread_name(): + if hasattr(threading, 'current_thread'): + # Changed in version 2.6: Added current_thread() and name property. + return threading.current_thread().name + else: + # This gives warnings in more recent versions of Python + return threading.currentThread().getName() + def _log_messages_by_thread(self, name): for message in self._messages.pop(name, []): print(message.format())