Installation:
composer require codetech/laravel-api-logs
The package auto-registers its service provider, but verify it exists in config/app.php under providers.
Run Migrations:
php artisan vendor:publish --provider="CodeTech\ApiLogs\Providers\ApiLogServiceProvider" --tag=migrations
php artisan migrate
This creates the api_logs table to store request data.
Enable Middleware:
Add LogApiRequest::class to the api middleware group in app/Http/Kernel.php:
'api' => [
\Illuminate\Routing\Middleware\ThrottleRequests::class,
\CodeTech\ApiLogs\Http\Middleware\LogApiRequest::class, // <-- Add this line
// ... other middleware
],
First Use Case:
Immediately start logging all API requests. No additional configuration is needed for basic usage. Logs will appear in the api_logs table with:
Logging All API Requests:
The middleware automatically logs every request routed through the api middleware group. No manual logging required in controllers.
Customizing Logged Data:
Extend the middleware to include additional fields. Override the LogApiRequest middleware in your project:
namespace App\Http\Middleware;
use CodeTech\ApiLogs\Http\Middleware\LogApiRequest as BaseLogApiRequest;
class LogApiRequest extends BaseLogApiRequest
{
protected function getLogData()
{
$data = parent::getLogData();
$data['custom_field'] = auth()->id(); // Example: Add user ID
return $data;
}
}
Update Kernel.php to use your custom middleware.
Conditional Logging:
Skip logging for specific routes by adding a skipApiLogging key to the route:
Route::get('/skip-logging', function () {
return response()->json(['message' => 'This won’t be logged']);
})->middleware('skipApiLogging');
Create a SkipApiLogging middleware to exclude routes.
Querying Logs:
Use Eloquent to fetch logs. The ApiLog model is available via:
use CodeTech\ApiLogs\Models\ApiLog;
$logs = ApiLog::where('status_code', 404)->latest()->get();
Integration with Existing Systems:
php artisan vendor:publish --provider="CodeTech\ApiLogs\Providers\ApiLogServiceProvider" --tag=views
api.logged event:
Event::listen('api.logged', function ($log) {
// Send to external service
});
API Rate Limiting + Logging:
Combine with throttle middleware to log rate-limited requests:
Route::middleware(['throttle:60,1', 'logApiRequest'])->group(function () {
// Rate-limited routes
});
Performance Overhead:
skipApiLogging middleware to critical paths.Sensitive Data Exposure:
getLogData() to sanitize inputs:
protected function getLogData()
{
$data = parent::getLogData();
unset($data['input']['password']); // Remove sensitive fields
return $data;
}
Migration Conflicts:
api_logs table already exists, the migration may fail. Use --force or manually merge columns:
php artisan migrate --force
Middleware Order Matters:
LogApiRequest after authentication middleware (e.g., auth:api) to include user context in logs:
'api' => [
\App\Http\Middleware\Authenticate::class,
\CodeTech\ApiLogs\Http\Middleware\LogApiRequest::class, // <-- After auth
],
Large Payloads:
protected function getLogData()
{
$data = parent::getLogData();
if (strlen(json_encode($data['input'])) > 1000) {
$data['input'] = 'Large payload truncated';
}
return $data;
}
Verify Middleware is Active:
Check if the middleware is registered in Kernel.php and that the route uses the api middleware group.
Check Log Table:
Inspect the api_logs table directly:
php artisan tinker
>>> \CodeTech\ApiLogs\Models\ApiLog::latest()->first();
Event Listeners:
Debug the api.logged event to ensure custom logic runs:
Event::listen('api.logged', function ($log) {
\Log::debug('Custom logic triggered for log ID: ' . $log->id);
});
Configuration Quirks:
config/logging.php settings.api_logs table is backed up regularly.Custom Log Model:
Extend the ApiLog model to add scopes or accessors:
namespace App\Models;
use CodeTech\ApiLogs\Models\ApiLog as BaseApiLog;
class ApiLog extends BaseApiLog
{
public function scopeFailed($query)
{
return $query->where('status_code', '>=', 400);
}
}
Dynamic Logging: Conditionally log requests based on route attributes:
Route::get('/admin', function () {
return response()->json(['data' => 'admin']);
})->middleware(['auth:admin', 'logApiRequest']);
Log Retention: Add a scheduled task to purge old logs (e.g., older than 30 days):
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('api:purge-logs')->daily();
}
Publish the package’s commands:
php artisan vendor:publish --provider="CodeTech\ApiLogs\Providers\ApiLogServiceProvider" --tag=commands
Response Logging: Log response data by extending the middleware:
protected function getLogData()
{
$data = parent::getLogData();
$data['response'] = response()->getContent();
return $data;
}
Warning: This can significantly increase storage usage. Use sparingly.
How can I help you explore Laravel packages today?