7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel APIのリクエストとレスポンスログを出力する

Last updated at Posted at 2023-11-04

2024/4/10 追記: こちらの記事をライブラリ化しました。

https://qiita.com/ucan-lab/items/dc33ab7df03ebf485898

過去記事

目的

リクエストログと合わせてレスポンスログを出力したい要望がありました。
また、どのリクエストがどのレスポンスと紐付くのかぱっと見わかりやすくするためリクエストIDを付けたい。

環境

  • PHP 8.2.11
  • Laravel Framework 10.30.1

手順

$ php artisan make:middleware ApiLogger
app/Http/Middleware/Kernel.php
<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

final class ApiLogger
{
    public function handle(Request $request, Closure $next): JsonResponse
    {
        $requestId = uniqid('req-', false);

        Log::debug($requestId . ':' . $request->method() . ':' . $request->fullUrl(), [
            'user' => $request->user()?->id,
            'headers' => $request->headers->all(),
            'body' => $request->all(),
        ]);

        /** @var JsonResponse $response */
        $response = $next($request);

        Log::debug($requestId, $response->getData(true));

        return $response;
    }
}
  • ※ Apiのコントローラ側で JsonResponse 返す前提を想定してます。

app/Http/Kernel.php を編集します。

app/Http/Kernel.php
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    // ...

    protected $middlewareGroups = [
        // ...
        'api' => [
            // ...
            \App\Http\Middleware\ApiLogger::class, // 追加
        ],
    ];

    // ...
}
7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?