diff --git a/src/livesub/app.py b/src/livesub/app.py index f4dc749..b759c81 100644 --- a/src/livesub/app.py +++ b/src/livesub/app.py @@ -26,10 +26,12 @@ def setup_logging(verbose: bool = False, to_file: bool = True) -> None: BufferHandler(BUFFER), ] if to_file: + path = user_data_dir() / "livesub.log" with contextlib.suppress(OSError): - handlers.append( - logging.FileHandler(user_data_dir() / "livesub.log", encoding="utf-8") - ) + # 이어 쓰는 파일이라 이전 실행 기록이 앞에 있다. 이번 실행분만 내보낸다. + offset = path.stat().st_size if path.exists() else 0 + handlers.append(logging.FileHandler(path, encoding="utf-8")) + BUFFER.attach_file(path, offset) logging.basicConfig( level=logging.DEBUG if verbose else logging.INFO, format="%(asctime)s %(levelname)-7s %(name)s: %(message)s", diff --git a/src/livesub/log_buffer.py b/src/livesub/log_buffer.py index c121f2f..a862bd8 100644 --- a/src/livesub/log_buffer.py +++ b/src/livesub/log_buffer.py @@ -1,8 +1,12 @@ -"""실행 중 로그를 메모리에 모아 두는 곳. '로그' 화면이 여기서 읽는다. +"""실행 중 로그를 모아 두는 곳. '로그' 화면이 여기서 읽는다. `livesub.log` 파일만으로는 사용자가 찾아서 보내기 어렵다. 저장 위치를 직접 -열어야 하고, 실행 중에는 파일이 잠겨 있을 때도 있다. 그래서 같은 내용을 -메모리에도 쌓아 두고 화면에서 바로 복사·저장하게 한다. +열어야 하고, 이전 실행 기록까지 섞여 있다. 그래서 화면에서 바로 복사·저장하게 한다. + +화면에 보이는 줄(`lines`)은 메모리를 아끼려고 최근 것만 들고 있다. 복사·저장하는 +내용(`full_text`)은 그와 따로, 이번 실행에서 `livesub.log` 에 쓴 부분 전체를 +파일에서 다시 읽는다. 오래 켜 두면 맨 앞의 GPU 준비·모델 로드 기록이 화면에서는 +밀려나는데, 원인을 찾을 때 가장 필요한 게 바로 그 부분이다. """ from __future__ import annotations @@ -11,6 +15,7 @@ import logging import threading from collections import deque from collections.abc import Callable +from pathlib import Path #: 화면에 들고 있을 최대 줄 수. 한 줄 200바이트로 잡아도 1MB 남짓이다. MAX_RECORDS = 5000 @@ -25,6 +30,11 @@ class LogBuffer: self._lines: deque[str] = deque(maxlen=limit) self._listeners: list[Listener] = [] self._lock = threading.Lock() + #: 이번 실행의 로그 파일과, 이번 실행이 쓰기 시작한 위치(바이트) + self._file: Path | None = None + self._file_offset = 0 + #: 로그 파일을 열기 전(저장 위치를 고르기 전)에 남은 줄. 파일에는 없다. + self._before_file: list[str] = [] def append(self, line: str) -> None: with self._lock: @@ -41,9 +51,34 @@ class LogBuffer: return "\n".join(self.lines()) def clear(self) -> None: + """화면용 줄만 비운다. 복사·저장할 전체 기록은 그대로 둔다.""" with self._lock: self._lines.clear() + def attach_file(self, path: Path, offset: int) -> None: + """이번 실행이 `path` 의 `offset` 바이트부터 로그를 쓴다고 알려 준다.""" + with self._lock: + if self._file is None: + self._before_file = list(self._lines) + self._file = path + self._file_offset = offset + + def full_text(self) -> str: + """이번 실행의 로그 전체. 파일을 못 읽으면 화면에 있는 만큼이라도 준다.""" + with self._lock: + path, offset, before = self._file, self._file_offset, list(self._before_file) + if path is None: + return self.text() + try: + with open(path, "rb") as f: + f.seek(offset) + raw = f.read().decode("utf-8", errors="replace") + except OSError: + return self.text() + # Windows 에서는 FileHandler 가 텍스트 모드라 줄 끝이 \r\n 이다. + written = raw.replace("\r\n", "\n").rstrip("\n") + return "\n".join([*before, written] if written else before) + def subscribe(self, listener: Listener) -> None: """새 줄이 들어올 때마다 불린다. 로그를 남긴 스레드에서 불리는 점에 주의.""" with self._lock: diff --git a/src/livesub/ui/pages/log_page.py b/src/livesub/ui/pages/log_page.py index 29c3eeb..1d41271 100644 --- a/src/livesub/ui/pages/log_page.py +++ b/src/livesub/ui/pages/log_page.py @@ -57,7 +57,9 @@ class LogPage(QWidget): self.save_button = QPushButton("파일로 저장") self.save_button.clicked.connect(self._save_dialog) self.clear_button = QPushButton("화면 비우기") - self.clear_button.setToolTip("이 화면만 비웁니다. livesub.log 파일은 그대로 둡니다.") + self.clear_button.setToolTip( + "이 화면만 비웁니다. 복사·저장에는 이번 실행 기록이 전부 그대로 들어갑니다." + ) self.clear_button.clicked.connect(self.clear) for button in (self.copy_button, self.save_button, self.clear_button): row.addWidget(button) @@ -102,11 +104,12 @@ class LogPage(QWidget): f"저장 위치 {user_data_dir()} · 기록 시각 {datetime.now():%Y-%m-%d %H:%M:%S}", "-" * 60, ] - return "\n".join(header) + "\n" + self.buffer.text() + "\n" + return "\n".join(header) + "\n" + self.buffer.full_text() + "\n" def copy_to_clipboard(self) -> None: - QGuiApplication.clipboard().setText(self.report()) - self.notice.setText(f"{len(self.buffer.lines())}줄을 복사했습니다") + text = self.report() + QGuiApplication.clipboard().setText(text) + self.notice.setText(f"{text.count(chr(10))}줄을 복사했습니다") def save_to(self, path: str) -> None: with open(path, "w", encoding="utf-8") as f: diff --git a/tests/test_log_buffer.py b/tests/test_log_buffer.py new file mode 100644 index 0000000..358e470 --- /dev/null +++ b/tests/test_log_buffer.py @@ -0,0 +1,45 @@ +"""'로그' 화면의 복사·저장이 화면 줄 수 제한과 상관없이 이번 실행 기록 전체를 담는지.""" + +from __future__ import annotations + +import logging + +import pytest + +import livesub.app as app +from livesub.log_buffer import LogBuffer + + +@pytest.fixture +def small_buffer(tmp_path, monkeypatch): + buffer = LogBuffer(limit=3) + monkeypatch.setattr(app, "BUFFER", buffer) + monkeypatch.setattr(app, "user_data_dir", lambda: tmp_path) + yield buffer + root = logging.getLogger() + for handler in list(root.handlers): + root.removeHandler(handler) + handler.close() + + +def test_export_keeps_whole_run_beyond_screen_limit(small_buffer, tmp_path): + (tmp_path / "livesub.log").write_text("지난 실행 기록\n", encoding="utf-8") + log = logging.getLogger("livesub.test") + + app.setup_logging(to_file=False) # 저장 위치를 고르기 전 + log.info("저장 위치 고르기 전") + app.setup_logging() + for i in range(10): + log.info("줄 %d", i) + + assert len(small_buffer.lines()) == 3 # 화면은 최근 것만 + exported = small_buffer.full_text() + assert "저장 위치 고르기 전" in exported + assert all(f"줄 {i}" in exported for i in range(10)) + assert "지난 실행 기록" not in exported + + +def test_export_falls_back_to_screen_lines_without_log_file(small_buffer): + app.setup_logging(to_file=False) + logging.getLogger("livesub.test").warning("파일 없음") + assert "파일 없음" in small_buffer.full_text()