Railsみたいにhttpリクエストをログファイルに出力する
出力用のMiddlewareを追加
app/Http/Middleware/RequestMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class RequestMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (in_array(app()->environment(), ["local", "development"])) {
$this->writeLog($request);
}
return $next($request);
}
private function writeLog($request)
{
$query = collect($request->all())->except("q")->all();
\Log::debug($request->method(), ["path" => $request->query("q", "/"), "query" => http_build_query($query)]);
}
}
Kernel.php
で読み込むようにRequestMiddleware.php
を追加する。
laravel/app/Http/Kernel.php
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
+ \App\Http\Middleware\RequestMiddleware::class,
];
http://localhost/groups?hoge=fuga&111=333
にアクセスすると下記のログが出力される
storage/logs/laravel.log
[2018-02-27 19:14:41] local.DEBUG: GET {"path":"/groups","query":"hoge=fuga&111=333"}
[2018-02-27 19:14:41] local.DEBUG: SQL {"time":"9.19 ms","sql":"select * from \"groups\" order by createdday desc limit 10"}