ForcePilot/backend/package/yuxi/services/operation_log_service.py

33 lines
1.2 KiB
Python
Raw Normal View History

2026-05-29 22:19:58 +08:00
from fastapi import Request
from sqlalchemy.ext.asyncio import AsyncSession
from yuxi.storage.postgres.manager import pg_manager
2026-05-29 22:19:58 +08:00
from yuxi.storage.postgres.models_business import OperationLog
from yuxi.utils import logger
2026-05-29 22:19:58 +08:00
async def log_operation(
db: AsyncSession,
user_id: int | None,
operation: str,
details: str | None = None,
request: Request | None = None,
) -> None:
"""记录操作日志。
使用独立会话写入日志避免日志写入失败污染业务会话的事务状态
``db`` 参数保留以保持与现有调用方兼容但实际写入在独立会话中完成
"""
2026-05-29 22:19:58 +08:00
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}")