1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- <?php
- namespace App\Providers;
- use Illuminate\Support\ServiceProvider;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- class QueryLogServiceProvider extends ServiceProvider
- {
- /**
- * Register services.
- */
- public function register(): void
- {
- //
- }
- /**
- * Bootstrap services.
- */
- public function boot(): void
- {
- if (config('app.debug')) {
- DB::listen(function($query) {
- $sql = $query->sql;
- $bindings = $query->bindings;
- $time = $query->time;
- // 格式化SQL语句(替换占位符)
- foreach ($bindings as $binding) {
- $value = is_numeric($binding) ? $binding : "'".$binding."'";
- $sql = preg_replace('/\?/', $value, $sql, 1);
- }
- // 记录SQL日志
- Log::channel('sql')->debug('SQL', [
- 'sql' => $sql,
- 'time' => $time.'ms',
- ]);
- });
- }
- }
- }
|