Log requests and group together for aggregated statistics of route usage

Overview

Log Laravel route usage statistics

bilfeldt/laravel-route-statistics

Latest Version on Packagist GitHub Tests Action Status StyleCI Code Style Status Total Downloads

Log Laravel requests and responses for statistical purposes and optionally aggregate by hours/days/months for minimal db requirements.

Description

Log requests and group them together for aggregated statistics of route usage. Grouping requests by route means that this package saves a minimum of data to the database and subsequent purging of old data can improve this even further.

This package lets you:

  • See how much each user uses the application and what part of the application they use
  • See if any unauthenticated users are making a lot of requests to your application

Installation

You can install the package via composer:

composer require bilfeldt/laravel-route-statistics

You can publish and run the migrations with:

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

You can publish the config file with:

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

Usage

There are a few ways to enable logging of route usage:

Enable global logging

This will enable site-wide logging and although being the easiest implementation this might not be exactly what you are looking for (consider only logging relevant routes using the middleware approach below)

Simply add RouteStatisticsMiddleware as a global middleware in app/Http/Kernel.php

// app/Http/Kernel.php
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Bilfeldt\LaravelRouteStatistics\Http\Middleware\RouteStatisticsMiddleware::class, // <-- 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,
    ];
...

Enable via middleware

Instead of adding RouteStatisticsMiddleware as a global middleware then it can be added to certain routes or route groups using:

Route::middleware(['routestatistics'])->...

Enable using request macro

It is possible to enable logging ad-hoc, usually within a controller, which is useful for any conditional logging:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index(Request $request)
    {
        $request->routeStatistics(); // This will enable route statistics logging
    
        return view('home');
    }
}

How it works

This package works as follows:

  1. Tag the request for logging: Can be done using middleware or request helper
  2. (optional) Add any context data which will be used when logging: A common use case is adding relevant route parameters like a team_id for example
  3. Log the request: Persist the log record to the database - the following will be logged when using the default logger:
  • user_id: The authenticated user (if any)
  • team_id: The team id associated with the request (if available)
  • method: The HTTP method (GET/POST/...)
  • route: The route name (if available) or the route URI (eg /posts/{post})
  • status: The HTTP status (eg 202)
  • ip: The request ip
  • date: The date of the request as datetime (can be aggregated)
  • counter: Number of requests logged when aggregating records by minute/hour/day/month...

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.
This package provides convenient methods for making token code, sending and verifying mobile phone verification requests.

Laravel Mobile Verification Introduction Many web applications require users to verify their mobile phone numbers before using the application. Rather

Execute Laravel Artisan commands via REST APIs and HTTP requests safely.

Artisan Api There might be some times you wanted to execute an Artisan command, but you did not have access to shell or SSH. Here we brought REST API

Log executed Laravel SQL queries and their line number and more

A lightweight laravel package for logging executed SQL queries, line number and more

Dashboard to view your http client requests in laravel application
Dashboard to view your http client requests in laravel application

Laravel Blanket is a package with wraps laravel http client requests and provide logs for request and response, also give option to retry any request from dashboard and more...

Make requests to the Shopify API from your Laravel app
Make requests to the Shopify API from your Laravel app

Make requests to the Shopify API from your Laravel app The signifly/laravel-shopify package allows you to easily make requests to the Shopify API. Ins

Laravel magical helpers such as Controllers / Requests / Models

Laravel Magic provides Abstract Controller, Model, generic Request, Traits, Exceptions and various middlewares in order to generate very easily and quickly API resources from scratch.

Log activity inside your Laravel app
Log activity inside your Laravel app

Log activity inside your Laravel app The spatie/laravel-activitylog package provides easy to use functions to log the activities of the users of your

Record the change log from models in Laravel

This package will help you understand changes in your Eloquent models, by providing information about possible discrepancies and anomalies that could

This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

Comments
  • Implement artisan command

    Implement artisan command

    Implement an artisan command for showing route statistics in a table view

    • Option array for group (example: --group=user --group=date)
    • Option for filtering by user (--user=123)
    • Option for filtering by team (--team=123)
    • Option for filtering by method (--method=GET)
    • Option for filtering by route (--route='api.example')
    • Option for filtering by code (--code=200 note that it would be nice to accept a syntax like `--code=2xx' or '--code=2%')
    • Option for filtering by ip (--ip='192.168.0.102' note that it would be nice to accept a syntax like `--ip=192.168.0.*' or '--ip=192.168.%')
    • Option for filtering by date (--date=2021-01-22 should return everything on that day - how to select the level, from config or another option?)
    • Option for amount of returned results (default =20)
    enhancement 
    opened by bilfeldt 2
  • Streamed responses fail with call to undefined method

    Streamed responses fail with call to undefined method

    Description

    When returning a streamed response (download of file) then the following error is thrown:

    Call to undefined method Symfony\Component\HttpFoundation\StreamedResponse::status()
    

    which is caused by

    $event->response->status() // src/Listeners/LogRouteStatistics.php:26
    

    Flare error: https://flareapp.io/share/x5MqjZe5

    Steps to recreate

    1. Add a csv file to a disk
    2. Add the route below
    3. Visit the route /test in a browser
    // web.php
    
    Route::get('/test', function () {
        return Storage::download('test.csv');
    });
    
    bug 
    opened by bilfeldt 1
  • Artisan command for unused routes

    Artisan command for unused routes

    Implement an artisan command showing unused routes route:unused

    Note that this is already possible using the following package: https://laravel-news.com/route-usage-package-for-laravel

    Motivation

    This way, the package could act as a sort of automatic tombstoning service for routes.

    Thanks for the idea @JackWH

    Syntax

    php artisan route:unused // List all unused routes
    // or specifying a date
    php artisan route:unused '-30 days' // List all routes that have not been used in the last 30 days (input converted to Carbon)
    

    Notes

    This command can probably easily be implemented by extending the route:list command and overriding the filterRoute(array $route) method and the getRouteInformation() method (to add two extra columns last used at and counter)

    Note that if there is no stats recorded then it should exit with an error - just like it does when the application does not have any routes

    enhancement 
    opened by bilfeldt 0
  • v0.4.0

    v0.4.0

    See CHANGELOG.md:

    • Remove the facade and listener and instead rely on the bilfeldt/laravel-request-logger package for actual logging.
    • Remove RouteStatisticInterface in favor of \Bilfeldt\RequestLogger\Contracts\RequestLoggerInterface
    • Remove attributes from log method
    • Rename \Bilfeldt\LaravelRouteStatistics\Http\Middleware\RouteStatistics to RouteStatisticsMiddleware
    • Set minimum Laravel requirement to ^8.50
    • Note that this release contains breaking changes if one interacting with the facade, model, listener or interface directly but for those simply relying on the default macros and middleware there is no problem updating.
    opened by bilfeldt 0
Releases(v1.2.0)
  • v1.2.0(Jan 30, 2022)

    What's Changed

    • Add Laravel 9 support by @bilfeldt in https://github.com/bilfeldt/laravel-route-statistics/pull/14

    Full Changelog: https://github.com/bilfeldt/laravel-route-statistics/compare/v1.1.0...v1.2.0

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Dec 23, 2021)

    What's Changed

    • Fix name of middleware in README.md by @bilfeldt in https://github.com/bilfeldt/laravel-route-statistics/pull/8
    • Add query scopes whereApi and whereWeb by @bilfeldt in https://github.com/bilfeldt/laravel-route-statistics/pull/11
    • PHP 8.1 compatible by @bilfeldt in https://github.com/bilfeldt/laravel-route-statistics/pull/10
    • Add a new route:stats artisan command to show statistics by @bilfeldt in https://github.com/bilfeldt/laravel-route-statistics/pull/12
    • Add a new route:unused artisan command to show all unused routes by @bilfeldt in https://github.com/bilfeldt/laravel-route-statistics/pull/13

    Full Changelog: https://github.com/bilfeldt/laravel-route-statistics/compare/v1.0.0...v1.1.0

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Nov 12, 2021)

  • v0.5.0(Nov 10, 2021)

    • Breaking change: Rename field code to status
    • Cast date field to Carbon

    Full Changelog: https://github.com/bilfeldt/laravel-route-statistics/compare/v0.4.0...v0.5.0

    Source code(tar.gz)
    Source code(zip)
  • v0.4.0(Nov 9, 2021)

    What's Changed

    • v0.4.0 by @bilfeldt in https://github.com/bilfeldt/laravel-route-statistics/pull/4

    See CHANGELOG.md:

    • Remove the facade and listener and instead rely on the bilfeldt/laravel-request-logger package for actual logging.
    • Remove RouteStatisticInterface in favor of \Bilfeldt\RequestLogger\Contracts\RequestLoggerInterface
    • Remove attributes from log method
    • Rename \Bilfeldt\LaravelRouteStatistics\Http\Middleware\RouteStatistics to RouteStatisticsMiddleware
    • Set minimum Laravel requirement to ^8.50
    • Note that this release contains breaking changes if one interacting with the facade, model, listener or interface directly but for those simply relying on the default macros and middleware there is no problem updating.

    Full Changelog: https://github.com/bilfeldt/laravel-route-statistics/compare/v0.3.0...v0.4.0

    Source code(tar.gz)
    Source code(zip)
  • v0.3.0(Apr 27, 2021)

  • v0.2.0(Apr 20, 2021)

  • v0.1.1(Apr 19, 2021)

  • v0.1.0(Apr 19, 2021)

Owner
Bilfeldt
Bilfeldt
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

null 9 Dec 14, 2022
Links statistics & link tracking for laravel 5, It tracks down browsers, operating systems, languages and more

Links Links statistics for laravel 5 Table Of Contents Installation Configuration Usage Installation To install charts use composer Download composer

Erik C. Forés 52 Jul 31, 2021
A Laravel Statistics SDK

laravel-statistics shanjing laravel-statistics是一个基于 laravel 开发而成的统计工具,只需很少的代码即可快速构建出一个功能完善的统计模块。开箱即用,对后端开发者非常友好。 功能特性 简洁优雅 API 当缺失对应日期的数据时,自动补充 0 作为默认

青岛山景信息技术有限公司 2 Dec 14, 2022
Quickly identify controller methods with no route in your Laravel applications.

Orphan Controller Quickly identify controller methods with no route in your Laravel applications. Installation You can install the package via Compose

Ryan Chandler 16 Feb 18, 2022
A simple laravel package to handle multiple key based model route binding

Laravel Model UUID A simple package to handle the multiple key/column based route model binding for laravel package Installation Require the package u

null 13 Mar 2, 2022
Gretel is a Laravel package for adding route-based breadcrumbs to your application.

Gretel Laravel breadcrumbs right out of a fairy tale. Gretel is a Laravel package for adding route-based breadcrumbs to your application. Defining Bre

Galahad 131 Dec 31, 2022
an opensourced roblox group finder writen in python 100% free and virus-free

Roblox-Group-Finder an opensourced roblox group finder writen in python 100% free and virus-free note : if you don't want install python or just use w

mollomm1 1 Nov 11, 2021
Laravel 101 presentation for the Winnipeg PHP Meetup group

Laravel 101 Slides These are the slides I used for my "Laravel 101" presentation at the Winnipeg PHP Meetup on March 26, 2014. The slideshow framework

Colin Viebrock 10 Oct 6, 2022
A package that helps to group methods that mostly use for the view presentation purpose.

A package that helps to group methods that mostly use for the view presentation purpose form models to a dedicated presenter class.

Touhidur Rahman 9 Apr 26, 2022
An example chat app to illustrate the usage of kitar/laravel-dynamodb.

Simplechat An example chat app to illustrate the usage of kitar/laravel-dynamodb. Demo https://demo.simplechat.app/ This demo app is deployed with Lar

Satoshi Kita 38 Nov 22, 2022