0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Laravel】API呼び出し時にクエリログを出力する方法

Last updated at Posted at 2025-01-14

概要

APIが呼ばれるたびに、リクエストの内容と、発行されたクエリをログ出力させるミドルウェアを作成します。デバッグやパフォーマンス改善に活用できます。

前提知識

ミドルウェアとは?

HTTPリクエストがアプリケーションに到達する前に、リクエストをフィルタリングまたは操作する層です。以下のような処理ができます。

  • 認証の確認
  • CORSの設定
  • メンテナンスモードのチェック
  • フォームデータのトリミングや変換

ミドルウェアは、Kernel.php ファイルを通じてアプリケーション全体または特定のルートに適用できます。

Kernel.phpについて

Laravelの Kernel.php は、アプリケーションのリクエストライフサイクルを管理するファイルです。
以下2種類があります。

  • HTTPリクエストを管理するapp/Http/Kernel.php(☜ 今回使うのはこっち)
  • コンソールコマンドを管理する app/Console/Kernel.php

ミドルウェアの作成

LogQueries ミドルウェアを作ります。
クエリログを有効にし、リクエストの内容とクエリをログに出力する処理を実装します。

/laravel/app/Http/Middleware/LogQueries.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class LogQueries
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // クエリログを有効化
        DB::enableQueryLog();

        // リクエストの処理
        $response = $next($request);

        // クエリログを取得
        $queries = DB::getQueryLog();

        // リクエストとクエリログをログに出力
        Log::info('クエリログ:', [
            'method' => $request->getMethod(),
            'url' => $request->fullUrl(),
            'input' => $request->all(),
            'queries' => $queries,
        ]);

        return $response;
    }
}

ミドルウェアの登録

作成したミドルウェアを Kernel.php に登録し、APIのミドルウェアグループに追加します。

/laravel/app/Http/Kernel.php
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    // ... existing code ...

    protected $middlewareGroups = [
        'web' => [
            // ... existing middleware ...
        ],

        'api' => [
            ...
            \App\Http\Middleware\LogQueries::class, // ここに追加
        ],
    ];

    // ... existing code ...
}

これで完了です。
Laravelのログ設定に応じて、 APIリクエストが行われるたびにstorage/logs/laravel.logにログが出力されます。

出力されるログの例

[2024-06-24 15:05:26] local.INFO: クエリログ {"method":"GET","url":"https://.../get","input":[],"queries":["select count(*) as aggregate from \"..."]}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?