laravel sql 语句监听

AppServiceProvider 类的 boot 方法添加如下代码

if (config('app.log_db')) {
      Schema::defaultStringLength(191);
      DB::listen(function ($query) {
          $sql = $query->sql;
          if (! Arr::isAssoc($query->bindings)) {
              foreach ($query->bindings as $value) {
                  if ($value instanceof \DateTime) {
                      $value = $value->format('Y-m-d H:i:s');
                  }
                  $sql = Str::replaceFirst('?', "'{$value}'", $sql);
              }
          }

          Log::info(sprintf('[%s] %s', $query->time, $sql));
      });
  }
posted @ 2022-06-30 16:58  _DongGe  阅读(161)  评论(0编辑  收藏  举报