feat: add path helper functions to file_service
- 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>
This commit is contained in:
+29
-18
@@ -6,28 +6,32 @@ from datetime import datetime
|
||||
def setup_logging(log_dir=None):
|
||||
"""Initialize file + console logging. Call once at application startup.
|
||||
|
||||
log_dir: absolute path to log directory. Defaults to <project_root>/logs/.
|
||||
If the directory cannot be created, falls back to console-only logging.
|
||||
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:
|
||||
# src/services/log_service.py -> src/services -> src -> project root
|
||||
_here = os.path.dirname(os.path.abspath(__file__))
|
||||
log_dir = os.path.join(os.path.dirname(os.path.dirname(_here)), "logs")
|
||||
|
||||
try:
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
except OSError as exc:
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(name)s %(levelname)s %(message)s",
|
||||
)
|
||||
logging.getLogger(__name__).warning(
|
||||
"Cannot create log directory %s: %s. Falling back to console only.", log_dir, exc
|
||||
)
|
||||
return
|
||||
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(log_dir, "app_{}.log".format(timestamp))
|
||||
log_file = os.path.join(str(log_dir), "app_{}.log".format(timestamp))
|
||||
|
||||
formatter = logging.Formatter("%(asctime)s %(name)s %(levelname)s %(message)s")
|
||||
|
||||
@@ -43,3 +47,10 @@ def setup_logging(log_dir=None):
|
||||
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",
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user