File size: 2,394 Bytes
76962bf cb505ff 76962bf cb505ff 76962bf cb505ff 76962bf cb505ff 76962bf cb505ff 76962bf cb505ff 76962bf cb505ff 76962bf cb505ff 76962bf cb505ff | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | import logging
import os
import sys
from src.utils import run_manager
def _debug_enabled():
"""Return whether verbose logging was requested for this process."""
env_value = os.getenv("DEBUG_LOGGING", "").strip().lower()
return "--debug" in sys.argv or env_value in {"1", "true", "yes", "on"}
def setup_logger(name, debug=None):
"""
Sets up a logger with a standard configuration that logs to the console,
the active run log file ('logs/run_<N>.log'), and mirrors to 'logs/app.log'.
Pass ``--debug`` to the application command, or set ``DEBUG_LOGGING=true``,
to enable DEBUG-level output.
"""
logger = logging.getLogger(name)
level = logging.DEBUG if (_debug_enabled() if debug is None else debug) else logging.INFO
logger.setLevel(level)
# If logger already has handlers, don't add more (to avoid duplicate logs).
if not logger.handlers:
run_number = run_manager.get_current_run_number()
run_log_path = run_manager.get_current_run_log_file()
logs_dir = os.path.dirname(run_log_path)
os.makedirs(logs_dir, exist_ok=True)
# Create formatters with run number
formatter = logging.Formatter(
f'%(asctime)s - [Run #{run_number}] - %(name)s - %(levelname)s - %(message)s'
)
# Console Handler
console_handler = logging.StreamHandler()
console_handler.setLevel(level)
console_handler.setFormatter(formatter)
logger.addHandler(console_handler)
# Run-specific File Handler
run_file_handler = logging.FileHandler(run_log_path, encoding='utf-8')
run_file_handler.setLevel(level)
run_file_handler.setFormatter(formatter)
logger.addHandler(run_file_handler)
# Legacy / general app.log File Handler in the same logs directory
app_log_path = os.path.join(logs_dir, "app.log")
app_file_handler = logging.FileHandler(app_log_path, encoding='utf-8')
app_file_handler.setLevel(level)
app_file_handler.setFormatter(formatter)
logger.addHandler(app_file_handler)
else:
# A module may have configured this logger before the debug flag was
# evaluated. Keep its existing handlers in sync with the logger level.
for handler in logger.handlers:
handler.setLevel(level)
return logger
|