71 lines
1.9 KiB
PHP
71 lines
1.9 KiB
PHP
<?php
|
||
|
||
namespace App\Providers;
|
||
|
||
use Illuminate\Database\Events\QueryExecuted;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Log;
|
||
use Illuminate\Support\ServiceProvider;
|
||
|
||
class AppServiceProvider extends ServiceProvider
|
||
{
|
||
/**
|
||
* Register any application services.
|
||
*/
|
||
public function register(): void
|
||
{
|
||
//
|
||
}
|
||
|
||
/**
|
||
* Bootstrap any application services.
|
||
*/
|
||
public function boot(): void
|
||
{
|
||
$this->setupSlowQueryLogging();
|
||
}
|
||
|
||
/**
|
||
* 设置慢查询日志记录
|
||
*/
|
||
private function setupSlowQueryLogging(): void
|
||
{
|
||
try {
|
||
DB::listen(function (QueryExecuted $query) {
|
||
$this->logSlowQuery($query);
|
||
});
|
||
} catch (\Exception $e) {
|
||
// 如果SQL日志系统初始化失败,记录到默认日志但不影响主要业务
|
||
|
||
}
|
||
}
|
||
|
||
|
||
/**
|
||
* 记录慢查询
|
||
*/
|
||
private function logSlowQuery(QueryExecuted $query): void
|
||
{
|
||
try {
|
||
// 根据环境设置不同的慢查询阈值, 本地环境所有查询都记录, 正式环境慢查询阈值500ms
|
||
$slowQueryThreshold = $this->app->environment(['local','development']) ? 0 : 500;
|
||
|
||
// 只记录慢查询
|
||
if ($query->time > $slowQueryThreshold) {
|
||
Log::channel('sql')->info('Slow Query: ' . $query->sql, [
|
||
'bindings' => $query->bindings,
|
||
'time' => $query->time . 'ms',
|
||
'environment' => $this->app->environment()
|
||
]);
|
||
}
|
||
} catch (\Exception $e) {
|
||
// 慢查询日志记录失败,降级处理
|
||
Log::error('慢查询日志记录失败', [
|
||
'query' => $query->sql,
|
||
'bindings' => $query->bindings,
|
||
'time' => $query->time . 'ms'
|
||
]);
|
||
}
|
||
}
|
||
}
|