study-api-v2/app/Providers/AppServiceProvider.php

71 lines
1.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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'
]);
}
}
}