feat: implement logging service with file output

- setup_logging() creates logs/ dir and writes timestamped log file
- format: asctime name levelname message
- falls back to console-only if log dir is not writable
- main.py now calls setup_logging() at startup and logs app name/version

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-15 16:33:33 +08:00
co-authored by Claude Sonnet 4.6
parent 7d941a03aa
commit 24d43db434
3 changed files with 60 additions and 15 deletions
+9 -1
View File
@@ -1,18 +1,26 @@
import logging
import sys
from PySide6.QtWidgets import QApplication
from app.main_window import MainWindow
from version import APP_NAME
from services.log_service import setup_logging
from version import APP_NAME, APP_VERSION
logger = logging.getLogger(__name__)
def main():
setup_logging()
logger.info("Application starting: %s %s", APP_NAME, APP_VERSION)
app = QApplication(sys.argv)
app.setApplicationName(APP_NAME)
window = MainWindow()
window.show()
logger.info("Main window displayed")
return app.exec()
+42 -5
View File
@@ -1,8 +1,45 @@
import logging
import os
from datetime import datetime
def setup_logging():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
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.
"""
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
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
log_file = os.path.join(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)