From 89cb413cc1fe1495665acc090f286ec42bcaa5bb Mon Sep 17 00:00:00 2001 From: Aaron LI Date: Thu, 29 Sep 2016 22:58:54 +0800 Subject: utils/logging: reset handlers before initialization/reconfiguration Also improve the comments. --- fg21sim/configs/manager.py | 8 +++++++- fg21sim/utils/logging.py | 11 +++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) (limited to 'fg21sim') diff --git a/fg21sim/configs/manager.py b/fg21sim/configs/manager.py index f5465a9..a889259 100644 --- a/fg21sim/configs/manager.py +++ b/fg21sim/configs/manager.py @@ -84,7 +84,13 @@ class ConfigManager: @property def logging(self): """Get and prepare the logging configurations for - `logging.basicConfig()` + ``logging.basicConfig()`` to initialize the logging module. + + NOTE + ---- + ``basicConfig()`` will automatically create a ``Formatter`` with + the giving ``format`` and ``datefmt`` for each handlers if necessary, + and then adding the handlers to the "root" logger. """ from logging import FileHandler, StreamHandler conf = self.get("logging") diff --git a/fg21sim/utils/logging.py b/fg21sim/utils/logging.py index 0abf4d3..2630a58 100644 --- a/fg21sim/utils/logging.py +++ b/fg21sim/utils/logging.py @@ -19,6 +19,7 @@ def setup_logging(dict_config=None, level=None, stream=None, logfile=None): ---------- dict_config : dict Dict of logging configurations specified in the config file. + If this parameter specified, the logging will be reconfigured. level : string; Override the existing log level stream : string; "stderr", "stdout", or "" @@ -37,16 +38,22 @@ def setup_logging(dict_config=None, level=None, stream=None, logfile=None): """ # default file open mode for logging to file filemode = "a" + root_logger = logging.getLogger() # if dict_config: # XXX: # "basicConfig()" does NOT accept paramter "filemode" if the # corresponding parameter "filename" NOT specified. filemode = dict_config.pop("filemode", filemode) + # Clear existing handlers, otherwise further "basicConfig" calls + # will be ignored + for handler in root_logger.handlers: + root_logger.removeHandler(handler) + # Initialize/reconfigure the logging, which will automatically + # create a ``Formatter`` for handlers if necessary, and adding + # the handlers to the "root" logger. logging.basicConfig(**dict_config) # - root_logger = logging.getLogger() - # if level is not None: level_int = getattr(logging, level.upper(), None) if not isinstance(level_int, int): -- cgit v1.2.2