p2 project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.0 KiB

2 months ago
<?php
declare(strict_types=1);
namespace app\command;
use app\model\ApiLogModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;
use think\facade\Log;
1 month ago
use think\facade\Db;
2 months ago
class ApiLogCommand extends Command
{
protected function configure()
{
1 month ago
$this->setName('api_log')->setDescription('the api_log command');
2 months ago
}
1 month ago
2 months ago
protected function execute(Input $input, Output $output)
{
while (true) {
try {
$redis = Cache::store('redis')->handler();
$result = $redis->blpop(['api_log'], 5);
if ($result) {
$logData = json_decode($result[1], true);
if (!is_array($logData) || empty($logData)) {
continue;
}
1 month ago
$logData['params'] = json_encode($logData['params'] ?? [], JSON_UNESCAPED_UNICODE);
$logData['response'] = json_encode($logData['response'] ?? [], JSON_UNESCAPED_UNICODE);
try {
2 months ago
ApiLogModel::create($logData);
1 month ago
} catch (\Throwable $e) {
// 如果是 MySQL 2006 错误,则重连后再执行
if (strpos($e->getMessage(), '2006 MySQL server has gone away') !== false) {
Log::warning('MySQL connection lost, reconnecting...');
Db::purge();
// Db::disconnect(); // 清理旧连接
// Db::reconnect(); // 重新连接
1 month ago
ApiLogModel::create($logData); // 重试一次
} else {
throw $e;
}
2 months ago
}
} else {
1 month ago
sleep(10); // 没数据时休眠
2 months ago
}
} catch (\Throwable $e) {
Log::error('ApiLogCommand error: ' . $e->getMessage());
sleep(3);
}
}
}
}