Appearance
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
Clone the repository:
bashgit clone <repository_url> cd <project_directory>Run the migration to create the
api_logstable:bashphp 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.
Create the ApiLog Model:
bashphp artisan make:model ApiLogphpnamespace 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', ]; }Create the API Log Middleware:
bashphp artisan make:middleware ApiLogMiddlewarephpnamespace 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; } }Register the Middleware:
Open
app/Http/Kernel.phpand register theApiLogMiddlewarein theapimiddleware group.phpprotected $middlewareGroups = [ 'api' => [ \App\Http\Middleware\ApiLogMiddleware::class, // other middlewares (optional) ], ];