47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
"""Per-connection session log on disk (already redacted lines only)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import re
|
|
from pathlib import Path
|
|
|
|
from .logline import LogLine
|
|
|
|
SESSIONS_DIR = Path.home() / "KotaTechnicianTool" / "sessions"
|
|
|
|
|
|
class SessionLog:
|
|
def __init__(self, root: Path = SESSIONS_DIR):
|
|
self.root = root
|
|
self.path: Path | None = None
|
|
self._fh = None
|
|
|
|
def start(self, device_hint: str) -> Path:
|
|
self.stop()
|
|
self.root.mkdir(parents=True, exist_ok=True)
|
|
stamp = dt.datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
safe = re.sub(r"[^A-Za-z0-9]+", "", device_hint)[:20] or "board"
|
|
self.path = self.root / f"session_{stamp}_{safe}.log"
|
|
self._fh = self.path.open("a", encoding="utf-8", newline="\n")
|
|
return self.path
|
|
|
|
def write(self, line: LogLine) -> None:
|
|
if self._fh is None:
|
|
return
|
|
ts = dt.datetime.fromtimestamp(line.host_time).strftime("%H:%M:%S.%f")[:-3]
|
|
self._fh.write(f"[{ts}] {line.text}\n")
|
|
self._fh.flush()
|
|
|
|
def write_report(self, text: str) -> None:
|
|
"""Append the diagnosis at the end of the session (for the firmware team)."""
|
|
if self._fh is None:
|
|
return
|
|
self._fh.write("\n===== Diagnosis at end of session =====\n" + text + "\n")
|
|
self._fh.flush()
|
|
|
|
def stop(self) -> None:
|
|
if self._fh is not None:
|
|
self._fh.close()
|
|
self._fh = None
|