- get_app_dir(): project root in dev, exe dir in PyInstaller bundle - get_resource_path/get_config_path: paths under app dir - get_log_dir/get_output_dir: auto-create and return logs/ and output/ - Refactor log_service to use get_log_dir() instead of own __file__ calc Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
57 lines
1.7 KiB
Python
57 lines
1.7 KiB
Python
import logging
|
|
import os
|
|
from datetime import datetime
|
|
|
|
|
|
def setup_logging(log_dir=None):
|
|
"""Initialize file + console logging. Call once at application startup.
|
|
|
|
log_dir: str or Path to log directory. Defaults to <app_dir>/logs/ via
|
|
file_service.get_log_dir(). Falls back to console-only if the
|
|
directory cannot be created.
|
|
"""
|
|
if log_dir is None:
|
|
try:
|
|
from services.file_service import get_log_dir
|
|
log_dir = get_log_dir()
|
|
except OSError as exc:
|
|
_setup_console_only()
|
|
logging.getLogger(__name__).warning(
|
|
"Cannot create log directory: %s. Falling back to console only.", exc
|
|
)
|
|
return
|
|
else:
|
|
try:
|
|
os.makedirs(str(log_dir), exist_ok=True)
|
|
except OSError as exc:
|
|
_setup_console_only()
|
|
logging.getLogger(__name__).warning(
|
|
"Cannot create log directory %s: %s. Falling back to console only.", log_dir, exc
|
|
)
|
|
return
|
|
|
|
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
log_file = os.path.join(str(log_dir), "app_{}.log".format(timestamp))
|
|
|
|
formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")
|
|
|
|
root = logging.getLogger()
|
|
root.setLevel(logging.INFO)
|
|
|
|
fh = logging.FileHandler(log_file, encoding="utf-8")
|
|
fh.setFormatter(formatter)
|
|
root.addHandler(fh)
|
|
|
|
sh = logging.StreamHandler()
|
|
sh.setFormatter(formatter)
|
|
root.addHandler(sh)
|
|
|
|
logging.getLogger(__name__).info("Logging initialized. Log file: %s", log_file)
|
|
|
|
|
|
def _setup_console_only():
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s %(name)s %(levelname)s %(message)s",
|
|
)
|