search
LoginSignup
15

More than 3 years have passed since last update.

posted at

updated at

Laravelでhttpリクエストをlaravel.logに出力する

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"} 

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
15