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