Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 9 additions & 25 deletions src/registration_engine/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,21 +24,6 @@
from logging.handlers import RotatingFileHandler


class RegistrationFormatter(logging.Formatter):
"""Custom logging Formatter that handles dynamic attributes.

Specifically handles 'newline' and 'provider' attributes in the
format string.
"""

def format(self, record: logging.LogRecord) -> str:
if not hasattr(record, "newline"):
record.newline = "\n"
if not hasattr(record, "provider"):
record.provider = "unknown"
return super().format(record)


def get_logger(debug: bool = False) -> logging.Logger:
"""Retrieve and configure the 'registration-engine' logger.

Expand All @@ -62,19 +47,18 @@ def get_logger(debug: bool = False) -> logging.Logger:
log_path, maxBytes=10 * 1024 * 1024, backupCount=5
)
except Exception:
# Fallback to local directory if ~ is not writable
file_handler = RotatingFileHandler(
"registration_engine.log",
maxBytes=10 * 1024 * 1024,
backupCount=5,
)
# If home dir is not writable skip file log
file_handler = None

fmt = (
"%(levelname)s %(asctime)s %(name)s:%(provider)s%(newline)s %(message)s"
"%(levelname)s %(asctime)s %(name)s "
"[%(module)s.%(funcName)s:%(lineno)d]\n %(message)s"
)
formatter = RegistrationFormatter(fmt)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
formatter = logging.Formatter(fmt)

if file_handler:
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(formatter)
Expand Down
39 changes: 16 additions & 23 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,7 @@
import tempfile
from unittest.mock import patch

from registration_engine.utils import RegistrationFormatter, get_logger


def test_registration_formatter():
"""Test that the custom formatter correctly injects default attributes."""
formatter = RegistrationFormatter()
record = logging.LogRecord(
name="test",
level=logging.INFO,
pathname="test.py",
lineno=10,
msg="test message",
args=(),
exc_info=None,
)
# By default, record shouldn't have 'newline' or 'provider' attributes
assert not hasattr(record, "newline")
assert not hasattr(record, "provider")

# Formatting should inject default values
formatter.format(record)
assert record.newline == "\n"
assert record.provider == "unknown"
from registration_engine.utils import get_logger


def test_get_logger_config():
Expand All @@ -71,3 +49,18 @@ def test_get_logger_config():
assert log_instance_debug.level == logging.DEBUG
# Should not duplicate handler
assert len(log_instance_debug.handlers) == 2


@patch("registration_engine.utils.RotatingFileHandler")
def test_get_logger_unwritable_directory(mock_rotating_handler):
"""Test get_logger handles RotatingFileHandler failures gracefully."""
mock_rotating_handler.side_effect = PermissionError("Permission denied")

logger = logging.getLogger("registration-engine")
logger.handlers.clear()

log_instance = get_logger(debug=False)
assert log_instance.level == logging.INFO
# Only StreamHandler should be present as file_handler creation failed
assert len(log_instance.handlers) == 1
assert isinstance(log_instance.handlers[0], logging.StreamHandler)
Loading