From eb183b0d3b0af1fac2a62a27db39551d0e71cd6a Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Fri, 6 Jan 2023 18:18:55 +0100 Subject: [PATCH] config: split console logging between stdout & stderr base on level --- mylib/config.py | 22 +++++++++++++++++++--- tests/test_config.py | 18 +++++++++++++++++- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/mylib/config.py b/mylib/config.py index a6ab0de..ea3952b 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -879,11 +879,20 @@ class Config: # pylint: disable=too-many-instance-attributes logging.getLogger().setLevel(logging.INFO) if self.get('console', 'enabled'): - console_handler = logging.StreamHandler(sys.stdout) + stdout_console_handler = logging.StreamHandler(sys.stdout) + stdout_console_handler.addFilter(StdoutInfoFilter()) + stdout_console_handler.setLevel(logging.DEBUG) + + stderr_console_handler = logging.StreamHandler(sys.stderr) + stderr_console_handler.setLevel(logging.WARNING) + if self.get('console', 'log_format'): console_formater = logging.Formatter(self.get('console', 'log_format')) - console_handler.setFormatter(console_formater) - logging.getLogger().addHandler(console_handler) + stdout_console_handler.setFormatter(console_formater) + stderr_console_handler.setFormatter(console_formater) + + logging.getLogger().addHandler(stdout_console_handler) + logging.getLogger().addHandler(stderr_console_handler) if execute_callback: self._loaded() @@ -1127,3 +1136,10 @@ class ConfigSectionAsDictWrapper: def __delitem__(self, key): raise Exception('Deleting a configuration option is not supported') + + +# pylint: disable=too-few-public-methods +class StdoutInfoFilter(logging.Filter): + """ Logging filter to keep messages only >= logging.INFO """ + def filter(self, record): + return record.levelno in (logging.DEBUG, logging.INFO) diff --git a/tests/test_config.py b/tests/test_config.py index 44ab445..4018f7b 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,10 +1,12 @@ # pylint: disable=redefined-outer-name,missing-function-docstring,protected-access,global-statement """ Tests on config lib """ +import logging + from mylib.config import Config, ConfigSection from mylib.config import StringOption -runned = dict() +runned = {} def test_config_init_default_args(): @@ -208,3 +210,17 @@ def test_get_default(): config.parse_arguments_options(argv=[], create=False) assert config.get(section_name, opt_name) == opt_default_value + + +def test_logging_splited_stdout_stderr(capsys): + config = Config('Test app') + config.parse_arguments_options(argv=['-C', '-v'], create=False) + info_msg = "[info]" + err_msg = "[error]" + logging.getLogger().info(info_msg) + logging.getLogger().error(err_msg) + captured = capsys.readouterr() + assert info_msg in captured.out + assert info_msg not in captured.err + assert err_msg in captured.err + assert err_msg not in captured.out