182 lines
6.0 KiB
Python
182 lines
6.0 KiB
Python
"""运行状态与日志。运行结果持久化到账号目录 runtime.json,日志同时写文件与内存环形缓冲。
|
|
|
|
v0.4 按账号分权:日志路由器会根据行内的 [账号ID] 前缀(无前缀时回退读线程当前账号)
|
|
把日志同步路由进对应账号的环形缓冲,`recent_account_logs()` 只返回该账号自己的日志。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import re
|
|
import threading
|
|
from collections import deque
|
|
from pathlib import Path
|
|
|
|
from . import accounts
|
|
from .config import DATA_DIR, account_dir, DEFAULT_ACCOUNT_ID
|
|
|
|
LOG_DIR = DATA_DIR / "logs"
|
|
|
|
# 行内账号标识:[default] 或 [acc_xxxxxxxx](与服务端所有 logger 调用一致)
|
|
_ACCOUNT_RE = re.compile(r"\[(default|acc_[0-9a-f]{8})\]")
|
|
|
|
|
|
def runtime_path(account_id: str | None = None) -> Path:
|
|
return account_dir(account_id) / "runtime.json"
|
|
|
|
|
|
_lock = threading.Lock()
|
|
_ring_lock = threading.Lock()
|
|
_ring: deque[str] = deque(maxlen=600)
|
|
_account_rings: dict[str, deque[str]] = {} # account_id -> 该账号专属日志缓冲
|
|
|
|
|
|
def _default() -> dict:
|
|
return {"session_status": "unknown", "running": False, "last_run": None, "history": []}
|
|
|
|
|
|
def load_runtime(account_id: str | None = None) -> dict:
|
|
rt = _default()
|
|
rp = runtime_path(account_id)
|
|
if rp.exists():
|
|
try:
|
|
data = json.loads(rp.read_text(encoding="utf-8"))
|
|
if isinstance(data, dict):
|
|
rt.update(data)
|
|
except Exception:
|
|
pass
|
|
return rt
|
|
|
|
|
|
def _save(rt: dict, account_id: str | None = None) -> None:
|
|
with _lock:
|
|
d = account_dir(account_id)
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
rp = runtime_path(account_id)
|
|
rp.write_text(json.dumps(rt, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
|
|
|
|
def set_running(value: bool, account_id: str | None = None) -> None:
|
|
rt = load_runtime(account_id)
|
|
rt["running"] = bool(value)
|
|
_save(rt, account_id)
|
|
|
|
|
|
def record_run(result: dict, account_id: str | None = None) -> None:
|
|
rt = load_runtime(account_id)
|
|
rt["last_run"] = result
|
|
history = rt.get("history", [])
|
|
history.insert(0, result)
|
|
rt["history"] = history[:30]
|
|
|
|
if result.get("logged_out"):
|
|
rt["session_status"] = "expired"
|
|
elif result.get("ok") and not result.get("failed"):
|
|
rt["session_status"] = "ok"
|
|
elif result.get("ok"):
|
|
rt["session_status"] = "partial"
|
|
elif not result.get("failed"):
|
|
rt["session_status"] = "ok"
|
|
else:
|
|
rt["session_status"] = "failed"
|
|
_save(rt, account_id)
|
|
|
|
|
|
def record_contacts(data: dict, account_id: str | None = None) -> None:
|
|
rt = load_runtime(account_id)
|
|
rt["contacts"] = data.get("names", [])
|
|
rt["contacts_at"] = data.get("at")
|
|
rt["contacts_error"] = data.get("error")
|
|
_save(rt, account_id)
|
|
|
|
|
|
def update_runtime(account_id: str | None = None, **fields) -> None:
|
|
rt = load_runtime(account_id)
|
|
rt.update(fields)
|
|
_save(rt, account_id)
|
|
|
|
|
|
def record_harvest(harvest_last: dict | None, account_id: str | None = None) -> None:
|
|
"""持久化最近一次 creator 采集摘要,服务重启后不丢(台账数据本身持久化不受影响)。"""
|
|
rt = load_runtime(account_id)
|
|
if harvest_last is None:
|
|
rt.pop("harvest_last", None)
|
|
else:
|
|
rt["harvest_last"] = harvest_last
|
|
_save(rt, account_id)
|
|
|
|
|
|
def load_harvest_last(account_id: str | None = None) -> dict | None:
|
|
"""读取持久化的采集摘要;无记录返回 None。"""
|
|
return load_runtime(account_id).get("harvest_last")
|
|
|
|
|
|
class RoutingHandler(logging.Handler):
|
|
"""统一日志路由:全局环形缓冲 + 按账号环形缓冲。
|
|
|
|
行内带 [账号ID] 前缀的日志按前缀归入该账号;不带前缀的回退到
|
|
线程当前账号(accounts.set_current_account,由各工作线程设置),
|
|
保证 automation 内部的发送细节日志也能出现在对应账号的日志页。
|
|
"""
|
|
|
|
def emit(self, record: logging.LogRecord) -> None:
|
|
try:
|
|
line = self.format(record)
|
|
m = _ACCOUNT_RE.search(line)
|
|
aid = m.group(1) if m else (accounts.current_account() or "")
|
|
with _ring_lock:
|
|
_ring.append(line)
|
|
if aid:
|
|
_account_rings.setdefault(aid, deque(maxlen=600)).append(line)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def setup_logging() -> logging.Logger:
|
|
logger = logging.getLogger("douyin-cloud-streak")
|
|
if logger.handlers:
|
|
return logger
|
|
logger.setLevel(logging.INFO)
|
|
fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
|
|
|
|
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
|
fh = logging.FileHandler(LOG_DIR / "app.log", encoding="utf-8")
|
|
fh.setFormatter(fmt)
|
|
logger.addHandler(fh)
|
|
|
|
sh = logging.StreamHandler()
|
|
sh.setFormatter(fmt)
|
|
logger.addHandler(sh)
|
|
|
|
rh = RoutingHandler()
|
|
rh.setFormatter(fmt)
|
|
logger.addHandler(rh)
|
|
return logger
|
|
|
|
|
|
def recent_logs(n: int = 300) -> list[str]:
|
|
return list(_ring)[-n:]
|
|
|
|
|
|
def recent_account_logs(account_id: str, n: int = 300) -> list[str]:
|
|
"""仅返回指定账号的日志(其他账号与全局启动日志不可见)。
|
|
|
|
内存缓冲为空时(如服务刚重启),回退扫描全局日志文件尾部按 [账号ID] 过滤。
|
|
"""
|
|
with _ring_lock:
|
|
lines = list(_account_rings.get(account_id, ()))
|
|
if not lines:
|
|
try:
|
|
log_file = LOG_DIR / "app.log"
|
|
if log_file.exists():
|
|
with log_file.open("r", encoding="utf-8", errors="replace") as f:
|
|
f.seek(0, 2)
|
|
size = f.tell()
|
|
f.seek(max(0, size - 512 * 1024))
|
|
tail = f.read().splitlines()
|
|
lines = [l for l in tail if f"[{account_id}]" in l]
|
|
except OSError:
|
|
lines = []
|
|
return lines[-n:]
|