"""操作日志服务""" from typing import Optional from sqlalchemy.ext.asyncio import AsyncSession from ..models import OperationLog from ..utils.audited_write import get_audit_context, normalize_caller async def log_operation( db: AsyncSession, *, tenant_id: int, user_id: int, project_id: Optional[int], entity_type: str, entity_id: str, action: str, before_data: Optional[dict] = None, after_data: Optional[dict] = None, remark: Optional[str] = None, trace_id: Optional[str] = None, interface_path: Optional[str] = None, caller: Optional[str] = None, ) -> None: """记录操作日志,失败时不影响主流程。""" try: context = get_audit_context() resolved_trace = str(trace_id or context.trace_id or "").strip()[:64] or None resolved_interface = str(interface_path or context.interface_path or "").strip()[:255] or None resolved_caller = normalize_caller(caller or context.caller or "system") db.add( OperationLog( tenant_id=tenant_id, user_id=user_id, project_id=project_id, entity_type=entity_type, entity_id=entity_id, action=action, before_data=before_data, after_data=after_data, remark=remark, trace_id=resolved_trace, interface_path=resolved_interface, caller=resolved_caller, ) ) db.sync_session.info["_pmflow_audit_written"] = True except Exception: # 日志失败不阻断主交易 return