Skip to content

Commit

Permalink
Handle multiprocessing for named loggers. (#34)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
3 people authored May 2, 2024
1 parent a860778 commit 6372af5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
13 changes: 10 additions & 3 deletions fancylog/fancylog.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,14 +292,21 @@ 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,
log_to_console=log_to_console,
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

Expand All @@ -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():
Expand Down
17 changes: 17 additions & 0 deletions tests/tests/test_general.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import logging

import pytest
from rich.logging import RichHandler

import fancylog
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 6372af5

Please sign in to comment.