Metrics is a package created by Steve Bauman which offers a simple and elegant way of recording and querying metrics within your Laravel application. Easily track page views, API calls, user signups, or any other countable events.
To install this package, use Composer and then publish and run the migrations:
composer require directorytree/metricsphp artisan vendor:publish --tag="metrics-migrations"php artisan migrate
You can then start tracking metrics using the Metric facade:
use DirectoryTree\Metrics\MetricData;use DirectoryTree\Metrics\Facades\Metrics; Metrics::record(new MetricData('signups'));
Or using the metric helper method:
metric('signups')->record();
You can also organize your metrics into categories:
// Track errors by severitymetric('errors')->category('critical')->record();metric('errors')->category('warning')->record();
Your metrics can be associated with your Eloquent models using the HasMetrics trait:
use DirectoryTree\Metrics\HasMetrics;use Illuminate\Database\Eloquent\Model; class User extends Model{ use HasMetrics;}
$user = User::find(1); // Track logins per usermetric('logins')->measurable($user)->record();
If you have multiple metrics to record, the option is also available to batch them in memory and then commit them.
use DirectoryTree\Metrics\Facades\Metrics; Metrics::capture(); // Record multiple metricsmetric('signups')->record();metric('emails_sent')->category('welcome')->record();metric('signups')->record(); // Commit all captured metrics at onceMetrics::commit();
Another handy feature of this package is the ability for you to query metrics using the query builder with date filters:
use DirectoryTree\Metrics\Metric; // Get today's metrics$metrics = Metric::today()->get(); // Get this week's metrics$metrics = Metric::thisWeek()->get(); // Get today's signups$signups = Metric::today() ->where('name', 'signups') ->sum('value');
Steve has really put together a nice and helpful package. Learn more about this package and view the source code on GitHub.