From 68c2103c584dfefc556355b7d5c4f9137bbb66a8 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Mon, 30 Oct 2023 14:04:43 +0100 Subject: [PATCH] config: add console log_level parameter --- mylib/config.py | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/mylib/config.py b/mylib/config.py index f2acf42..b91f4af 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -849,6 +849,17 @@ class Config: # pylint: disable=too-many-instance-attributes arg="--console-log-format", comment="Console log format", ) + console_section.add_option( + StringOption, + "log_level", + comment=( + "Console log level limit : by default, all logged messages (according to main log " + "level) will be logged to the console, but you can set a minimal level if you " + # logging.getLevelNamesMapping() not available in python 3.9 + # pylint: disable=protected-access + f"want. Possible values: {', '.join(logging._nameToLevel)}." + ), + ) logfile_section = self.add_section("logfile", comment="Logging file") logfile_section.add_option(StringOption, "path", comment="File log path") @@ -950,21 +961,33 @@ class Config: # pylint: disable=too-many-instance-attributes self.set(*opt_info) if self.get("console", "enabled"): - stdout_console_handler = logging.StreamHandler( - sys.stderr if self.get("console", "force_stderr") else sys.stdout + console_log_level = ( + # logging.getLevelNamesMapping() not available in python 3.9 + # pylint: disable=protected-access + logging._nameToLevel.get(self.get("console", "log_level")) + if self.get("console", "log_level") + else logging.DEBUG ) - stdout_console_handler.addFilter(StdoutInfoFilter()) - stdout_console_handler.setLevel(logging.DEBUG) + if console_log_level < logging.WARNING: + stdout_console_handler = logging.StreamHandler( + sys.stderr if self.get("console", "force_stderr") else sys.stdout + ) + stdout_console_handler.addFilter(StdoutInfoFilter()) + stdout_console_handler.setLevel(console_log_level) stderr_console_handler = logging.StreamHandler(sys.stderr) - stderr_console_handler.setLevel(logging.WARNING) + stderr_console_handler.setLevel( + console_log_level if console_log_level > logging.WARNING else logging.WARNING + ) if self.get("console", "log_format"): console_formater = logging.Formatter(self.get("console", "log_format")) - stdout_console_handler.setFormatter(console_formater) + if console_log_level < logging.WARNING: + stdout_console_handler.setFormatter(console_formater) stderr_console_handler.setFormatter(console_formater) - logging.getLogger().addHandler(stdout_console_handler) + if console_log_level < logging.WARNING: + logging.getLogger().addHandler(stdout_console_handler) logging.getLogger().addHandler(stderr_console_handler) if self.get("logfile", "path"):