AuditService.java
1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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;
}
}