From 6372af5267e0c0f0c31a0f49a0d7abdd7f6665d4 Mon Sep 17 00:00:00 2001 From: Joe Ziminski <55797454+JoeZiminski@users.noreply.github.com> Date: Thu, 2 May 2024 11:47:08 +0100 Subject: [PATCH] Handle multiprocessing for named loggers. (#34) * Use created logger for multiprocessing setup. * Instead raise if trying to multiprocess log not using root. * Add test. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: Adam Tyson Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- fancylog/fancylog.py | 13 ++++++++++--- tests/tests/test_general.py | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/fancylog/fancylog.py b/fancylog/fancylog.py index 156089a..77a6c64 100644 --- a/fancylog/fancylog.py +++ b/fancylog/fancylog.py @@ -292,7 +292,7 @@ def setup_logging( :param logger_name: If None, logger uses default logger. Otherwise, logger name is set to `logger_name`. """ - initialise_logger( + logger = initialise_logger( filename, print_level=print_level, file_level=file_level, @@ -300,6 +300,13 @@ def setup_logging( logger_name=logger_name, ) if multiprocessing_aware: + if logger_name: + raise ValueError( + "`multiprocessing_aware` is not supported" + "with `logger_name`. Multiprocess logging" + "must be performed with the root logger." + ) + try: import multiprocessing_logging @@ -316,8 +323,8 @@ def setup_logging( "multiple processes." ) else: - logging.info("Starting logging") - logging.info("Not logging multiple processes") + logger.info("Starting logging") + logger.info("Not logging multiple processes") def disable_logging(): diff --git a/tests/tests/test_general.py b/tests/tests/test_general.py index fe78753..6f1acbb 100644 --- a/tests/tests/test_general.py +++ b/tests/tests/test_general.py @@ -1,5 +1,6 @@ import logging +import pytest from rich.logging import RichHandler import fancylog @@ -42,6 +43,22 @@ def test_logger_name(tmp_path): assert logger_name in logging.root.manager.loggerDict +def test_assert_named_logger_with_multiprocessing(tmp_path): + """ + Test an error is raised if trying to use multiprocess + logging with a named logger. + """ + with pytest.raises(ValueError) as e: + fancylog.start_logging( + tmp_path, + fancylog, + logger_name="hello_world", + multiprocessing_aware=True, + ) + + assert "root logger" in str(e.value) + + def test_logging_to_console(tmp_path, capsys): """ Check that logs are written to stdout when