PHPackages                             robertogallea/laravel-metrics - 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. [Logging &amp; Monitoring](/categories/logging)
4. /
5. robertogallea/laravel-metrics

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

robertogallea/laravel-metrics
=============================

Instrument your Laravel application with smart metrics

0.5.1(4y ago)141493PHPPHP ^7.2|^8.0CI failing

Since Jan 9Pushed 4y ago1 watchersCompare

[ Source](https://github.com/robertogallea/LaravelMetrics)[ Packagist](https://packagist.org/packages/robertogallea/laravel-metrics)[ RSS](/packages/robertogallea-laravel-metrics/feed)WikiDiscussions master Synced 2d ago

READMEChangelogDependencies (7)Versions (11)Used By (0)

LaravelMetrics [![](https://camo.githubusercontent.com/6860c220a291d84851b760e3d693468bfa598f82c8900fd910d1d32510f2f0d1/68747470733a2f2f696d6167652e666c617469636f6e2e636f6d2f69636f6e732f7376672f313334302f313334303130352e737667)](https://camo.githubusercontent.com/6860c220a291d84851b760e3d693468bfa598f82c8900fd910d1d32510f2f0d1/68747470733a2f2f696d6167652e666c617469636f6e2e636f6d2f69636f6e732f7376672f313334302f313334303130352e737667)
====================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#laravelmetrics-)

[![Packagist Version](https://camo.githubusercontent.com/525768efdfff6b8b2841bfcecdbb5f358ec49b854a5256a801ffb34a795aa3f1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726f626572746f67616c6c65612f6c61726176656c2d6d657472696373)](https://camo.githubusercontent.com/525768efdfff6b8b2841bfcecdbb5f358ec49b854a5256a801ffb34a795aa3f1/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f726f626572746f67616c6c65612f6c61726176656c2d6d657472696373)[![GitHub Workflow Status](https://camo.githubusercontent.com/93980bca9078b9eb934966dc1dd21dc1f538675a6d2e39290c99ab0795e9b3a7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f726f626572746f67616c6c65612f4c61726176656c4d6574726963732f52756e25323074657374733f6c6162656c3d7465737473)](https://camo.githubusercontent.com/93980bca9078b9eb934966dc1dd21dc1f538675a6d2e39290c99ab0795e9b3a7/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f776f726b666c6f772f7374617475732f726f626572746f67616c6c65612f4c61726176656c4d6574726963732f52756e25323074657374733f6c6162656c3d7465737473)

Introduction
------------

[](#introduction)

This package allows to record metrics in your laravel application and performing statistics.

It also provides tools for implementing simple alerting mechanisms.

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

[](#installation)

In order to install the package run

`composer require robertogallea/laravel-metrics`

Laravel auto-discovery will register package ServiceProvider and Aliases.

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

[](#configuration)

If you wish to edit the package configuration run

```
php artisan vendor:publish --provider=robertogallea\\LaravelMetrics\\MetricsServiceProvider --tag=config
```

Usage
-----

[](#usage)

The package relies on the concept of `Metric`. A metric is a measure of some type inside the application.

Currently, two types of measures are supported:

- `Markers`
- `Timers`

`Markers` are just their name. These could be used to determine how many times an event occurred in your application.

`Timers` tracks events duration. These could be useful to determine how long events took to complete.

### Save metrics

[](#save-metrics)

This is the simplest way of using metrics. In any part of your code you can save metrics as follows:

- Markers:

```
$registry = resolve(MetricRegistry::class);
$marker = $registry->meter('metric-name');

$marker->mark();

// or you can use facade
$marker = \Metrics::meter('metric-name');

$marker->mark();
```

- Timers

```
$registry = resolve(MetricRegistry::class);
$timer = $registry->meter('metric-name', MeterType::TIMER);

$timerId = $timer->start();

// or you can use facade
$timer = \Metrics::meter('metric-name', MeterType::TIMER);

$timerId = $timer->start();

doSomething();

$timer->stop($timerId);
```

By default, timers are stored using `seconds` resolution. However, desired resolution can be changed before stopping the timer:

```
$timer->inMicrosceconds()->stop($timerId);
$timer->inMilliseconds()->stop($timerId);
$timer->inSeconds()->stop($timerId);
$timer->inMinutes()->stop($timerId);
$timer->inHours()->stop($timerId);
$timer->inDays()->stop($timerId);
$timer->inWeeks()->stop($timerId);
$timer->inMonths()->stop($timerId);
$timer->inYears()->stop($timerId);
```

#### Storing metadata

[](#storing-metadata)

If needed, you can also store additional metadata in your metrics, by passing a data array to the `mark()` or `start()/stop()` methods:

Marker

```
$data = ['key' => 'value'];
$marker->mark($data);
```

Timer

```
$data = ['key' => 'value'];
$timerId = $timer->start($data);

doSomething();

$timer->stop($timerId);
```

or

```
$timerId = $timer->start();

$data = doSomething();

$timer->stop($timerId, $data);
```

### Measuring events

[](#measuring-events)

You could automatically save marker metrics during event dispatch by doing three steps:

- Implementing the `PerformsMetrics` interface;
- Using the `Measurable` trait;
- Defining the `$meter` field with the name you want to use for your metric.

```
class TestEvent implements PerformsMetrics
{
    use Dispatchable;
    use Measurable;

    protected $meter = 'test';
}
```

Now, whenever you dispatch an event, the marker is automatically saved:

```
event(new TestEvent());
```

#### Creating measurable events

[](#creating-measurable-events)

For your convenience a command is registered for creating measurable events:

```
php artisan make:measurable-event MyMeterEvent
```

### Measuring requests

[](#measuring-requests)

You can also instrument your requests by using two middlewares provided:

```
Route::get('/', 'HomeController@index')->middleware('mark:home-visits');
```

A `Marker` is saved with the `home-visits` name;

```
Route::get('/page/{page}', 'PagesController@show')->middleware('measure-time:page-visits-duration');
```

A `Timer` containing the request duration is saved with the `page-visit-duration` name.

```
Route::get('/details', 'DetailsController@index')->middleware('measure-time:details-duration,milliseconds');
```

Timer could be set to a specific resolution using a second parameter.

Retrieving metrics
------------------

[](#retrieving-metrics)

There are two options for retrieving metrics:

- Using `MetricRegistry`:

```
$registry = resolve(MetricRegistry::class);
$meter = $registry->meter('meter-name');
$meter->get(); // gets the entire dataset for the meter

$from = Carbon::yesterday();
$meter->after($from)->get(); // gets the dataset for meters recorded after $from

$to = Carbon::tomorrow();
$meter->before($from)->get(); // gets the dataset for meters recorded before $to

$meter->between($from, $to)->get(); // gets the dataset for meters recorded between $from and $to
```

- Directly querying the `Metric` Eloquent model.

Time series
-----------

[](#time-series)

One of the most important aspect of using metrics is extracting time series from them with convenient statistics.

Currently supported statistics are `count`, `average`, `max` and `min`.

```
$registry = resolve(MetricRegistry::class);

$timer = $registry->meter('meter-name', MeterType::TIMER);

$from = Carbon::now()->subYears(2);
$to = Carbon::today();

$timeSeries = $this->timer->bySecond($from, $to, TimeSeriesStatistics::COUNT);
$timeSeries = $this->timer->byMinute($from, $to, TimeSeriesStatistics::AVERAGE);
$timeSeries = $this->timer->byHour($from, $to, TimeSeriesStatistics::MAX);
$timeSeries = $this->timer->byMonth($from, $to, TimeSeriesStatistics::MIN);
$timeSeries = $this->timer->byYear($from, $to, TimeSeriesStatistics::MIN);
```

Time series are generated as custom collection of type `MetricCollection`.

### Statistics on time series

[](#statistics-on-time-series)

Once a time series is extracted, you can perform statistics on it. In addition to standard `Collection` methods, like `mean()`, `max()`, `min()`, `avg()`, etc., the `MetricCollection`class adds methods for performing other operations. Actually the following are supported:

- `stDev()` - computes values standard deviation
- `variance()` - computes values variance
- `cumulative()` - computes discrete probability density function (i.e. cumulative sum)
- `histogram($nbins)` - computes the histogram for the values using `nbins` bins.
- `kolmSmirn($collection)` - computes [Kolmogorov-Smirnov](https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test) distance for comparing two time series.

Treeware
--------

[](#treeware)

You're free to use this package, but if it makes it to your production environment you are required to buy the world a tree.

It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to [plant trees](https://www.bbc.co.uk/news/science-environment-48870920). If you support this package and contribute to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

You can buy trees here [offset.earth/treeware](https://offset.earth/treeware?gift-trees)

Read more about Treeware at [treeware.earth](http://treeware.earth)

Issues, Questions and Pull Requests
-----------------------------------

[](#issues-questions-and-pull-requests)

You can report issues and ask questions in the [issues section](https://github.com/robertogallea/LaravelMetrics/issues). Please start your issue with ISSUE: and your question with QUESTION:

If you have a question, check the closed issues first. Over time, I've been able to answer quite a few.

To submit a Pull Request, please fork this repository, create a new branch and commit your new/updated code in there. Then open a Pull Request from your new branch. Refer to [this guide](https://help.github.com/articles/about-pull-requests/) for more info.

###  Health Score

30

—

LowBetter than 64% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 96% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~58 days

Recently: every ~129 days

Total

10

Last Release

1794d ago

PHP version history (2 changes)0.1.0PHP ^7.2

0.5.1PHP ^7.2|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/818f547bcf73a82393d9014c85c90c83d760102a8d4dfe806353afb83848a901?d=identicon)[robertogallea](/maintainers/robertogallea)

---

Top Contributors

[![robertogallea](https://avatars.githubusercontent.com/u/19411470?v=4)](https://github.com/robertogallea "robertogallea (24 commits)")[![ricardosierra](https://avatars.githubusercontent.com/u/5499444?v=4)](https://github.com/ricardosierra "ricardosierra (1 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/robertogallea-laravel-metrics/health.svg)

```
[![Health](https://phpackages.com/badges/robertogallea-laravel-metrics/health.svg)](https://phpackages.com/packages/robertogallea-laravel-metrics)
```

###  Alternatives

[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[beyondcode/laravel-server-timing

Add Server-Timing header information from within your Laravel apps.

5712.0M1](/packages/beyondcode-laravel-server-timing)[rollbar/rollbar-laravel

Rollbar error monitoring integration for Laravel projects

14110.4M7](/packages/rollbar-rollbar-laravel)[yadahan/laravel-authentication-log

Laravel Authentication Log provides authentication logger and notification for Laravel.

416632.8k5](/packages/yadahan-laravel-authentication-log)[kitloong/laravel-app-logger

Laravel log for your application

101.2M8](/packages/kitloong-laravel-app-logger)[label84/laravel-auth-log

Log user authentication actions in Laravel.

3654.0k](/packages/label84-laravel-auth-log)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
