Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Request Logger Laravel Package

bilfeldt/laravel-request-logger

Log incoming HTTP requests in Laravel with a simple middleware. Capture method, URL, headers, payload, response status and timing, then store to database or logs for debugging, auditing and performance insights. Configurable, lightweight, easy to add to routes or globally.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bilfeldt/laravel-request-logger
    php artisan vendor:publish --provider="Bilfeldt\RequestLogger\RequestLoggerServiceProvider" --tag="request-logger-migrations"
    php artisan migrate
    
  2. First Use Case: Enable logging for a route via middleware:

    Route::middleware('requestlog')->get('/api/endpoint', [YourController::class, 'method']);
    

    This logs the request/response to the database with minimal configuration.

Key Configuration

  • Publish the config file for customization:
    php artisan vendor:publish --provider="Bilfeldt\RequestLogger\RequestLoggerServiceProvider" --tag="request-logger-config"
    
  • Configure log_methods or log_statuses in config/request-logger.php to filter logs (e.g., ['*'] for all requests or ['5**'] for server errors).

Implementation Patterns

1. Middleware-Based Logging

  • Route-Level Control:

    Route::middleware(['requestlog'])->group(function () {
        Route::get('/admin', [AdminController::class, 'index']);
        Route::post('/api/webhook', [WebhookController::class, 'handle']);
    });
    
    • Useful for API endpoints or admin panels where detailed logging is critical.
  • Conditional Logging:

    Route::middleware(['requestlog:custom-driver'])->get('/debug', [DebugController::class, 'log']);
    
    • Leverage custom drivers (e.g., S3, external APIs) for specialized logging needs.

2. Dynamic Logging via Request Macro

  • Enable logging in controllers:
    public function sensitiveAction(Request $request) {
        $request->enableLog(); // Logs this specific request
        // ...
    }
    
    • Ideal for critical actions (e.g., payments, data exports) where logging is context-dependent.

3. Integration with Existing Workflows

  • Error Handling: Combine with Laravel’s App\Exceptions\Handler to log failed requests automatically:

    public function register() {
        $this->renderable(function (Throwable $e, $request) {
            $request->enableLog(); // Log failed requests
            return response()->view('errors.500');
        });
    }
    
  • Testing: Mock the RequestLog model in tests:

    $this->partialMock(RequestLog::class, function ($mock) {
        $mock->shouldReceive('create')->once();
    });
    

4. Custom Drivers

  • Extend the package by creating a custom driver (e.g., for Elasticsearch):
    // app/Providers/RequestLoggerServiceProvider.php
    public function register() {
        $this->app->extend('request-logger', function () {
            return new ElasticsearchLogger();
        });
    }
    
    • Use in middleware:
    Route::middleware(['log:elasticsearch'])->get('/search', [SearchController::class, 'index']);
    

Gotchas and Tips

Pitfalls

  1. Performance Overhead:

    • Logging every request adds latency. Use middleware selectively (e.g., exclude health checks):
      'log_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], // Exclude OPTIONS, etc.
      
  2. Database Bloat:

    • Prune logs regularly via scheduled command:
      // app/Console/Kernel.php
      protected function schedule(Schedule $schedule) {
          $schedule->command('requestlog:prune')->dailyAt('2:00');
      }
      
    • For large-scale apps, use a dedicated database connection:
      REQUEST_LOGGER_DB_CONNECTION=logging
      
  3. Sensitive Data Leakage:

    • Exclude sensitive headers/params by default (e.g., api_token):
      'headers' => ['authorization', 'cookie'],
      'parameters' => ['password', 'credit_card'],
      
  4. Proxy/Load Balancer IPs:

    • Trusted proxies must be configured in config/trustedproxies.php to log client IPs correctly:
      'proxies' => ['192.168.1.1', '10.0.0.1'],
      

Debugging Tips

  1. Verify Logging: Check the request_logs table for entries after triggering a logged request. Use Laravel Scout for real-time monitoring:

    php artisan tinker
    >>> \Bilfeldt\RequestLogger\RequestLog::latest()->first();
    
  2. Middleware Debugging: Add a temporary log to diagnose middleware issues:

    Route::middleware(['requestlog', function ($request, $next) {
        \Log::info('Middleware executed', ['path' => $request->path()]);
        return $next($request);
    }])->get('/test', [TestController::class, 'index']);
    
  3. Custom Driver Issues:

    • Ensure the driver implements Bilfeldt\RequestLogger\Contracts\Logger:
      class ElasticsearchLogger implements Logger {
          public function log(Request $request, Response $response) {
              // Implementation
          }
      }
      

Extension Points

  1. Modify Logged Data: Override the RequestLog model to customize fields:

    // app/Models/CustomRequestLog.php
    class CustomRequestLog extends \Bilfeldt\RequestLogger\RequestLog {
        protected $casts = [
            'user_agent' => 'encrypted', // Encrypt sensitive UAs
        ];
    }
    

    Update config:

    'model' => \App\Models\CustomRequestLog::class,
    
  2. Add Metadata: Use the LogContextMiddleware (from bilfeldt/laravel-correlation-id) to attach context:

    Route::middleware(['requestlog', 'log-context'])->get('/tracked', [TrackedController::class, 'index']);
    
  3. Filtering: Dynamically exclude routes in middleware:

    public function handle($request, Closure $next) {
        if ($request->is('health*')) return $next($request);
        return parent::handle($request, $next);
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky