优化(登录任务): 逐账号日志改为全量采集,并收口不可重试失败
- loguru sink 按线程采集 core/ 登录步骤日志(代理、极验、邮箱取码等) - 单任务最多 300 条,溢出优先丢 DEBUG,消息截断 1200 字 - 日志改用独立短事务写入,避免与登录事务互相等锁 - 日志弹窗显示级别/时间/模块,支持复制全部 - 必须绑定手机号改为不可重试终态,不再空转 20 轮 - 邮箱验证码超时最多重试 2 次,避免单账号拖 20 分钟
This commit is contained in:
@@ -42,6 +42,99 @@ from .login_quota_service import (
|
||||
from .proxy_service import build_proxy_runtime
|
||||
from .task_runtime import TaskLane, submit
|
||||
|
||||
# ── 逐账号全量日志 ────────────────────────────────────────────────
|
||||
# core/ 里的登录实现直接用 loguru 打日志(步骤 1~7、代理预检、极验、邮箱取码…),
|
||||
# 不经过 LoginBatchRunner。页面要看的「这个账号到底卡在哪一步」恰恰就在那些
|
||||
# 记录里,所以这里挂一个 loguru sink,按线程把日志归到当前登录任务上。
|
||||
_LOG_CONTEXT = threading.local()
|
||||
_TASK_LOG_SINK_ID: int | None = None
|
||||
_TASK_LOG_SINK_LOCK = threading.Lock()
|
||||
# 单任务最多保留条数;超出后优先丢 DEBUG,避免把关键步骤挤掉。
|
||||
TASK_LOG_LIMIT = 300
|
||||
TASK_LOG_MESSAGE_LIMIT = 1200
|
||||
_TASK_LOG_BATCH_PREFIX = "[登录批次 "
|
||||
|
||||
|
||||
def _append_task_log(level: str, message: str, module: str = "") -> None:
|
||||
task_id = int(getattr(_LOG_CONTEXT, "task_id", 0) or 0)
|
||||
if not task_id:
|
||||
return
|
||||
text = str(message or "").strip()
|
||||
if not text:
|
||||
return
|
||||
# 批次级前缀对单账号日志没有意义,这里剥掉。
|
||||
if text.startswith(_TASK_LOG_BATCH_PREFIX):
|
||||
end = text.find("] ")
|
||||
if end > 0:
|
||||
text = text[end + 2 :].strip()
|
||||
logs = getattr(_LOG_CONTEXT, "logs", None)
|
||||
if logs is None:
|
||||
logs = []
|
||||
_LOG_CONTEXT.logs = logs
|
||||
logs.append(
|
||||
{
|
||||
"level": level,
|
||||
"message": text[:TASK_LOG_MESSAGE_LIMIT],
|
||||
"module": module,
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
)
|
||||
if len(logs) > TASK_LOG_LIMIT:
|
||||
for index, item in enumerate(logs):
|
||||
if item.get("level") == "debug":
|
||||
del logs[index]
|
||||
break
|
||||
else:
|
||||
del logs[0]
|
||||
|
||||
|
||||
def _task_log_sink(message: Any) -> None:
|
||||
record = getattr(message, "record", None)
|
||||
if record is None:
|
||||
return
|
||||
_append_task_log(
|
||||
str(record["level"].name or "info").lower(),
|
||||
str(record["message"] or ""),
|
||||
str((record.get("name") or "").split(".")[-1]),
|
||||
)
|
||||
|
||||
|
||||
def _install_task_log_sink() -> None:
|
||||
"""全局只挂一个 sink;重复构造 runner 不会重复记录。"""
|
||||
global _TASK_LOG_SINK_ID
|
||||
if _TASK_LOG_SINK_ID is not None:
|
||||
return
|
||||
with _TASK_LOG_SINK_LOCK:
|
||||
if _TASK_LOG_SINK_ID is not None:
|
||||
return
|
||||
_TASK_LOG_SINK_ID = logger.add(
|
||||
_task_log_sink,
|
||||
level="DEBUG",
|
||||
format="{message}",
|
||||
enqueue=False,
|
||||
backtrace=False,
|
||||
diagnose=False,
|
||||
)
|
||||
|
||||
|
||||
def _persist_task_logs(task_id: int, logs: list[dict[str, Any]]) -> None:
|
||||
"""用独立短事务写日志,避免和登录事务互相影响。"""
|
||||
if not logs:
|
||||
return
|
||||
session = WorkerSessionLocal()
|
||||
try:
|
||||
task = session.query(LoginTask).filter(LoginTask.id == task_id).first()
|
||||
if task is None:
|
||||
return
|
||||
task.logs = logs[-TASK_LOG_LIMIT:]
|
||||
session.commit()
|
||||
except Exception: # noqa: BLE001 - 日志落库失败不能掩盖登录结果
|
||||
session.rollback()
|
||||
logger.exception("保存登录账号日志失败: task_id={}", task_id)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
CHECK_STATUS_MESSAGES = {
|
||||
"account_cancelled": "账号已注销",
|
||||
"password_wrong": "账号密码错误",
|
||||
@@ -368,8 +461,9 @@ class LoginBatchRunner:
|
||||
self._stop = threading.Event()
|
||||
self._counter_lock = threading.Lock()
|
||||
self._completed = 0
|
||||
# 每个登录线程独立收集当前账号日志;批次级日志不写入账号任务。
|
||||
self._log_context = threading.local()
|
||||
# 逐账号日志走模块级 loguru sink(见文件头 _LOG_CONTEXT),
|
||||
# 这里只保证 sink 已挂上。
|
||||
_install_task_log_sink()
|
||||
|
||||
# 共享代理获取器(无池,每次取新代理)
|
||||
self._proxy_runtime = build_proxy_runtime(
|
||||
@@ -434,21 +528,8 @@ class LoginBatchRunner:
|
||||
worker_db.close()
|
||||
|
||||
def _push_log(self, level: str, message: str):
|
||||
if message:
|
||||
task_id = int(getattr(self._log_context, "task_id", 0) or 0)
|
||||
if task_id:
|
||||
logs = getattr(self._log_context, "logs", None)
|
||||
if logs is None:
|
||||
logs = []
|
||||
self._log_context.logs = logs
|
||||
logs.append(
|
||||
{
|
||||
"level": level,
|
||||
"message": message,
|
||||
"at": datetime.now(UTC).isoformat(),
|
||||
}
|
||||
)
|
||||
# 即使没有页面实时日志,也要保留批次进度到 app.log,便于排查卡点。
|
||||
# 逐账号日志由模块级 loguru sink 统一收集(含 core/ 的步骤日志);
|
||||
# 这里只负责 app.log、页面实时队列和外部 log_sink。
|
||||
if message:
|
||||
log_level = (
|
||||
level
|
||||
@@ -496,8 +577,8 @@ class LoginBatchRunner:
|
||||
task = worker_db.query(LoginTask).filter(LoginTask.id == task_id).first()
|
||||
if not task:
|
||||
return
|
||||
self._log_context.task_id = int(task.id)
|
||||
self._log_context.logs = []
|
||||
_LOG_CONTEXT.task_id = int(task.id)
|
||||
_LOG_CONTEXT.logs = []
|
||||
# CK、健康与重登状态都挂在账号上;登录记录只是一次尝试的历史。
|
||||
account = task.account
|
||||
|
||||
@@ -703,17 +784,13 @@ class LoginBatchRunner:
|
||||
worker_db.commit()
|
||||
|
||||
finally:
|
||||
logs = list(getattr(self._log_context, "logs", []) or [])
|
||||
if task is not None and logs:
|
||||
try:
|
||||
task.logs = logs[-300:]
|
||||
worker_db.commit()
|
||||
except Exception: # noqa: BLE001 - 日志落库失败不能掩盖登录结果
|
||||
worker_db.rollback()
|
||||
logger.exception("保存登录账号日志失败: task_id={}", task_id)
|
||||
self._log_context.task_id = 0
|
||||
self._log_context.logs = []
|
||||
logs = list(getattr(_LOG_CONTEXT, "logs", []) or [])
|
||||
_LOG_CONTEXT.task_id = 0
|
||||
_LOG_CONTEXT.logs = []
|
||||
# 先关会话释放行锁,再用独立短事务写日志;反过来会在异常路径上
|
||||
# 自己堵自己(同一行 UPDATE 等锁 50 秒)。
|
||||
worker_db.close()
|
||||
_persist_task_logs(task_id, logs)
|
||||
|
||||
def run(self):
|
||||
"""在线程中执行批量登录。"""
|
||||
|
||||
@@ -477,6 +477,7 @@ export interface SupportUserItem {
|
||||
export interface LoginTaskLogItem {
|
||||
level: string;
|
||||
message: string;
|
||||
module?: string;
|
||||
at?: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1164,37 +1164,71 @@ export default function LoginTasksPage() {
|
||||
<Modal
|
||||
title={logTask ? `登录日志 · ${logTask.account_username}` : '登录日志'}
|
||||
open={Boolean(logTask)}
|
||||
footer={null}
|
||||
width={760}
|
||||
width={860}
|
||||
onCancel={() => setLogTask(null)}
|
||||
footer={[
|
||||
<Button
|
||||
key="copy"
|
||||
disabled={logItems.length === 0}
|
||||
onClick={() => {
|
||||
const text = logItems
|
||||
.map((item) => `${item.at ? formatTime(item.at) : ''} [${item.level || 'info'}] ${item.message}`)
|
||||
.join('\n');
|
||||
void navigator.clipboard
|
||||
?.writeText(text)
|
||||
.then(() => message.success(`已复制 ${logItems.length} 条日志`))
|
||||
.catch(() => message.error('复制失败,请手动选择文本'));
|
||||
}}
|
||||
>
|
||||
复制全部
|
||||
</Button>,
|
||||
<Button key="close" type="primary" onClick={() => setLogTask(null)}>
|
||||
关闭
|
||||
</Button>,
|
||||
]}
|
||||
>
|
||||
{logsLoading ? (
|
||||
<div style={{ minHeight: 120, display: 'grid', placeItems: 'center' }}>
|
||||
<Spin />
|
||||
</div>
|
||||
) : logItems.length === 0 ? (
|
||||
<Text type="secondary">暂无日志;任务完成后会写入本次登录尝试的日志。</Text>
|
||||
<Text type="secondary">
|
||||
暂无日志。逐账号日志在本次登录尝试结束后写入;旧的登录任务不会再补。
|
||||
</Text>
|
||||
) : (
|
||||
<div style={{ maxHeight: '62vh', overflow: 'auto', display: 'grid', gap: 8 }}>
|
||||
{logItems.map((item, index) => (
|
||||
<div
|
||||
key={`${item.at || ''}-${index}`}
|
||||
style={{
|
||||
padding: '8px 10px',
|
||||
border: `1px solid ${token.colorBorderSecondary}`,
|
||||
borderRadius: 6,
|
||||
}}
|
||||
>
|
||||
<Space size={6} style={{ marginBottom: 4 }}>
|
||||
<Tag color={item.level === 'error' ? 'red' : item.level === 'warning' ? 'orange' : item.level === 'success' ? 'green' : 'blue'}>
|
||||
{item.level || 'info'}
|
||||
</Tag>
|
||||
{item.at ? <Text type="secondary" style={{ fontSize: 12 }}>{formatTime(item.at)}</Text> : null}
|
||||
</Space>
|
||||
<div style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{item.message}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>
|
||||
共 {logItems.length} 条,包含代理预检、极验、登录步骤和邮箱取码等完整过程。
|
||||
</Text>
|
||||
<div style={{ maxHeight: '58vh', overflow: 'auto', display: 'grid', gap: 6, marginTop: 8 }}>
|
||||
{logItems.map((item, index) => (
|
||||
<div
|
||||
key={`${item.at || ''}-${index}`}
|
||||
style={{
|
||||
padding: '6px 10px',
|
||||
border: `1px solid ${token.colorBorderSecondary}`,
|
||||
borderRadius: 6,
|
||||
background: item.level === 'error' ? token.colorErrorBg : undefined,
|
||||
}}
|
||||
>
|
||||
<Space size={6} style={{ marginBottom: 2 }}>
|
||||
<Tag color={item.level === 'error' ? 'red' : item.level === 'warning' ? 'orange' : item.level === 'success' ? 'green' : item.level === 'debug' ? 'default' : 'blue'}>
|
||||
{item.level || 'info'}
|
||||
</Tag>
|
||||
{item.at ? (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{formatTime(item.at)}</Text>
|
||||
) : null}
|
||||
{item.module ? (
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>{item.module}</Text>
|
||||
) : null}
|
||||
</Space>
|
||||
<div style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word', fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 12 }}>
|
||||
{item.message}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user