package com.xly.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; /** * 业务审计:写操作 / SQL 的不可变留痕(谁、何时、什么动作、目标、结果)。 * 记账失败绝不阻断主流程(审计是旁路)。 */ @Service public class AuditService { private static final Logger log = LoggerFactory.getLogger(AuditService.class); private final JdbcTemplate jdbc; public AuditService(JdbcTemplate jdbc) { this.jdbc = jdbc; } public void log(String userId, String conversationId, String action, String target, String detail, boolean ok, String resultMsg) { try { jdbc.update( "INSERT INTO ai_audit_log(tTime,sUserId,sConversationId,sAction,sTarget,sDetail,sResult,sResultMsg) " + "VALUES(NOW(),?,?,?,?,?,?,?)", userId, conversationId, action, trunc(target, 200), trunc(detail, 60000), ok ? "ok" : "fail", trunc(resultMsg, 500)); } catch (Exception e) { log.warn("audit write failed (action={}): {}", action, e.getMessage()); } } private static String trunc(String s, int max) { if (s == null) { return null; } return s.length() > max ? s.substring(0, max) : s; } }