Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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"} 
tmf16
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away