How to log requests in Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Laravel, a powerful MVC framework for PHP, offers tools for robust application logging. By logging HTTP requests, developers can debug and monitor their applications, understanding user interactions and quickly identifying issues. This tutorial will cover different methods of logging requests, starting from basic techniques to more advanced solutions using middleware and event listeners.

Prerequisites

  • PHP >= 7.2.5 installed
  • Composer installed
  • A Laravel application setup

Basic Logging

Let’s start with the most straightforward method of logging a request. Laravel’s built-in logger, based on the popular Monolog library, can be accessed via the Log facade.

Example:

use Illuminate\Support\Facades\Log;

Route::get('/example', function () {
    Log::info('Example route has been hit.');
    return 'Logged the info';
});

Output in log file:

[timestamp] production.INFO: Example route has been hit.

Logging Request Data

Beyond basic logging, capturing the request data provides context for each log entry. A simple way to do this is by utilizing the request() helper within your routes or controllers.

Example:

use Illuminate\Support\Facades\Log;

Route::post('/submit', function () {
    Log::info('Form submitted', ['data' => request()->all()]);
    return 'Form data logged';
});

Output in log file:

[timestamp] production.INFO: Form submitted {"data":{"name":"John Doe", "email":"[email protected]"}}

Advanced Logging with Middleware

For applications requiring systematic logging on multiple routes, implementing a middleware is the way to go. Middleware allows you to intercept every HTTP request and response, making it an ideal place to incorporate logging logic.

Creating a Middleware

To create a custom middleware, run the Artisan command:

php artisan make:middleware LogHttpRequests

Then, insert your logging logic within the handle method:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogHttpRequests
{
    public function handle($request, Closure $next)
    {
        Log::debug('Request logged', [
            'url' => $request->url(),
            'method' => $request->method(),
            'data' => $request->all()
        ]);

        return $next($request);
    }
}

You then register your middleware in the $middleware array of your app/Http/Kernel.php file for global logging or leverage the Route middleware groups for more granular control.

Using Middleware

Global Middleware example:

protected $middleware = [
    // ...
    \App\Http\Middleware\LogHttpRequests::class,
];

Route Middleware example:

Route::middleware(['web', 'log.http'])->group(function () {
    Route::get('/home', 'HomeController@index');
    // Other routes...
});

By referring to the middleware log.http, you ensure that all routes within the group are logged.

Integrating Advanced Logging With Event Listeners

To observe request logging with more granularity or to perform additional actions upon logging, you can implement event listeners. Laravel fires various events during the request lifecycle, which can be used as triggers for logging.

Creating and Registering an Event Listener

Create an event listener using Artisan and write a listener for the RequestHandled event:

php artisan make:listener LogRequestEvent --event=RequestHandled

In your generated listener:

namespace App\Listeners;

use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Support\Facades\Log;

class LogRequestEvent
{
    public function handle(RequestHandled $event)
    {
        Log::info('Request Handled', [
            'request' => $event->request->toArray(),
            'response' => strval($event->response)
        ]);
    }
}

Then, register your listener for the RequestHandled event within the EventServiceProvider.

protected $listen = [
    \Illuminate\Foundation\Http\Events\RequestHandled::class => [
        'App\Listeners\LogRequestEvent',
    ],
];

This ensures your logging logic is called each time the event is fired.

Conclusion

Logging requests in Laravel can be as straightforward or elaborate as your application requires. Whether you are simply logging requests to a file or orchestrating detailed records with middleware and event listeners, Laravel provides all the tools to effectively monitor and analyze HTTP requests.