AppServiceProvider.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace App\Providers;
  3. use Illuminate\Support\Facades\DB;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\ServiceProvider;
  6. class AppServiceProvider extends ServiceProvider
  7. {
  8. /**
  9. * Register any application services.
  10. *
  11. * @return void
  12. */
  13. public function register()
  14. {
  15. //添加自定义辅助函数
  16. require_once __DIR__.'/../helpers.php';
  17. }
  18. /**
  19. * Bootstrap any application services.
  20. *
  21. * @return void
  22. */
  23. public function boot()
  24. {
  25. //把SQL输出到日志中
  26. if ($this->app->environment('local')) { // 仅在本地环境启用
  27. DB::listen(function ($query) {
  28. // 格式化 SQL 语句
  29. $sql = $query->sql;
  30. foreach ($query->bindings as $binding) {
  31. $sql = preg_replace('/\?/', "'" . addslashes($binding) . "'", $sql, 1);
  32. }
  33. // 输出到控制台
  34. //dump($sql . ' [' . $query->time . 'ms]');
  35. //输出到log
  36. if ($query->time > 1000) {
  37. Log::error($sql . ' [' . $query->time . 'ms]');
  38. } else {
  39. Log::info($sql . ' [' . $query->time . 'ms]');
  40. }
  41. });
  42. }
  43. }
  44. }