Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Metrics Laravel Package

directorytree/metrics

Record and query metrics in Laravel with a simple, elegant API. Track page views, API calls, signups, and other events with optional values, categories, dates, hourly buckets, model-scoped metrics, and custom attributes. Supports Redis and extensible drivers.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps:

  1. Install via Composer:
    composer require directorytree/metrics
    
  2. Publish migrations and run them:
    php artisan vendor:publish --tag="metrics-migrations"
    php artisan migrate
    
  3. First Use Case: Track a simple event (e.g., page views):
    use DirectoryTree\Metrics\Facades\Metrics;
    Metrics::record(new \DirectoryTree\Metrics\MetricData('page_views'));
    
    Or use the helper:
    metric('page_views')->record();
    

Where to Look First:

  • config/metrics.php (for driver/configuration)
  • app/Console/Kernel.php (for scheduling metrics:commit if using Redis)
  • app/Providers/AppServiceProvider.php (for global metric capturing)

Implementation Patterns

Core Workflows

  1. Basic Tracking:

    // In a controller/middleware
    metric('api_calls')->record();
    
    • Useful for counting requests, logins, or actions.
  2. Batch Recording:

    Metrics::capture(); // Start batch
    metric('events')->record(50); // Bulk increment
    Metrics::commit(); // Flush to DB
    
    • Ideal for high-traffic endpoints (e.g., webhooks, cron jobs).
  3. Model-Associated Metrics:

    // User model with HasMetrics trait
    class User extends Model { use HasMetrics; }
    
    // Track logins per user
    metric('user_logins')->measurable(auth()->user())->record();
    
    • Query later:
      $user->metrics()->where('name', 'user_logins')->sum('value');
      
  4. Segmented Analytics:

    // Track by category + attributes
    metric('purchases')
        ->category('premium')
        ->with(['source' => 'campaign_a'])
        ->record();
    
    • Query segments:
      Metric::where('name', 'purchases')
          ->where('category', 'premium')
          ->where('source', 'campaign_a')
          ->sum('value');
      

Integration Tips

  • Middleware: Track API calls globally:
    // app/Http/Middleware/TrackApiCalls.php
    public function handle($request, Closure $next) {
        metric('api_requests')->record();
        return $next($request);
    }
    
  • Events: Hook into Laravel events (e.g., registered, created):
    // In an event listener
    metric('user_registrations')->record();
    
  • Jobs: Batch metrics in queued jobs:
    // app/Jobs/RecordMetrics.php
    public function handle() {
        Metrics::capture();
        // Record multiple metrics...
        Metrics::commit();
    }
    

Gotchas and Tips

Pitfalls

  1. Redis Driver Quirks:

    • If using Redis, ensure metrics:commit is scheduled (e.g., hourly) to avoid metric loss.
    • Disable auto_commit in config if committing manually:
      'auto_commit' => env('METRICS_AUTO_COMMIT', false),
      
    • Redis TTL (default: 1 day) may drop metrics if the commit job fails repeatedly.
  2. Hourly Metrics Overhead:

    • Hourly metrics create 24x more rows than daily. Avoid unless necessary.
    • Querying hourly metrics requires explicit hourly() scope:
      Metric::thisHour()->where('name', 'api_calls')->sum('value');
      
  3. Attribute Conflicts:

    • Custom attributes cannot override core fields (e.g., name, value). Example:
      // Fails silently (name ignored)
      metric('dynamic_name')->with(['name' => 'override'])->record();
      
  4. Model Metrics Pitfalls:

    • Ensure measurable_type and measurable_id are indexed in the DB for performance.
    • Soft-deleted models may cause orphaned metrics. Handle with:
      $user->metrics()->whereDeleted()->delete();
      

Debugging Tips

  1. Check Captured Metrics:
    // Dump pending metrics (if using Redis or capture)
    dd(Metrics::getPendingMetrics());
    
  2. Verify Redis Storage:
    # Check Redis keys (adjust pattern)
    redis-cli keys "metrics:*"
    
  3. Query Performance:
    • Add indexes for frequent filters (e.g., category, measurable_id):
      Schema::table('metrics', function (Blueprint $table) {
          $table->index(['name', 'category']);
      });
      
    • Use select('name', 'value') to limit columns in queries.

Extension Points

  1. Custom Metric Models:

    • Extend the Metric model to add scopes:
      class CustomMetric extends \DirectoryTree\Metrics\Metric {
          public function scopeBySource($query, $source) {
              return $query->where('source', $source);
          }
      }
      
    • Bind in AppServiceProvider:
      Metrics::setMetricModel(CustomMetric::class);
      
  2. Queue Commit Jobs:

    • Dispatch Metrics\Jobs\CommitMetrics manually for async commits:
      CommitMetrics::dispatch();
      
  3. Custom Drivers:

    • Implement DirectoryTree\Metrics\Contracts\MetricDriver for non-Redis/DB storage (e.g., DynamoDB).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope