在Laravel应用中直接通过DB门面或模型执行查询时,开发者往往只能看到最终的SQL结果,却无法感知执行过程中的性能抖动、慢查询堆积或N+1问题。一个更彻底的方案是注册一个全局中间件,在每一次请求生命周期内拦截所有数据库操作,把原始SQL、绑定参数、执行时间和连接名完整记录下来,并基于预设阈值自动标记异常。这样做的价值在于:不需要依赖第三方APM工具,就能在本地或测试环境快速复现问题SQL,同时为生产环境的慢查询预警提供第一手数据。
注册中间件并注入数据库监听先在app/Http/Middleware目录下创建SqlMonitor中间件,核心思路是利用DB::listen注册一个全局查询回调。Laravel的数据库事件会携带QueryExecuted对象,包含sql、bindings、time和connectionName四个关键属性。中间件在handle方法里注册监听,并把收集到的日志写入数组或直接推送到日志通道。
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class SqlMonitor
{
public function handle($request, Closure $next)
{
// 开启查询日志(非生产环境可强制启用)
DB::enableQueryLog();
// 收集所有SQL执行记录
$queries = [];
DB::listen(function (\Illuminate\Database\Events\QueryExecuted $event) use (&$queries) {
$sql = $this->bindParams($event->sql, $event->bindings);
$time = $event->time;
$connection = $event->connectionName;
$queries[] = [
'sql' => $sql,
'time' => $time,
'connection' => $connection,
'timestamp' => now()->toDateTimeString(),
];
});
$response = $next($request);
// 请求结束后统一处理
$this->analyzeAndLog($queries);
return $response;
}
protected function bindParams($sql, $bindings)
{
// 将问号占位符替换为实际参数值,便于直接复制执行
$bindings = array_map(function ($binding) {
if ($binding instanceof \DateTime) {
return $binding->format('Y-m-d H:i:s');
}
if (is_string($binding)) {
return "'{$binding}'";
}
return $binding;
}, $bindings);
return vsprintf(str_replace('?', '%s', $sql), $bindings);
}
protected function analyzeAndLog($queries)
{
$totalTime = array_sum(array_column($queries, 'time'));
$queryCount = count($queries);
$slowThreshold = config('sql_monitor.slow_threshold', 100); // 毫秒
$slowQueries = array_filter($queries, function ($q) use ($slowThreshold) {
return $q['time'] > $slowThreshold;
});
$logData = [
'uri' => request()->getRequestUri(),
'method' => request()->method(),
'total_queries' => $queryCount,
'total_time_ms' => $totalTime,
'slow_queries' => array_values($slowQueries),
'all_queries' => $queries,
];
// 异常检测逻辑
$this->detectAnomalies($logData);
// 写入专用日志通道
Log::channel('sql_monitor')->info('SQL监控报告', $logData);
}
protected function detectAnomalies($logData)
{
$warnings = [];
// 1. 单次请求查询数过多
if ($logData['total_queries'] > 50) {
$warnings[] = "查询数量异常:单次请求执行了 {$logData['total_queries']} 条SQL,可能存在N+1问题";
}
// 2. 总耗时过高
if ($logData['total_time_ms'] > 2000) {
$warnings[] = "总耗时过长:累计 {$logData['total_time_ms']}ms,建议优化查询或增加缓存";
}
// 3. 慢查询数量
$slowCount = count($logData['slow_queries']);
if ($slowCount > 0) {
$warnings[] = "发现 {$slowCount} 条慢查询(阈值100ms)";
}
// 4. 重复查询检测
$sqlHashes = [];
foreach ($logData['all_queries'] as $q) {
$hash = md5($q['sql']);
$sqlHashes[$hash][] = $q;
}
foreach ($sqlHashes as $hash => $group) {
if (count($group) > 3) {
$warnings[] = "重复查询:相同SQL执行了 " . count($group) . " 次,建议使用缓存或预加载";
break; // 只记录一次
}
}
if (!empty($warnings)) {
Log::channel('sql_monitor')->warning('SQL异常检测', [
'uri' => $logData['uri'],
'warnings' => $warnings,
]);
}
}
}
注册全局中间件并配置日志通道
中间件编写完成后,在app/Http/Kernel.php的$middleware数组中注册,使其作用于每一个HTTP请求。同时创建独立的日志通道,避免SQL监控日志与业务日志混杂。
// app/Http/Kernel.php
protected $middleware = [
// 其他中间件...
\App\Http\Middleware\SqlMonitor::class,
];
接着在config/logging.php中新增sql_monitor通道,建议按日期切割,并限制保留天数。
'channels' => [
// 其他通道...
'sql_monitor' => [
'driver' => 'daily',
'path' => storage_path('logs/sql_monitor.log'),
'level' => 'debug',
'days' => 7,
],
],
创建配置文件灵活控制监控行为
把慢查询阈值、是否启用监控、忽略的URL模式等做成可配置项,方便不同环境切换。创建config/sql_monitor.php配置文件。
return [
// 是否启用SQL监控
'enabled' => env('SQL_MONITOR_ENABLED', true),
// 慢查询阈值(毫秒)
'slow_threshold' => env('SQL_MONITOR_SLOW_THRESHOLD', 100),
// 单次请求最大查询数阈值
'max_queries' => env('SQL_MONITOR_MAX_QUERIES', 50),
// 总耗时阈值(毫秒)
'max_total_time' => env('SQL_MONITOR_MAX_TOTAL_TIME', 2000),
// 重复查询次数阈值
'duplicate_threshold' => env('SQL_MONITOR_DUPLICATE_THRESHOLD', 3),
// 忽略的URL模式(支持通配符)
'ignore_urls' => [
'telescope/*',
'horizon/*',
'health-check',
],
// 是否记录所有查询(关闭后仅记录异常)
'log_all_queries' => env('SQL_MONITOR_LOG_ALL', false),
];
修改中间件的handle方法,在开头加入启用判断和URL过滤。
public function handle($request, Closure $next)
{
if (!config('sql_monitor.enabled', true)) {
return $next($request);
}
// 忽略指定URL
foreach (config('sql_monitor.ignore_urls', []) as $pattern) {
if ($request->is($pattern)) {
return $next($request);
}
}
// 后续监听逻辑...
}
扩展异常检测维度
基础的慢查询和重复查询检测只能覆盖部分场景,实际项目中还需要关注更多异常模式。比如某条SQL的绑定参数为空数组导致全表扫描、whereIn条件包含过多元素、或者同一接口在短时间内查询数突增。这些检测逻辑可以封装成独立的检测器类,方便扩展。
// 创建 app/Services/SqlAnomalyDetector.php
namespace App\Services;
class SqlAnomalyDetector
{
protected $config;
public function __construct()
{
$this->config = config('sql_monitor');
}
public function detect(array $queries, string $uri): array
{
$warnings = [];
$warnings = array_merge($warnings, $this->checkEmptyInClause($queries));
$warnings = array_merge($warnings, $this->checkLargeInClause($queries));
$warnings = array_merge($warnings, $this->checkNoWhereClause($queries));
$warnings = array_merge($warnings, $this->checkCartesianJoin($queries));
return $warnings;
}
// 检测空IN子句
protected function checkEmptyInClause($queries)
{
$warnings = [];
foreach ($queries as $q) {
if (preg_match('/where\s+.*\s+in\s*\(\s*\)/i', $q['sql'])) {
$warnings[] = "空IN子句:{$q['sql']},可能导致意外结果";
}
}
return $warnings;
}
// 检测IN子句元素过多
protected function checkLargeInClause($queries)
{
$warnings = [];
foreach ($queries as $q) {
if (preg_match('/in\s*\(([^)]+)\)/i', $q['sql'], $matches)) {
$count = substr_count($matches[1], ',') + 1;
if ($count > 500) {
$warnings[] = "IN子句包含 {$count} 个元素,建议分批处理或使用临时表";
}
}
}
return $warnings;
}
// 检测无WHERE条件的UPDATE/DELETE
protected function checkNoWhereClause($queries)
{
$warnings = [];
foreach ($queries as $q) {
$sql = strtolower($q['sql']);
if ((strpos($sql, 'update') !== false || strpos($sql, 'delete') !== false)
&& strpos($sql, 'where') === false) {
$warnings[] = "危险操作:未包含WHERE条件的修改语句 - {$q['sql']}";
}
}
return $warnings;
}
// 检测笛卡尔积JOIN(简化版:连续多个JOIN无ON条件)
protected function checkCartesianJoin($queries)
{
$warnings = [];
foreach ($queries as $q) {
$joinCount = preg_match_all('/\bjoin\b/i', $q['sql'], $matches);
$onCount = preg_match_all('/\bon\b/i', $q['sql'], $matches);
if ($joinCount > 1 && $onCount < $joinCount) {
$warnings[] = "可能存在笛卡尔积JOIN,JOIN数量{$joinCount},ON条件数量{$onCount}";
}
}
return $warnings;
}
}
在中间件的analyzeAndLog方法中调用检测器,将所有警告汇总输出。
protected function analyzeAndLog($queries)
{
// ...原有统计逻辑...
$detector = new \App\Services\SqlAnomalyDetector();
$anomalyWarnings = $detector->detect($queries, $logData['uri']);
if (!empty($anomalyWarnings)) {
$logData['anomaly_warnings'] = $anomalyWarnings;
Log::channel('sql_monitor')->warning('SQL异常检测', $logData);
}
// 根据配置决定是否记录全部查询
if (config('sql_monitor.log_all_queries', false)) {
Log::channel('sql_monitor')->info('SQL监控报告', $logData);
}
}
处理绑定参数的安全替换
原生DB::listen获取到的bindings是未经处理的原始值,直接拼接到SQL中可能因数据类型问题导致语法错误。bindParams方法需要处理字符串引号包裹、日期格式化、布尔值转换和NULL值处理。更严谨的做法是区分参数类型,避免将二进制数据或超长文本直接写入日志。
protected function bindParams($sql, $bindings)
{
$bindings = array_map(function ($binding) {
if (is_null($binding)) {
return 'NULL';
}
if (is_bool($binding)) {
return $binding ? '1' : '0';
}
if ($binding instanceof \DateTimeInterface) {
return "'{$binding->format('Y-m-d H:i:s')}'";
}
if (is_string($binding)) {
// 截断过长字符串,防止日志膨胀
$binding = mb_strlen($binding) > 200
? mb_substr($binding, 0, 200) . '...'
: $binding;
return "'" . addslashes($binding) . "'";
}
if (is_array($binding)) {
return "'" . json_encode($binding, JSON_UNESCAPED_UNICODE) . "'";
}
return $binding;
}, $bindings);
return vsprintf(str_replace(['%', '?'], ['%%', '%s'], $sql), $bindings);
}
按连接分组与数据库实例区分
大型应用可能同时连接多个数据库,监控日志需要区分连接名,便于定位是主库还是只读库的问题。在收集查询时按connection分组统计,输出报告时分别展示每个库的查询数和耗时。
$groupedQueries = [];
foreach ($queries as $q) {
$conn = $q['connection'];
$groupedQueries[$conn][] = $q;
}
foreach ($groupedQueries as $conn => $connQueries) {
$connTime = array_sum(array_column($connQueries, 'time'));
$logData['connections'][$conn] = [
'query_count' => count($connQueries),
'total_time_ms' => $connTime,
];
}
生产环境下的性能考量
全局监听所有SQL必然带来额外开销,尤其是在高并发场景下。建议在生产环境采取采样策略,例如只对1%的请求启用完整监控,或者仅在检测到响应时间超过阈值时才记录SQL日志。可以在中间件中结合随机采样和响应时间判断。
public function handle($request, Closure $next)
{
// 采样率配置
$sampleRate = config('sql_monitor.sample_rate', 0.01);
$shouldMonitor = config('sql_monitor.enabled') && (mt_rand() / mt_getrandmax()) <= $sampleRate;
if (!$shouldMonitor) {
return $next($request);
}
// 记录开始时间
$startTime = microtime(true);
// ...注册监听...
$response = $next($request);
$responseTime = (microtime(true) - $startTime) * 1000;
// 响应时间超过阈值时强制记录
$forceLog = $responseTime > config('sql_monitor.force_log_response_time', 3000);
if ($forceLog || $shouldMonitor) {
$this->analyzeAndLog($queries);
}
return $response;
}
日志分析与可视化建议
纯文本日志在查询量大的时候难以阅读,可以在中间件中增加JSON格式输出,配合ELK或本地脚本解析。更轻量的做法是提供一个Artisan命令,按条件筛选日志文件中的慢查询或异常记录。
// 创建 app/Console/Commands/SqlMonitorReport.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class SqlMonitorReport extends Command
{
protected $signature = 'sql:report {--date= : 指定日期,格式Y-m-d} {--slow-only : 仅显示慢查询}';
protected $description = '解析SQL监控日志并生成报告';
public function handle()
{
$date = $this->option('date') ?? now()->format('Y-m-d');
$logFile = storage_path("logs/sql_monitor-{$date}.log");
if (!file_exists($logFile)) {
$this->error("日志文件不存在:{$logFile}");
return;
}
$lines = file($logFile);
$slowQueries = [];
$totalRequests = 0;
foreach ($lines as $line) {
$data = json_decode($line, true);
if (!$data) continue;
$totalRequests++;
if (!empty($data['slow_queries'])) {
foreach ($data['slow_queries'] as $sq) {
$slowQueries[] = [
'uri' => $data['uri'],
'sql' => $sq['sql'],
'time' => $sq['time'],
];
}
}
}
$this->info("分析日期:{$date}");
$this->info("总请求数:{$totalRequests}");
$this->info("慢查询数:" . count($slowQueries));
if ($this->option('slow-only')) {
$this->table(['URI', 'SQL', '耗时(ms)'], array_slice($slowQueries, 0, 20));
}
}
}
与现有调试工具的差异和配合
Laravel Telescope和Debugbar都提供了SQL监控能力,但它们偏向于开发调试,生产环境通常不会启用。本文实现的中间件方案专注于生产可用的轻量级监控,不依赖图形界面,日志可接入现有告警体系。两者可以共存:开发环境用Telescope查看实时查询,生产环境靠中间件日志做长期追踪和异常告警。关键区别在于中间件方案支持自定义检测规则、采样策略和日志聚合,更适合作为运维监控的一环。
实际落地中的注意事项绑定参数替换时要注意SQL注入风险仅存在于日志输出阶段,不影响实际执行。日志文件权限需确保Web进程可写,使用daily驱动时配合logrotate或Laravel自带的日志清理机制。如果应用使用了队列任务或定时任务,这些CLI执行环境不会经过HTTP中间件,需要在AppServiceProvider或对应入口单独注册DB::listen。最后,中间件中收集的查询数组在请求结束后应立即释放,避免长驻内存导致累积。
