Skip to content

Commit

Permalink
Don't propagate named loggers. (#32)
Browse files Browse the repository at this point in the history
* Don't propagate named loggers and add tests.

* Tidy up test docstring.

* Fix working of test name.
  • Loading branch information
JoeZiminski authored May 2, 2024
1 parent be62d33 commit a860778
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
1 change: 1 addition & 0 deletions fancylog/fancylog.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,7 @@ def initialise_logger(
if logger_name:
logger = logging.getLogger(logger_name)
logger.handlers = []
logger.propagate = False
else:
logger = logging.getLogger()

Expand Down
56 changes: 55 additions & 1 deletion tests/tests/test_general.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,26 @@ def test_logger_name(tmp_path):
assert logger_name in logging.root.manager.loggerDict


def test_logging_to_console(tmp_path, capsys):
"""
Check that logs are written to stdout when
`log_to_console` is `True`.
"""
logger_name = "hello_world"

fancylog.start_logging(
tmp_path, fancylog, log_to_console=True, logger_name=logger_name
)

logger = logging.getLogger(logger_name)

logger.debug("!!£%$")

captured = capsys.readouterr()

assert "!!£%$" in captured.out


def test_correct_handlers_are_set(tmp_path):
"""
Test the handlers on the logger are as specified by the
Expand All @@ -51,7 +71,7 @@ def test_correct_handlers_are_set(tmp_path):
"""
logger_name = "hello_world"

# Test no handlers are assigned when non requested
# Test no handlers are assigned when not requested
fancylog.start_logging(
tmp_path,
fancylog,
Expand Down Expand Up @@ -141,3 +161,37 @@ def test_handlers_are_refreshed(tmp_path):
)

assert logger.handlers == []


def test_named_logger_doesnt_propagate(tmp_path, capsys):
"""
By default, named loggers will propagate through
parent handlers. Root is always parent to named loggers.
This means that named logger can still print to console
through the root StreamHandler unless `propagate` is set
to `False`. Check here that propagate is set to False and
indeed named logger does not print to console.
"""
logger_name = "hello_world"

fancylog.start_logging(
tmp_path, fancylog, logger_name=logger_name, log_to_console=False
)

logger = logging.getLogger(logger_name)

assert logger.propagate is False

logger.debug("XN$£ not in stdout")

logging.debug("YYXX in stdout")

logger.debug("PQ&* not in stdout")

captured = capsys.readouterr()

assert "XN$£" not in captured.out, "logger initially writing to stdout"
assert "YYXX" in captured.out, "root is not writing to stdout"
assert (
"PQ&*" not in captured.out
), "logger writing to stdout through root handler"

0 comments on commit a860778

Please sign in to comment.