diff --git a/bittensor/utils/btlogging/loggingmachine.py b/bittensor/utils/btlogging/loggingmachine.py index 3fd323c742..8e12c70567 100644 --- a/bittensor/utils/btlogging/loggingmachine.py +++ b/bittensor/utils/btlogging/loggingmachine.py @@ -47,6 +47,12 @@ from .helpers import all_loggers +def _concat_message(msg="", prefix="", suffix=""): + """Concatenates a message with optional prefix and suffix.""" + msg = f"{f'{prefix} - ' if prefix else ''}{msg}{f' - {suffix}' if suffix else ''}" + return msg + + class LoggingConfig(NamedTuple): """Named tuple to hold the logging configuration.""" @@ -363,17 +369,17 @@ def __trace_on__(self) -> bool: def trace(self, msg="", prefix="", suffix="", *args, **kwargs): """Wraps trace message with prefix and suffix.""" - msg = f"{prefix} - {msg} - {suffix}" + msg = _concat_message(msg, prefix, suffix) self._logger.trace(msg, *args, **kwargs) def debug(self, msg="", prefix="", suffix="", *args, **kwargs): """Wraps debug message with prefix and suffix.""" - msg = f"{prefix} - {msg} - {suffix}" + msg = _concat_message(msg, prefix, suffix) self._logger.debug(msg, *args, **kwargs) def info(self, msg="", prefix="", suffix="", *args, **kwargs): """Wraps info message with prefix and suffix.""" - msg = f"{prefix} - {msg} - {suffix}" + msg = _concat_message(msg, prefix, suffix) self._logger.info(msg, *args, **kwargs) def success(self, msg="", prefix="", suffix="", *args, **kwargs): diff --git a/tests/unit_tests/test_logging.py b/tests/unit_tests/test_logging.py index 6bd7b6acda..2c5e593f0e 100644 --- a/tests/unit_tests/test_logging.py +++ b/tests/unit_tests/test_logging.py @@ -9,7 +9,7 @@ DEFAULT_LOG_FILE_NAME, BITTENSOR_LOGGER_NAME, ) -from bittensor.utils.btlogging.loggingmachine import LoggingConfig +from bittensor.utils.btlogging.loggingmachine import LoggingConfig, _concat_message @pytest.fixture(autouse=True, scope="session") @@ -175,3 +175,25 @@ def test_all_log_levels_output(logging_machine, caplog): assert "Test warning" in caplog.text assert "Test error" in caplog.text assert "Test critical" in caplog.text + + +@pytest.mark.parametrize( + "msg, prefix, suffix, expected_result", + [ + ("msg", "", "", "msg"), + ("msg", None, None, "msg"), + ("msg", "prefix", None, "prefix - msg"), + ("msg", None, "suffix", "msg - suffix"), + ("msg", "prefix", "suffix", "prefix - msg - suffix"), + ], + ids=[ + "message, no prefix (str), no suffix (str)", + "message, no prefix (None), no suffix (None)", + "message and prefix only", + "message and suffix only", + "message, prefix, and suffix", + ], +) +def test_concat(msg, prefix, suffix, expected_result): + """Test different options of message concatenation with prefix and suffix.""" + assert _concat_message(msg, prefix, suffix) == expected_result