2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel11 リクエストログを出力する

Posted at

Laravel8系の時に書いた記事がこのままの通りにはできなくなったので、Laravel11に合わせて書き直します。

目的

Laravelでリクエストログを出力します。
また、環境変数でログ出力の有効/無効の切り替えます。

環境

  • PHP 8.3.11
  • Laravel 11.23.5

RequestLogger を作成

$ php artisan make:middleware RequestLogger

app/Http/Middleware/RequestLogger.php ファイルが生成される。

bootstrap/app.php へ追記

bootstrap/app.php
<?php

declare(strict_types=1);

use App\Http\Middleware\RequestLogger;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(RequestLogger::class); // グローバル
        // $middleware->web(RequestLogger::class); // webグループのみ
        // $middleware->api(RequestLogger::class); // apiグループのみ
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

グローバルミドルウェアの登録方法が変わっています。
https://readouble.com/laravel/11.x/ja/middleware.html

app/Http/Middleware/RequestLogger.php を編集

app/Http/Middleware/RequestLogger.php
<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Response;

final class RequestLogger
{
    private array $excludes = [
        '_debugbar',
    ];

    public function __construct(private readonly LoggerInterface $logger)
    {
    }

    public function handle(Request $request, Closure $next): Response
    {
        if (config('logging.request.enable')) {
            if ($this->isWrite($request)) {
                $this->write($request);
            }
        }

        return $next($request);
    }

    /**
     * @param Request $request
     * @return bool
     */
    private function isWrite(Request $request): bool
    {
        return !in_array($request->path(), $this->excludes, true);
    }

    /**
     * @param Request $request
     */
    private function write(Request $request): void
    {
        $this->logger->debug($request->method(), ['url' => $request->fullUrl(), 'request' => $request->all()]);
    }
}

config/logging.php を編集

config/logging.php
return [
    /*
    |--------------------------------------------------------------------------
    | Custom Log
    |--------------------------------------------------------------------------
    */

    'request' => [
        'enable' => env('LOG_REQUEST_ENABLE', false),
    ],
];

ログ設定ファイルに追加してます。デフォルトは無効にしてます。

.env を編集

.env
LOG_REQUEST_ENABLE=true

環境設定ファイルで有効にしてご利用ください。

お試し実行

routes/web.php

Route::get('welcome/test', fn () => 'welcome test');

storage/logs/laravel.log ログファイルに次のログが出力されていればok

storage/logs/laravel.log
[2024-10-04 22:49:58] local.DEBUG: GET {"url":"http://localhost/welcome/test?foo=bar&hoge=fuga","request":{"foo":"bar","hoge":"fuga"}} 
2
2
0

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
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?