QueryLogServiceProvider.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\ServiceProvider;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Log;
  6. class QueryLogServiceProvider extends ServiceProvider
  7. {
  8. /**
  9. * Register services.
  10. */
  11. public function register(): void
  12. {
  13. //
  14. }
  15. /**
  16. * Bootstrap services.
  17. */
  18. public function boot(): void
  19. {
  20. if (config('app.debug')) {
  21. DB::listen(function($query) {
  22. $sql = $query->sql;
  23. $bindings = $query->bindings;
  24. $time = $query->time;
  25. // 格式化SQL语句(替换占位符)
  26. foreach ($bindings as $binding) {
  27. $value = is_numeric($binding) ? $binding : "'".$binding."'";
  28. $sql = preg_replace('/\?/', $value, $sql, 1);
  29. }
  30. // 记录SQL日志
  31. Log::channel('sql')->debug('SQL', [
  32. 'sql' => $sql,
  33. 'time' => $time.'ms',
  34. ]);
  35. });
  36. }
  37. }
  38. }