Railsみたいにhttpリクエスト後に発行されるSQLをログファイルに出力する
環境
- Laravel: 5.6.3
コード
app/Providers/AppServiceProvider.php
public function register()
{
// SQL Log
\DB::listen(function ($query) {
$sql = $query->sql;
for ($i = 0; $i < count($query->bindings); $i++) {
$sql = preg_replace("/\?/", $query->bindings[$i], $sql, 1);
}
\Log::debug("SQL", ["time" => sprintf("%.2f ms", $query->time), "sql" => $sql]);
});
}
[2018-02-14 09:17:04] laravel.DEBUG: SQL {"time":"24.56 ms","sql":"select * from \"groups\" order by createdday desc limit 10"}
[2018-02-14 09:17:04] laravel.DEBUG: SQL {"time":"4.98 ms","sql":"select count(*) as aggregate from \"groups\""
参考