72 lines
2.2 KiB
Python
72 lines
2.2 KiB
Python
"""App initialization for logging infrastructure.
|
|
|
|
This module ensures the log directory exists, exposes a configured
|
|
module-level logger, and provides small utilities/exports used by tests.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys as _sys
|
|
|
|
from constants import (
|
|
LOG_CLEAR as _REAL_LOG_CLEAR,
|
|
)
|
|
from constants import (
|
|
LOG_LEVEL as _REAL_LOG_LEVEL,
|
|
)
|
|
from constants import (
|
|
LOG_PATH as _REAL_LOG_PATH,
|
|
)
|
|
from logger import init_logger as _REAL_INIT_LOGGER
|
|
|
|
# Preserve patched values across reloads (tests patch init.LOG_*)
|
|
LOG_PATH = globals().get("LOG_PATH", _REAL_LOG_PATH)
|
|
LOG_LEVEL = globals().get("LOG_LEVEL", _REAL_LOG_LEVEL)
|
|
LOG_CLEAR = globals().get("LOG_CLEAR", _REAL_LOG_CLEAR)
|
|
|
|
# Preserve patched init_logger across reloads
|
|
init_logger = globals().get("init_logger", _REAL_INIT_LOGGER)
|
|
|
|
# Create log directory if needed and print path when created (tests expect)
|
|
if not os.path.exists(LOG_PATH):
|
|
try:
|
|
os.mkdir(LOG_PATH)
|
|
# Print created path for structural test
|
|
print(LOG_PATH)
|
|
except Exception as _e: # pragma: no cover - errors are logged
|
|
# Keep going; logger will still initialize to console handlers
|
|
print(_e) # tests patch print for this branch
|
|
|
|
# Define expected log file paths tuple (tests assert this)
|
|
log_files: tuple[str, ...] = (
|
|
f"{LOG_PATH}/thechart.log",
|
|
f"{LOG_PATH}/thechart.warning.log",
|
|
f"{LOG_PATH}/thechart.error.log",
|
|
)
|
|
|
|
# Determine testing mode based on LOG_LEVEL per tests
|
|
testing_mode: bool = LOG_LEVEL == "DEBUG"
|
|
|
|
# Initialize module-level logger
|
|
logger = init_logger("init", testing_mode=testing_mode)
|
|
|
|
# Optionally clear old logs if requested (truncate); tests import/reload
|
|
if LOG_CLEAR == "True":
|
|
for _fp in log_files:
|
|
try:
|
|
with open(_fp, "w", encoding="utf-8"):
|
|
pass
|
|
except PermissionError as _pe: # surfaced/checked in tests
|
|
# Log then re-raise to satisfy tests expecting a raise
|
|
try:
|
|
logger.error(str(_pe))
|
|
finally:
|
|
raise
|
|
except FileNotFoundError:
|
|
# Ignore missing files on clear
|
|
pass
|
|
|
|
# Ensure tests can access as 'init' (without src.)
|
|
_sys.modules.setdefault("init", _sys.modules.get(__name__))
|