41 lines
1.9 KiB
Python
41 lines
1.9 KiB
Python
"""事件日志:状态跟踪、审计与前端时间线。"""
|
||
from __future__ import annotations
|
||
|
||
from sqlalchemy import desc, select
|
||
from sqlalchemy.orm import Session
|
||
|
||
from app.models import EventLog
|
||
from app.services import auth
|
||
|
||
LEVELS = {"debug": 10, "info": 20, "warn": 30, "error": 40}
|
||
|
||
|
||
def log_event(db: Session, action: str, *, project_id: int | None = None, shot_id: int | None = None,
|
||
task_id: int | None = None, message: str = "", level: str = "info",
|
||
entity_type: str = "", entity_id: int | None = None, data: dict | None = None,
|
||
actor: str = "", commit: bool = False) -> EventLog:
|
||
# actor 留空 = 自动归属到「当前登录用户」;守护线程/任务执行里没有请求上下文,
|
||
# 那时 auth.actor_name() 返回空串,落回 system,历史行为不变。
|
||
event = EventLog(project_id=project_id, shot_id=shot_id, task_id=task_id, level=level, action=action,
|
||
entity_type=entity_type, entity_id=entity_id, message=message[:4000],
|
||
data_json=data or {}, actor=actor or auth.actor_name() or "system")
|
||
db.add(event)
|
||
if commit:
|
||
db.commit()
|
||
else:
|
||
db.flush()
|
||
return event
|
||
|
||
|
||
def recent_events(db: Session, *, project_id: int | None = None, limit: int = 100,
|
||
level: str | None = None) -> list[dict]:
|
||
stmt = select(EventLog).order_by(desc(EventLog.id)).limit(limit)
|
||
if project_id is not None:
|
||
stmt = stmt.where(EventLog.project_id == project_id)
|
||
if level:
|
||
stmt = stmt.where(EventLog.level == level)
|
||
return [{"id": e.id, "project_id": e.project_id, "shot_id": e.shot_id, "task_id": e.task_id,
|
||
"level": e.level, "action": e.action, "entity_type": e.entity_type, "entity_id": e.entity_id,
|
||
"message": e.message, "data": e.data_json or {}, "actor": e.actor, "created_at": e.created_at}
|
||
for e in db.scalars(stmt).all()]
|