<?php
class QueryPerformanceMonitor {
private $pdo;
private $logFile;
private $startTime;
private $endTime;
public function __construct($dsn, $username, $password, $logFile = 'query_performance.log') {
try {
$this->pdo = new PDO($dsn, $username, $password);
$this->logFile = $logFile;
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
}
// 开始计时
private function startTimer() {
$this->startTime = microtime(true);
}
// 结束计时
private function endTimer() {
$this->endTime = microtime(true);
return $this->endTime - $this->startTime;
}
// 执行查询并记录查询性能
public function executeQueryAndLog($query, $params = []) {
try {
$this->startTimer(); // 开始计时
$stmt = $this->pdo->prepare($query);
$stmt->execute($params);
$executionTime = $this->endTimer(); // 结束计时
$rowCount = $stmt->rowCount(); // 获取受影响行数
// 记录查询性能数据
$logEntry = [
'timestamp' => date('Y-m-d H:i:s'),
'query' => $query,
'execution_time' => round($executionTime, 4), // 保留4位小数
'row_count' => $rowCount
];
file_put_contents($this->logFile, json_encode($logEntry) . PHP_EOL, FILE_APPEND);
return $stmt->fetchAll(PDO::FETCH_ASSOC); // 返回查询结果
} catch (PDOException $e) {
echo "Query failed: " . $e->getMessage();
return false;
}
}
// 获取日志文件中的所有查询记录
public function getLogs() {
if (file_exists($this->logFile)) {
$logs = file($this->logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
return array_map('json_decode', $logs);
}
return [];
}
}
// 示例使用
$dsn = 'mysql:host=localhost;dbname=testdb';
$username = 'root';
$password = 'password';
$monitor = new QueryPerformanceMonitor($dsn, $username, $password);
// 示例查询
$query = "SELECT * FROM users WHERE age > :age";
$params = [':age' => 25];
$result = $monitor->executeQueryAndLog($query, $params);
if ($result) {
print_r($result);
}
// 输出所有日志
$logs = $monitor->getLogs();
foreach ($logs as $log) {
echo "Time: {$log->timestamp}, Query: {$log->query}, Execution Time: {$log->execution_time}s, Rows Affected: {$log->row_count}\n";
}
这个PHP代码片段实现了一个数据库查询性能监测工具,适用于监控和优化数据库查询的效率。该工具的核心功能如下:
- 查询性能监测:通过计时来测量SQL查询的执行时间,并记录到日志中,帮助开发者了解查询的性能表现。
- 日志记录:每次查询后,查询的SQL语句、执行时间、受影响行数等信息会被记录在指定的日志文件(默认为
query_performance.log
)中,以便后续分析。 - 日志读取:可以通过
getLogs
方法读取所有已记录的查询日志,从中找到执行时间较长或需要优化的查询语句。
该工具特别适合需要对数据库性能进行监控和优化的开发场景。通过分析查询日志,开发者可以发现性能瓶颈,进而优化数据库查询和架构设计。