feat: add configurable logging service with file rotation
This commit is contained in:
parent
77818c2bfd
commit
a12686eafb
|
|
@ -1,10 +1,13 @@
|
|||
from __future__ import annotations
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
from PySide6.QtWidgets import QApplication
|
||||
|
||||
from ui.main_window import MainWindow
|
||||
from core.config_service import AppConfig, ConfigError, ConfigService
|
||||
from logging_ext.logging_service import LoggingService
|
||||
|
||||
APP_NAME = "VoicePTT"
|
||||
ORGANIZATION_NAME = "VoicePTT"
|
||||
|
|
@ -17,9 +20,34 @@ def build_application(argv: list[str] | None = None) -> QApplication:
|
|||
return app
|
||||
|
||||
|
||||
def load_configuration() -> AppConfig:
|
||||
config_service = ConfigService()
|
||||
try:
|
||||
return config_service.load()
|
||||
except ConfigError:
|
||||
config = config_service.default_config()
|
||||
config.paths.config_path = str(config_service.config_path)
|
||||
return config
|
||||
|
||||
|
||||
def initialize_logging(config: AppConfig) -> logging.Logger:
|
||||
logging_service = LoggingService()
|
||||
result = logging_service.initialize(config.logging, config.paths.logs_root_directory)
|
||||
logger = logging.getLogger(APP_NAME)
|
||||
if result.success:
|
||||
logging_service.log_startup(logger)
|
||||
else:
|
||||
logging.warning("Logging initialization failed: %s", result.error_message)
|
||||
return logger
|
||||
|
||||
|
||||
def main() -> int:
|
||||
config = load_configuration()
|
||||
logger = initialize_logging(config)
|
||||
app = build_application()
|
||||
window = MainWindow()
|
||||
window.show()
|
||||
return app.exec()
|
||||
exit_code = app.exec()
|
||||
LoggingService.log_shutdown(logger)
|
||||
return exit_code
|
||||
|
||||
|
|
|
|||
|
|
@ -1,2 +1,3 @@
|
|||
"""Logging extensions package."""
|
||||
from .logging_service import LoggingService, LoggingSetupResult
|
||||
|
||||
__all__ = ["LoggingService", "LoggingSetupResult"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,112 @@
|
|||
"""Application logging setup for VoicePTT."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
|
||||
from core.config_service import (
|
||||
DEFAULT_LOG_BACKUP_COUNT,
|
||||
DEFAULT_LOG_FILE_NAME,
|
||||
DEFAULT_LOG_LEVEL,
|
||||
DEFAULT_LOG_ROTATION_BYTES,
|
||||
LoggingConfig,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class LoggingSetupResult:
|
||||
success: bool
|
||||
log_file_path: Path | None = None
|
||||
error_message: str | None = None
|
||||
|
||||
|
||||
class LoggingService:
|
||||
def initialize(self, logging_config: LoggingConfig, logs_root_directory: Path | str) -> LoggingSetupResult:
|
||||
log_directory = Path(logs_root_directory)
|
||||
log_file_name = logging_config.file_name or DEFAULT_LOG_FILE_NAME
|
||||
log_file_path = log_directory / log_file_name
|
||||
|
||||
level = self._parse_level(logging_config.level)
|
||||
rotation_bytes = self._coerce_positive_int(logging_config.rotation_bytes, DEFAULT_LOG_ROTATION_BYTES)
|
||||
backup_count = self._coerce_non_negative_int(logging_config.backup_count, DEFAULT_LOG_BACKUP_COUNT)
|
||||
|
||||
try:
|
||||
log_directory.mkdir(parents=True, exist_ok=True)
|
||||
handler = RotatingFileHandler(
|
||||
log_file_path,
|
||||
maxBytes=rotation_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding="utf-8",
|
||||
)
|
||||
handler.setFormatter(
|
||||
logging.Formatter(
|
||||
fmt="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
datefmt="%Y-%m-%d %H:%M:%S",
|
||||
)
|
||||
)
|
||||
except OSError as exc:
|
||||
return LoggingSetupResult(
|
||||
success=False,
|
||||
log_file_path=log_file_path,
|
||||
error_message=f"Unable to initialize log file at {log_file_path}: {exc}",
|
||||
)
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
previous_level = root_logger.level
|
||||
previous_handlers = list(root_logger.handlers)
|
||||
|
||||
try:
|
||||
for existing_handler in previous_handlers:
|
||||
root_logger.removeHandler(existing_handler)
|
||||
|
||||
root_logger.setLevel(level)
|
||||
root_logger.addHandler(handler)
|
||||
except Exception as exc: # pragma: no cover - defensive rollback
|
||||
root_logger.removeHandler(handler)
|
||||
handler.close()
|
||||
root_logger.setLevel(previous_level)
|
||||
for existing_handler in previous_handlers:
|
||||
if existing_handler not in root_logger.handlers:
|
||||
root_logger.addHandler(existing_handler)
|
||||
return LoggingSetupResult(
|
||||
success=False,
|
||||
log_file_path=log_file_path,
|
||||
error_message=f"Unable to configure application logging: {exc}",
|
||||
)
|
||||
|
||||
return LoggingSetupResult(success=True, log_file_path=log_file_path)
|
||||
|
||||
@staticmethod
|
||||
def log_startup(logger: logging.Logger | None = None) -> None:
|
||||
(logger or logging.getLogger("VoicePTT")).info("VoicePTT startup")
|
||||
|
||||
@staticmethod
|
||||
def log_shutdown(logger: logging.Logger | None = None) -> None:
|
||||
(logger or logging.getLogger("VoicePTT")).info("VoicePTT shutdown")
|
||||
|
||||
@staticmethod
|
||||
def _parse_level(level_name: str) -> int:
|
||||
candidate = (level_name or DEFAULT_LOG_LEVEL).upper()
|
||||
level = logging.getLevelName(candidate)
|
||||
if isinstance(level, int):
|
||||
return level
|
||||
return logging.getLevelName(DEFAULT_LOG_LEVEL)
|
||||
|
||||
@staticmethod
|
||||
def _coerce_positive_int(value: int, default: int) -> int:
|
||||
try:
|
||||
coerced = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return coerced if coerced > 0 else default
|
||||
|
||||
@staticmethod
|
||||
def _coerce_non_negative_int(value: int, default: int) -> int:
|
||||
try:
|
||||
coerced = int(value)
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return coerced if coerced >= 0 else default
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
import pytest
|
||||
|
||||
from core.config_service import LoggingConfig
|
||||
from logging_ext.logging_service import LoggingService
|
||||
|
||||
|
||||
@contextmanager
|
||||
def workspace_root(name: str):
|
||||
root = Path.cwd() / "tests" / "unit" / name
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
yield root
|
||||
finally:
|
||||
shutil.rmtree(root, ignore_errors=True)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def preserve_root_logging_state():
|
||||
root = logging.getLogger()
|
||||
original_handlers = list(root.handlers)
|
||||
original_level = root.level
|
||||
try:
|
||||
yield root, original_handlers
|
||||
finally:
|
||||
for handler in list(root.handlers):
|
||||
root.removeHandler(handler)
|
||||
if handler not in original_handlers:
|
||||
handler.close()
|
||||
for handler in original_handlers:
|
||||
if handler not in root.handlers:
|
||||
root.addHandler(handler)
|
||||
root.setLevel(original_level)
|
||||
|
||||
|
||||
def test_initialize_creates_rotating_log_file_and_writes_messages() -> None:
|
||||
with workspace_root("logging_service_success") as logs_root:
|
||||
service = LoggingService()
|
||||
config = LoggingConfig(
|
||||
level="DEBUG",
|
||||
file_name="voice_ptt.log",
|
||||
rotation_bytes=1024,
|
||||
backup_count=2,
|
||||
)
|
||||
|
||||
with preserve_root_logging_state() as (root_logger, original_handlers):
|
||||
result = service.initialize(config, logs_root)
|
||||
|
||||
assert result.success is True
|
||||
assert result.log_file_path == logs_root / "voice_ptt.log"
|
||||
assert len(root_logger.handlers) == 1
|
||||
assert isinstance(root_logger.handlers[0], RotatingFileHandler)
|
||||
assert root_logger.level == logging.DEBUG
|
||||
assert not original_handlers or root_logger.handlers[0] not in original_handlers
|
||||
|
||||
root_logger.info("startup message")
|
||||
root_logger.handlers[0].flush()
|
||||
|
||||
assert result.log_file_path.exists()
|
||||
assert "startup message" in result.log_file_path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_initialize_returns_failure_when_log_directory_cannot_be_created() -> None:
|
||||
with workspace_root("logging_service_failure") as logs_root:
|
||||
blocked_path = logs_root / "voice_ptt.log"
|
||||
blocked_path.write_text("blocked", encoding="utf-8")
|
||||
|
||||
service = LoggingService()
|
||||
config = LoggingConfig(
|
||||
level="INFO",
|
||||
file_name="voice_ptt.log",
|
||||
rotation_bytes=1024,
|
||||
backup_count=1,
|
||||
)
|
||||
|
||||
with preserve_root_logging_state() as (root_logger, original_handlers):
|
||||
result = service.initialize(config, blocked_path)
|
||||
|
||||
assert result.success is False
|
||||
assert result.log_file_path == blocked_path / "voice_ptt.log"
|
||||
assert list(root_logger.handlers) == original_handlers
|
||||
assert result.error_message is not None
|
||||
assert "Unable to initialize log file" in result.error_message
|
||||
Loading…
Reference in New Issue