Skip to content

API Logging for Laravel

This repository includes a feature to log API requests, responses, and errors for monitoring and debugging purposes. The logs capture information such as the request method, endpoint, request and response data, status codes, user agent, IP address, and response time.

Features

  • Logs each API request and response.
  • Captures request data, response data, and status codes.
  • Logs the IP address and user agent of the client.
  • Logs any exceptions or errors thrown during the request lifecycle.
  • Tracks response time for performance monitoring.
  • Easily configurable to log additional headers or custom fields.

Installation

  1. Clone the repository:

    bash
    git clone <repository_url>
    cd <project_directory>
  2. Run the migration to create the api_logs table:

    bash
    php artisan migrate
php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateApiLogsTable extends Migration
{
   /**
    * Run the migrations.
    *
    * @return void
    */
   public function up()
   {
       Schema::create('api_logs', function (Blueprint $table) {
           $table->id();
           $table->string('endpoint');
           $table->string('method');
           $table->json('request_data');
           $table->json('response_data');
           $table->integer('status_code');
           $table->string('ip_address');
           $table->string('user_agent');
           $table->unsignedBigInteger('response_time'); // in milliseconds
           $table->timestamps();
       });
   }

   /**
    * Reverse the migrations.
    *
    * @return void
    */
   public function down()
   {
       Schema::dropIfExists('api_logs');
   }
}

This will create the api_logs table in your database.

  1. Create the ApiLog Model:

    bash
    php artisan make:model ApiLog
    php
    namespace App\Models;
    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;
    
    class ApiLog extends Model
    {
    use HasFactory;
    
    protected $fillable = [
        'endpoint',
        'method',
        'request_data',
        'response_data',
        'status_code',
        'ip_address',
        'user_agent',
        'response_time',
    ];
    
    protected $casts = [
        'request_data' => 'array',
        'response_data' => 'array',
    ];
    }
  2. Create the API Log Middleware:

    bash
    php artisan make:middleware ApiLogMiddleware
    php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    use App\Models\ApiLog;
    use Illuminate\Support\Facades\Log;
    
    class ApiLogMiddleware
    {
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Capture start time
        $startTime = microtime(true);
    
        // Proceed with the request
        $response = $next($request);
    
        // Capture response time
        $responseTime = round((microtime(true) - $startTime) * 1000); // in milliseconds
    
        // Log the API request and response
        $logData = [
            'endpoint' => $request->path(),
            'method' => $request->method(),
            'request_data' => $request->all(),
            'response_data' => json_decode($response->getContent(), true),
            'status_code' => $response->status(),
            'ip_address' => $request->ip(),
            'user_agent' => $request->header('User-Agent'),
            'response_time' => $responseTime,
        ];
    
        ApiLog::create($logData);
    
        return $response;
    }
    }
  3. Register the Middleware:

    Open app/Http/Kernel.php and register the ApiLogMiddleware in the api middleware group.

    php
    protected $middlewareGroups = [
        'api' => [
            \App\Http\Middleware\ApiLogMiddleware::class,
            // other middlewares (optional)
        ],
    ];