Files

72 lines
2.5 KiB
PHP

<?php
namespace app\queue\redis;
use support\Db;
use support\Log;
use Webman\RedisQueue\Consumer;
class AuditLog implements Consumer
{
// 要消费的队列名
public $queue = 'audit_log';
// 连接名,对应 plugin/webman/redis-queue/redis.php 里的连接`
public $connection = 'default';
// 消费
public function consume($data)
{
try {
$now = (int)($data['ts'] ?? time());
$row = [
// 'trace_id' => $data['trace_id'] ?? null,
'user_id' => $data['user_id'] ?? null,
'user_name' => $data['user_name'] ?? null,
'route' => $data['route'] ?? null,
'method' => $data['method'] ?? null,
'ip' => $data['ip'] ?? null,
'ua' => $data['ua'] ?? null,
'action' => $data['action'] ?? null,
'status' => (int)($data['status'] ?? 1),
'http_code' => (int)($data['http_code'] ?? 200),
'latency_ms' => $data['latency_ms'] ?? null,
'params_brief' => !empty($data['params_brief']) ? json_encode($data['params_brief'], JSON_UNESCAPED_UNICODE) : null,
'changes' => !empty($data['changes']) ? json_encode($data['changes'], JSON_UNESCAPED_UNICODE) : null,
'message' => $data['message'] ?? null,
'created_at' => $now,
'updated_at' => $now,
];
Db::table('sys_op_log')->insert($row);
} catch (\Throwable $e) {
Log::error('audit_log consume error: '.$e->getMessage());
return false; // 允许重试与失败处理
}
return true;
}
// 消费失败回调
/*
$package = [
'id' => 1357277951, // 消息ID
'time' => 1709170510, // 消息时间
'delay' => 0, // 延迟时间
'attempts' => 2, // 消费次数
'queue' => 'send-mail', // 队列名
'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
'max_attempts' => 5, // 最大重试次数
'error' => '错误信息' // 错误信息
]
*/
public function onConsumeFailure(\Throwable $e, $package)
{
echo "consume failure\n";
echo $e->getMessage() . "\n";
// 无需反序列化
var_export($package);
Log::error('audit_log message failed after retries: '.json_encode($package, JSON_UNESCAPED_UNICODE));
}
}