from fastapi import Request from sqlalchemy.ext.asyncio import AsyncSession from yuxi.storage.postgres.manager import pg_manager from yuxi.storage.postgres.models_business import OperationLog from yuxi.utils import logger async def log_operation( db: AsyncSession, user_id: int | None, operation: str, details: str | None = None, request: Request | None = None, ) -> None: """记录操作日志。 使用独立会话写入日志,避免日志写入失败污染业务会话的事务状态。 ``db`` 参数保留以保持与现有调用方兼容,但实际写入在独立会话中完成。 """ try: ip_address = request.client.host if request and request.client else None async with pg_manager.get_async_session_context() as session: session.add( OperationLog( user_id=user_id, operation=operation, details=details, ip_address=ip_address, ) ) except Exception as exc: logger.warning(f"操作日志写入失败(不影响主流程): {operation}, user={user_id}, error={exc}")