Skip to content

Commit fa18af0

Browse files
committed
优化日志
1 parent e06ab2d commit fa18af0

3 files changed

Lines changed: 179 additions & 14 deletions

File tree

.codebuddy/plans/.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
*
2+
!.gitignore

app/Service/ProxyService.php

Lines changed: 143 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
use App\Helpers\WildcardHelper;
99
use Hyperf\Config\Annotation\Value;
1010
use Hyperf\Context\ApplicationContext;
11+
use Hyperf\Logger\LoggerFactory;
1112
use Psr\Container\ContainerInterface;
13+
use Psr\Log\LoggerInterface;
1214
use Swoole\Coroutine;
1315
use Swoole\Coroutine\Socket;
1416
use App\Protocol\ConnectionContext;
@@ -23,12 +25,16 @@ class ProxyService
2325
private bool $sqlHighlight;
2426
private array $excludePatterns;
2527
private array $connections = [];
26-
private \Psr\Log\LoggerInterface $logger;
28+
private LoggerInterface $logger;
29+
private LoggerInterface $sqlLogger;
30+
private LoggerInterface $connectionLogger;
2731

28-
public function __construct(ContainerInterface $container, \Psr\Log\LoggerInterface $logger)
32+
public function __construct(ContainerInterface $container, LoggerFactory $loggerFactory)
2933
{
3034
$this->container = $container;
31-
$this->logger = $logger;
35+
$this->logger = $loggerFactory->get('default');
36+
$this->sqlLogger = $loggerFactory->get('sql');
37+
$this->connectionLogger = $loggerFactory->get('connection');
3238
$config = config('proxy', []);
3339

3440
$this->logEnabled = isset($config['log']['enabled']) ? $config['log']['enabled'] : true;
@@ -148,8 +154,18 @@ private function handleQuery(\Swoole\Server $server, ConnectionContext $context,
148154
{
149155
$startTime = microtime(true);
150156

157+
$this->sqlLogger->info('收到SQL查询请求', [
158+
'client_id' => $context->getClientId(),
159+
'sql' => $sql,
160+
]);
161+
151162
// 检查排除规则
152163
if (WildcardHelper::shouldExclude($sql, $this->excludePatterns)) {
164+
$this->sqlLogger->debug('SQL匹配排除规则,直接转发', [
165+
'client_id' => $context->getClientId(),
166+
'sql' => $sql,
167+
'exclude_patterns' => $this->excludePatterns,
168+
]);
153169
$this->forwardToTarget($server, $context, $packet);
154170
return;
155171
}
@@ -175,6 +191,16 @@ private function handleQuery(\Swoole\Server $server, ConnectionContext $context,
175191
$group = isset($dsnParams['group']) ? $dsnParams['group'] : null;
176192
$transactionId = $context->isInTransaction() ? $context->getTransactionId() : null;
177193

194+
$this->sqlLogger->info('SQL查询完成', [
195+
'client_id' => $context->getClientId(),
196+
'client_info' => (string) $context,
197+
'sql' => $sql,
198+
'group' => $group,
199+
'transaction_id' => $transactionId,
200+
'elapsed_ms' => $elapsedMs,
201+
'affected_rows' => $affectedRows,
202+
]);
203+
178204
\App\Helpers\LogHelper::writeLog(
179205
(string) $context,
180206
$sql,
@@ -189,12 +215,24 @@ private function handleQuery(\Swoole\Server $server, ConnectionContext $context,
189215

190216
private function handlePrepare(\Swoole\Server $server, ConnectionContext $context, Packet $packet, string $sql): void
191217
{
218+
$this->sqlLogger->info('收到预处理语句请求', [
219+
'client_id' => $context->getClientId(),
220+
'sql' => $sql,
221+
]);
222+
192223
$response = $this->forwardToTargetAndGetResponse($server, $context, $packet);
193224

194225
// 注册预处理语句
195226
if ($response && isset($response[0])) {
196227
$prepareResp = Prepare::parsePrepareResponse($response[0]);
197-
Parser::registerPreparedStatement($prepareResp['statement_id'], $sql);
228+
$stmtId = $prepareResp['statement_id'];
229+
Parser::registerPreparedStatement($stmtId, $sql);
230+
231+
$this->sqlLogger->debug('预处理语句注册成功', [
232+
'client_id' => $context->getClientId(),
233+
'statement_id' => $stmtId,
234+
'sql' => $sql,
235+
]);
198236
}
199237
}
200238

@@ -203,11 +241,26 @@ private function handleExecute(\Swoole\Server $server, ConnectionContext $contex
203241
$stmtId = $data['statement_id'];
204242
$sql = Parser::getPreparedStatement($stmtId);
205243

244+
$this->sqlLogger->info('收到预处理语句执行请求', [
245+
'client_id' => $context->getClientId(),
246+
'statement_id' => $stmtId,
247+
'sql' => $sql,
248+
]);
249+
206250
if ($sql && $this->logEnabled) {
207251
$dsnParams = $context->getDsnParams();
208252
$group = isset($dsnParams['group']) ? $dsnParams['group'] : null;
209253
$transactionId = $context->isInTransaction() ? $context->getTransactionId() : null;
210254

255+
$this->sqlLogger->info('预处理语句执行', [
256+
'client_id' => $context->getClientId(),
257+
'client_info' => (string) $context,
258+
'sql' => "[EXECUTE] " . $sql,
259+
'group' => $group,
260+
'transaction_id' => $transactionId,
261+
'statement_id' => $stmtId,
262+
]);
263+
211264
\App\Helpers\LogHelper::writeLog(
212265
(string) $context,
213266
"[EXECUTE] " . $sql,
@@ -225,11 +278,19 @@ private function handleExecute(\Swoole\Server $server, ConnectionContext $contex
225278
private function handleQuit(\Swoole\Server $server, ConnectionContext $context): void
226279
{
227280
$clientId = $context->getClientId();
281+
282+
$this->connectionLogger->info('客户端请求断开连接', [
283+
'client_id' => $clientId,
284+
]);
285+
228286
unset($this->connections[$clientId]);
229287

230288
// 关闭目标MySQL连接
231289
if ($context->getMysqlSocket()) {
232290
$context->getMysqlSocket()->close();
291+
$this->connectionLogger->debug('已关闭目标MySQL连接', [
292+
'client_id' => $clientId,
293+
]);
233294
}
234295
}
235296

@@ -252,17 +313,51 @@ private function connectToTargetAndForward(\Swoole\Server $server, ConnectionCon
252313
$host = $context->getTargetHost() !== null ? $context->getTargetHost() : $defaultHost;
253314
$port = (int) ($context->getTargetPort() !== null ? $context->getTargetPort() : $defaultPort);
254315

255-
$socket = new Socket(AF_INET, SOCK_STREAM, 0);
256-
$socket->connect($host, $port);
316+
$this->connectionLogger->info('开始连接目标MySQL服务器', [
317+
'client_id' => $context->getClientId(),
318+
'host' => $host,
319+
'port' => $port,
320+
]);
257321

258-
$context->setMysqlSocket($socket);
322+
try {
323+
$socket = new Socket(AF_INET, SOCK_STREAM, 0);
324+
$socket->connect($host, $port);
259325

260-
// 转发认证数据
261-
$socket->sendAll($packet->toBytes());
326+
$context->setMysqlSocket($socket);
262327

263-
// 读取响应并转发回客户端
264-
$response = $this->readAllPackets($socket);
265-
$server->send((int) $context->getClientId(), $response);
328+
$this->connectionLogger->info('MySQL连接建立成功', [
329+
'client_id' => $context->getClientId(),
330+
'host' => $host,
331+
'port' => $port,
332+
]);
333+
334+
// 转发认证数据
335+
$socket->sendAll($packet->toBytes());
336+
337+
$this->connectionLogger->debug('已发送认证数据', [
338+
'client_id' => $context->getClientId(),
339+
'data_length' => strlen($packet->toBytes()),
340+
]);
341+
342+
// 读取响应并转发回客户端
343+
$response = $this->readAllPackets($socket);
344+
$server->send((int) $context->getClientId(), $response);
345+
346+
$this->connectionLogger->debug('认证响应已转发', [
347+
'client_id' => $context->getClientId(),
348+
'response_length' => strlen($response),
349+
]);
350+
} catch (\Exception $e) {
351+
$this->connectionLogger->error('MySQL连接失败', [
352+
'client_id' => $context->getClientId(),
353+
'host' => $host,
354+
'port' => $port,
355+
'error' => $e->getMessage(),
356+
'file' => $e->getFile(),
357+
'line' => $e->getLine(),
358+
]);
359+
throw $e;
360+
}
266361
}
267362

268363
private function forwardToTarget(\Swoole\Server $server, ConnectionContext $context, Packet $packet): void
@@ -274,12 +369,24 @@ private function forwardToTarget(\Swoole\Server $server, ConnectionContext $cont
274369
return;
275370
}
276371

277-
$socket->sendAll($packet->toBytes());
372+
$packetData = $packet->toBytes();
373+
$this->connectionLogger->debug('转发数据包到目标MySQL', [
374+
'client_id' => $context->getClientId(),
375+
'data_length' => strlen($packetData),
376+
'command' => $packet->getCommand(),
377+
]);
378+
379+
$socket->sendAll($packetData);
278380

279381
// 读取响应并转发回客户端
280382
$response = $this->readAllPackets($socket);
281383
if ($response !== '') {
282384
$server->send((int) $context->getClientId(), $response);
385+
386+
$this->connectionLogger->debug('已转发MySQL响应', [
387+
'client_id' => $context->getClientId(),
388+
'response_length' => strlen($response),
389+
]);
283390
}
284391
}
285392

@@ -292,13 +399,26 @@ private function forwardToTargetAndGetResponse(\Swoole\Server $server, Connectio
292399
return [];
293400
}
294401

295-
$socket->sendAll($packet->toBytes());
402+
$packetData = $packet->toBytes();
403+
$this->connectionLogger->debug('转发SQL查询到目标MySQL', [
404+
'client_id' => $context->getClientId(),
405+
'data_length' => strlen($packetData),
406+
'command' => $packet->getCommand(),
407+
]);
408+
409+
$socket->sendAll($packetData);
296410

297411
$responseData = $this->readAllPackets($socket);
298412
$packets = Parser::parsePackets($responseData);
299413

300414
if ($responseData !== '') {
301415
$server->send((int) $context->getClientId(), $responseData);
416+
417+
$this->connectionLogger->debug('已转发MySQL响应', [
418+
'client_id' => $context->getClientId(),
419+
'response_length' => strlen($responseData),
420+
'packet_count' => count($packets),
421+
]);
302422
}
303423

304424
return $packets;
@@ -352,9 +472,18 @@ public function onClose(\Swoole\Server $server, int $fd, int $reactorId): void
352472
if (isset($this->connections[$clientId])) {
353473
$context = $this->connections[$clientId];
354474

475+
$this->connectionLogger->info('客户端连接关闭', [
476+
'client_id' => $clientId,
477+
'client_ip' => $context->getRemoteIp(),
478+
'client_port' => $context->getRemotePort(),
479+
]);
480+
355481
// 关闭目标MySQL连接
356482
if ($context->getMysqlSocket()) {
357483
$context->getMysqlSocket()->close();
484+
$this->connectionLogger->debug('已关闭目标MySQL连接', [
485+
'client_id' => $clientId,
486+
]);
358487
}
359488

360489
unset($this->connections[$clientId]);

config/autoload/logger.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,4 +44,38 @@
4444
],
4545
],
4646
],
47+
'sql' => [
48+
'handler' => [
49+
'class' => Monolog\Handler\RotatingFileHandler::class,
50+
'constructor' => [
51+
'filename' => BASE_PATH . '/runtime/logs/sql.log',
52+
'level' => Monolog\Logger::INFO,
53+
],
54+
],
55+
'formatter' => [
56+
'class' => Monolog\Formatter\LineFormatter::class,
57+
'constructor' => [
58+
'format' => "[%datetime%] %channel%.%level_name%: %message%\n",
59+
'dateFormat' => 'Y-m-d H:i:s.v',
60+
'allowInlineLineBreaks' => true,
61+
],
62+
],
63+
],
64+
'connection' => [
65+
'handler' => [
66+
'class' => Monolog\Handler\RotatingFileHandler::class,
67+
'constructor' => [
68+
'filename' => BASE_PATH . '/runtime/logs/connection.log',
69+
'level' => Monolog\Logger::DEBUG,
70+
],
71+
],
72+
'formatter' => [
73+
'class' => Monolog\Formatter\LineFormatter::class,
74+
'constructor' => [
75+
'format' => "[%datetime%] %channel%.%level_name%: %message%\n",
76+
'dateFormat' => 'Y-m-d H:i:s.v',
77+
'allowInlineLineBreaks' => true,
78+
],
79+
],
80+
],
4781
];

0 commit comments

Comments
 (0)