更新
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace app\mcp\service;
|
||||
|
||||
use think\facade\Db;
|
||||
use think\facade\Log;
|
||||
|
||||
/**
|
||||
* AI 数据访问日志:记录谁、通过哪个行知任务、查了哪个资源、返回了哪些记录。
|
||||
* 参数先脱敏再写入;写日志失败不影响查询本身。
|
||||
*/
|
||||
class AuditLogger
|
||||
{
|
||||
public static function log(array $entry): void
|
||||
{
|
||||
try {
|
||||
$arguments = $entry['arguments'] ?? null;
|
||||
if (is_array($arguments)) {
|
||||
$arguments = json_encode(FieldPolicy::maskText($arguments), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
||||
}
|
||||
Db::name('ai_access_log')->insert([
|
||||
'grant_id' => (int) ($entry['grant_id'] ?? 0),
|
||||
'admin_id' => (int) ($entry['admin_id'] ?? 0),
|
||||
'tool' => mb_substr((string) ($entry['tool'] ?? ''), 0, 64),
|
||||
'resource' => mb_substr((string) ($entry['resource'] ?? ''), 0, 128),
|
||||
'arguments' => $arguments === null ? null : mb_substr((string) $arguments, 0, 2000),
|
||||
'result_rows' => max(0, (int) ($entry['result_rows'] ?? 0)),
|
||||
'record_ids' => mb_substr(implode(',', array_slice((array) ($entry['record_ids'] ?? []), 0, 200)), 0, 1000),
|
||||
'status' => mb_substr((string) ($entry['status'] ?? 'ok'), 0, 16),
|
||||
'message' => mb_substr((string) ($entry['message'] ?? ''), 0, 255),
|
||||
'duration_ms' => max(0, (int) ($entry['duration_ms'] ?? 0)),
|
||||
'client_task_id' => mb_substr(preg_replace('/[^\w.\-:]/', '', (string) ($entry['client_task_id'] ?? '')), 0, 64),
|
||||
'ip' => mb_substr((string) ($entry['ip'] ?? ''), 0, 45),
|
||||
'create_time' => time(),
|
||||
]);
|
||||
if (mt_rand(1, 500) === 1) {
|
||||
self::purge();
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('[ai_mcp] 写访问日志失败: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 清理超过保留期的日志(按需触发,每次最多 5000 行) */
|
||||
public static function purge(): int
|
||||
{
|
||||
$before = time() - McpConfig::logRetentionDays() * 86400;
|
||||
return (int) Db::name('ai_access_log')->where('create_time', '<', $before)->limit(5000)->delete();
|
||||
}
|
||||
|
||||
/** 从结果行里取记录 ID,用于回答“谁看过哪个患者” */
|
||||
public static function recordIds(array $rows): array
|
||||
{
|
||||
$ids = [];
|
||||
foreach ($rows as $row) {
|
||||
if (is_array($row) && isset($row['id']) && is_scalar($row['id'])) {
|
||||
$ids[] = (string) $row['id'];
|
||||
}
|
||||
}
|
||||
return $ids;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user