PHPackages                             sl-projects/laravel-request-logger - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. sl-projects/laravel-request-logger

ActiveLibrary

sl-projects/laravel-request-logger
==================================

A Laravel package to log all incoming HTTP requests

v1.0.10(10mo ago)03.0k↓100%MITPHPPHP ^8.2CI passing

Since Dec 14Pushed 8mo ago1 watchersCompare

[ Source](https://github.com/SofianeLasri/laravel-request-logger)[ Packagist](https://packagist.org/packages/sl-projects/laravel-request-logger)[ RSS](/packages/sl-projects-laravel-request-logger/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (4)Versions (12)Used By (0)

Laravel Request Logger
======================

[](#laravel-request-logger)

[![Latest Version](https://camo.githubusercontent.com/5f07f90e6d4e3f7a0284178ec1ed3332e2259f7e39ec9fb6368020df6f5ba8eb/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f536f6669616e654c617372692f6c61726176656c2d726571756573742d6c6f67676572)](https://github.com/SofianeLasri/laravel-request-logger/releases)[![License](https://camo.githubusercontent.com/14eb86433f7ae84349dd9792c543a8779c8dff9b643c6779a212b899a08f6a49/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f536f6669616e654c617372692f6c61726176656c2d726571756573742d6c6f67676572)](LICENSE)[![codecov](https://camo.githubusercontent.com/10772b2b77fa86dd6c36a8197d85de782b8b4aa398dedf8eba9c28cb1761158e/68747470733a2f2f636f6465636f762e696f2f67682f536f6669616e654c617372692f6c61726176656c2d726571756573742d6c6f676765722f67726170682f62616467652e7376673f746f6b656e3d5932424b4d335a4d4656)](https://codecov.io/gh/SofianeLasri/laravel-request-logger)[![PHP Version](https://camo.githubusercontent.com/63ea83e71c3fd48b050214ac4d72f1ea643152513b507c5efd71d19ed4c058d0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f736c2d70726f6a656374732f6c61726176656c2d726571756573742d6c6f67676572)](https://packagist.org/packages/sl-projects/laravel-request-logger)[![Laravel Version](https://camo.githubusercontent.com/a0d797cb08f8a5cde88d57c17b5969d51669a589328ecf98eaa11f04aad1d31c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31312e392532422d6f72616e6765)](https://laravel.com)

A high-performance Laravel package for logging and analyzing HTTP requests with minimal overhead. Built with a cache-first approach and normalized database structure for efficient storage and querying.

**NOTE:** This package has no connection with the Laravel framework or its creators. It is an independent project developed by [Sofiane Lasri](https://sofianelasri.fr), mainly for educational purposes.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Configuration](#configuration)
    - [For Laravel 11+ (New Structure)](#for-laravel-11-new-structure)
    - [For Laravel 10 and Earlier](#for-laravel-10-and-earlier)
- [Usage](#usage)
- [Advanced Features](#advanced-features)
- [Database Schema](#database-schema)
- [Performance Considerations](#performance-considerations)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

Features
--------

[](#features)

- 🚀 **High Performance**: Cache-first approach ensures zero impact on request processing
- 📊 **Normalized Database**: Efficient storage with deduplicated entities (IPs, URLs, User Agents, MIME types)
- 🔄 **Async Processing**: Background job processing for database persistence
- 📈 **Rich Data Capture**: Logs IP addresses, HTTP methods, status codes, response times, and more
- 🌍 **GeoIP Support**: Automatic country code detection from IP addresses
- 🛠️ **Fully Configurable**: Customize cache TTL, storage keys, and processing behavior
- 🧪 **100% Tested**: Comprehensive test coverage with factories for all models
- 🔒 **Thread-Safe**: Cache locking prevents race conditions in high-traffic scenarios

Requirements
------------

[](#requirements)

- PHP 8.2 or higher
- Laravel 11.9+ (with support for Laravel 12)
- Redis or Memcached recommended for caching (fallback to file cache supported)

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require sl-projects/laravel-request-logger
```

Run the migrations to create the necessary database tables:

```
php artisan migrate
```

(Optional) Publish the configuration file for customization:

```
php artisan vendor:publish --tag=request-logger-config
```

Configuration
-------------

[](#configuration)

### For Laravel 11+ (New Structure)

[](#for-laravel-11-new-structure)

Laravel 11 introduced a new application structure with simplified configuration. Here's how to set up the package:

#### 1. Register Middleware

[](#1-register-middleware)

In `bootstrap/app.php`:

```
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
use SlProjects\LaravelRequestLogger\app\Http\Middleware\SaveRequestMiddleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        // Global middleware (logs all requests)
        $middleware->append(SaveRequestMiddleware::class);

        // OR for specific routes only
        $middleware->appendToGroup('web', SaveRequestMiddleware::class);

        // OR create an alias for selective use
        $middleware->alias([
            'log.request' => SaveRequestMiddleware::class,
        ]);
    })
    ->create();
```

#### 2. Schedule the Command

[](#2-schedule-the-command)

In `routes/console.php`:

```
use Illuminate\Support\Facades\Schedule;

Schedule::command('save:requests')->everyMinute();
```

### For Laravel 10 and Earlier

[](#for-laravel-10-and-earlier)

For Laravel versions 10 and below, use the traditional configuration approach:

#### 1. Register Middleware

[](#1-register-middleware-1)

In `app/Http/Kernel.php`:

```
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;
use SlProjects\LaravelRequestLogger\app\Http\Middleware\SaveRequestMiddleware;

class Kernel extends HttpKernel
{
    // Global middleware (logs all requests)
    protected $middleware = [
        // ... other middleware
        SaveRequestMiddleware::class,
    ];

    // OR for web routes only
    protected $middlewareGroups = [
        'web' => [
            // ... other middleware
            SaveRequestMiddleware::class,
        ],
    ];

    // OR create an alias for selective use
    protected $middlewareAliases = [
        // ... other aliases
        'log.request' => SaveRequestMiddleware::class,
    ];
}
```

#### 2. Schedule the Command

[](#2-schedule-the-command-1)

In `app/Console/Kernel.php`:

```
namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    protected function schedule(Schedule $schedule): void
    {
        $schedule->command('save:requests')->everyMinute();
    }
}
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Once configured, the package automatically logs all incoming requests. The middleware captures request data in the `terminate()` method to ensure zero impact on response times.

### Selective Logging

[](#selective-logging)

Apply middleware to specific routes only:

```
// Laravel 11+ (routes/web.php)
Route::middleware(['log.request'])->group(function () {
    Route::get('/api/users', [UserController::class, 'index']);
    Route::post('/api/users', [UserController::class, 'store']);
});

// Or for individual routes
Route::get('/dashboard', DashboardController::class)
    ->middleware('log.request');
```

### Manual Processing

[](#manual-processing)

Process cached requests manually without waiting for the scheduler:

```
php artisan save:requests
```

### Querying Logged Requests

[](#querying-logged-requests)

```
use SlProjects\LaravelRequestLogger\app\Models\LoggedRequest;

// Get all requests from a specific IP
$requests = LoggedRequest::with(['ipAddress', 'url', 'userAgent'])
    ->whereHas('ipAddress', function ($query) {
        $query->where('ip', '192.168.1.1');
    })
    ->get();

// Get requests by status code
$errors = LoggedRequest::where('status_code', '>=', 400)
    ->where('status_code', '
