How to log all requests to a site with laravel-route-statistics

Overview

Logging stats of all requests to your sites can help you do the following:

  • Know how often specific users use your application and what they do.
  • Ascertain unauthenticated users’ engagement with the site, etc.

In turn, logging stats gives us statistical data that helps show us how to improve the site.

The laravel-route-statistics package

In this shot, we will use the laravel-route-statistics package to allow us to add the user monitoring functionality.

laravel-route-statistics basically enables us to log requests and responses from our application.

Package installation

Run the following command in your command line to install the package and ensure your network is strong during this process.


composer require bilfeldt/laravel-route-statistics

Publishing and migration

  • Step 1: Vendor publish generates the schema of the migration.

php artisan vendor:publish --provider="Bilfeldt\LaravelRouteStatistics\LaravelRouteStatisticsServiceProvider" --tag="migrations"

  • Step 2: Migrating Database. Migration sets a template table where all the logged data is stored.

php artisan migrate

  • Step 3: Publishing config file.

php artisan vendor:publish --provider="Bilfeldt\LaravelRouteStatistics\LaravelRouteStatisticsServiceProvider" --tag="config"

Implementation

In my previous shot, we saw how to do log stats from a controller, which enabled us to get login information for a specific function in a controller.

Code

In this shot, we will log the entire request to our site.

We do that from the app/Http/Kernel.php by registering/adding the RouteStatisticsMiddleware middleware, like so:

// app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
protected $middleware = [
\Bilfeldt\LaravelRouteStatistics\Http\Middleware\RouteStatisticsMiddleware::class, // <-- The middleware we added
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

Output

The code returns the frequency of the route being visited, which is then used graphically, like so:

widget

The graph depends on how you want to represent your data.

Explanation

Notice how we add the middleware at the top. This is to ensure that it logs every request first before other middleware interacts with the request.

Free Resources