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 countable events. Supports values, categories, custom attributes, hourly/dated metrics, model-based tracking, and Redis storage.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Laravel-Native Integration: The package is purpose-built for Laravel (9.0+), leveraging Laravel’s service container, facades, and Eloquent ORM. This ensures seamless integration with existing Laravel applications, reducing architectural friction.
  • Modular Design: Supports both simple and complex use cases (e.g., daily/hourly metrics, custom attributes, model associations) without forcing a monolithic implementation. The package’s layered architecture (e.g., MetricData, PendingMetric, HasMetrics trait) allows for granular adoption.
  • Event-Driven Flexibility: Capturing metrics in memory (via Metrics::capture()) and committing in batches aligns with Laravel’s request lifecycle, optimizing performance for high-traffic applications.
  • Extensibility: Customizable via repositories, models, and drivers (e.g., Redis for distributed systems), making it adaptable to microservices or multi-tenant architectures.

Integration Feasibility

  • Low Barrier to Entry: Installation requires only a Composer dependency, migrations, and optional configuration. The metric() helper and facade-based API reduce boilerplate.
  • Database Schema: The package includes migrations for a metrics table with fields for name, category, year/month/day/hour, value, and custom attributes. This is straightforward to extend or override.
  • Queue/Async Support: The Redis driver and metrics:commit command enable offloading metric persistence to background jobs, reducing latency in high-throughput systems.
  • Testing Support: Built-in fake implementation (Metrics::fake()) simplifies unit/integration testing, critical for CI/CD pipelines.

Technical Risk

  • Performance at Scale:
    • Hourly Metrics: Storing hourly granularity (24x daily rows) could bloat the database for high-frequency metrics. Requires monitoring and potential sharding/archiving strategies.
    • Custom Attributes: Unbounded attribute flexibility may lead to schema sprawl if not governed (e.g., via migrations or validation).
    • Redis Dependency: The Redis driver introduces a moving part for distributed setups, requiring Redis infrastructure and TTL management.
  • Data Retention: No built-in TTL or archiving mechanism for historical metrics. Requires custom logic (e.g., Laravel scheduling + Metric::whereDate() queries) to prune old data.
  • Concurrency: No explicit handling for concurrent writes (e.g., race conditions in value aggregation). The package relies on Laravel’s default database transactions, which may need tuning for high-write scenarios.
  • Model Associations: The HasMetrics trait ties metrics to Eloquent models, which could complicate:
    • Soft-deleted models (metrics may reference non-existent records).
    • Multi-tenancy (requires tenant-aware queries or custom scoping).
  • Backward Compatibility: As a relatively new package (last release 2026), long-term stability depends on the maintainer’s activity. The MIT license mitigates licensing risk.

Key Questions

  1. Use Case Alignment:
    • Are metrics primarily for analytics (e.g., dashboards), auditing, or operational monitoring? This dictates granularity (daily vs. hourly) and retention needs.
    • Will metrics be queried in real-time or batched (e.g., nightly reports)? This impacts driver choice (database vs. Redis).
  2. Scale Requirements:
    • What is the expected write volume (e.g., 10K metrics/hour)? Hourly granularity or custom attributes may require optimization (e.g., indexing, batching).
    • Is the application distributed (e.g., multi-AZ, microservices)? The Redis driver is critical here.
  3. Data Lifecycle:
    • How long should metrics be retained? Custom TTL logic or archiving (e.g., to S3) may be needed.
    • Are there compliance requirements (e.g., GDPR) for metric data? Model associations (measurable_type/id) may need anonymization.
  4. Team Skills:
    • Does the team have experience with Laravel’s service container and facades? The package’s API is Laravel-centric.
    • Is Redis available/acceptable for the Redis driver? If not, the database driver may suffice for smaller scales.
  5. Extensibility Needs:
    • Will custom attributes or drivers be required? The package supports this but may need additional validation or migrations.
    • Are there plans to integrate with third-party tools (e.g., Prometheus, Datadog)? The package’s output format (database table) may need adapters.

Integration Approach

Stack Fit

  • Laravel Ecosystem: The package is a drop-in solution for Laravel applications, leveraging:
    • Facades/Helpers: Metrics, metric(), PendingMetric for intuitive syntax.
    • Eloquent: Metric model for querying with Laravel’s query builder.
    • Service Container: Dependency injection for repositories/managers.
    • Migrations: Schema-agnostic setup via vendor:publish.
  • Database: Supports MySQL, PostgreSQL, SQLite (via Laravel’s DB layer). No vendor-specific SQL.
  • Redis: Optional for distributed systems, requiring Redis 6.0+ (for hashes).
  • Queue System: The metrics:commit command can be dispatched to Laravel queues for async processing.

Migration Path

  1. Pilot Phase:
    • Install the package in a staging environment:
      composer require directorytree/metrics
      php artisan vendor:publish --tag="metrics-migrations"
      php artisan migrate
      
    • Start with a single metric type (e.g., page:views) to validate the integration.
    • Use the database driver initially to avoid Redis dependencies.
  2. Core Integration:
    • Replace manual counters (e.g., Cache::increment()) with metric()->record().
    • Implement the HasMetrics trait for model-associated metrics (e.g., user activity).
    • Configure batching via Metrics::capture() in AppServiceProvider for performance.
  3. Advanced Features:
    • Enable Redis driver for distributed setups:
      METRICS_DRIVER=redis
      
      Schedule the commit command:
      // app/Console/Kernel.php
      $schedule->command('metrics:commit')->hourly();
      
    • Add custom attributes via migrations and queries for segmentation.
  4. Optimization:
    • Monitor database growth for hourly metrics/custom attributes. Add indexes if needed:
      Schema::table('metrics', function (Blueprint $table) {
          $table->index(['name', 'category', 'year', 'month', 'day']);
      });
      
    • Implement data retention policies (e.g., Laravel scheduler + Metric::whereDate()).

Compatibility

  • Laravel Versions: Tested on Laravel 9.0+. For Laravel 10/11, verify compatibility with the package’s composer.json constraints.
  • PHP Versions: Requires PHP 8.1+. Check for breaking changes in PHP 8.2+ (e.g., named arguments).
  • Dependencies:
    • Redis: Only needed for the Redis driver. Ensure the predis/predis or phpredis package is installed.
    • Carbon: Used for date handling (included via Laravel).
  • Third-Party Conflicts: Low risk, as the package uses Laravel’s service container and doesn’t override core classes.

Sequencing

  1. Pre-Installation:
    • Review existing metric collection logic (e.g., custom tables, logs) to avoid duplication.
    • Design a metric naming convention (e.g., domain:event).
  2. Installation:
    • Publish migrations/configuration.
    • Run migrations in a transactional test environment first.
  3. Development:
    • Start with the metric() helper for simplicity.
    • Gradually adopt HasMetrics for model associations.
    • Implement custom attributes only if segmentation is needed.
  4. Testing:
    • Use Metrics::fake() to test metric recording and querying.
    • Validate edge cases (e.g., concurrent writes, date boundaries).
  5. Production Rollout:
    • Deploy to a non-critical endpoint first (e.g., staging).
    • Monitor database performance and query latency.
    • Enable Redis driver and scheduled commits in phases.

Operational Impact

Maintenance

  • Schema Management:
    • Custom attributes require manual migrations. Document new attributes in a central place (e.g., docs/metrics.md).
    • Monitor the metrics table for growth. Consider archiving old data via:
      // app/Console/Commands/ArchiveMetrics.php
      Metric::whereDate('created_at', '<', now()->subYears(1))->delete();
      
  • Configuration:
    • Centralize settings in config/metrics.php (e.g., Redis TTL, auto-commit).
    • Use environment variables for sensitive settings (e.g., Redis password).
  • Dependencies:
    • Monitor for updates to directorytree/metrics and Laravel core. Test upgrades in staging.
    • Pin Redis client versions to avoid compatibility issues.

Support

  • Troubleshooting:
    • Missing Metrics: Check if Metrics::capture() is enabled and auto-commit is not disabled.
    • Redis Issues: Verify Redis connection and TTL settings. Check the `metrics:commit
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4