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 Bundle Laravel Package

api-insight/metrics-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require api-insight/metrics-bundle
  1. Register Bundle in config/bundles.php:
    ApiInsight\ApiInsightBundle::class => ['all' => true],
    
  2. Configure in config/packages/api_insight.yaml:
    api_insight:
        enabled: true
        storage: memory
    
  3. Import Routes in config/routes.yaml:
    api_insight:
        resource: '@ApiInsightBundle/Resources/config/routes.yaml'
    
  4. Clear Cache:
    php bin/console cache:clear
    

First Use Case

Access metrics immediately via:

curl http://your-api.com/metrics

Verify real-time API call tracking (e.g., total_calls, error_rate) for all routes.


Implementation Patterns

Core Workflow

  1. Automatic Metrics Collection:

    • No manual instrumentation needed. The bundle auto-tracks:
      • HTTP status codes (e.g., 200, 404).
      • Response times (avg_duration, min_duration, max_duration).
      • Error rates per route.
    • Example output:
      {
        "routes": {
          "api_users_get": {
            "total_calls": 120,
            "avg_duration": 0.056,
            "status_codes": {"200": 118, "404": 2}
          }
        }
      }
      
  2. Time-Based Metrics:

    • Query historical data via /metrics/time:
      curl http://your-api.com/metrics/time?period=hour&route=api_users_get
      
    • Useful for:
      • Spotting traffic spikes (e.g., hourly total_calls).
      • Debugging performance regressions (e.g., avg_duration trends).
  3. Conditional Monitoring:

    • Disable for Non-Prod:
      api_insight:
          enabled: "%env(bool:API_INSIGHT_ENABLED)%"  # Set to `false` in `.env.test`
      
    • Exclude Routes: Use Symfony’s matcher to ignore specific routes (e.g., health checks) by extending the bundle’s event subscriber.
  4. Integration with CI/CD:

    • Reset metrics before tests:
      curl -X POST http://your-api.com/metrics/reset -H "X-API-Insight-Token: $TOKEN"
      
    • Validate API stability by checking error_rate in post-deploy metrics.

Gotchas and Tips

Pitfalls

  1. Memory Storage Limitation:

    • Data resets on server restart. For persistence, upgrade to Redis/Database (Pro) or implement a cron job to export metrics to a file/database before restart.
  2. Route Naming Conflicts:

    • Ensure route names (e.g., api_users_get) are unique. Duplicate names may cause metric aggregation issues.
    • Debug with:
      php bin/console debug:router | grep api_
      
  3. Performance Overhead:

    • Minimal in free version (~1–2ms per request). Monitor with:
      curl http://your-api.com/metrics | jq '.global.avg_duration'
      
    • If latency spikes, check for:
      • High total_calls on a single route.
      • Slow storage backend (e.g., database queries in Pro).
  4. Authentication Bypass:

    • If auth.enabled: true, ensure the X-API-Insight-Token header is included in all requests to /metrics. Test with:
      curl -I http://your-api.com/metrics  # Should return 401 if misconfigured
      

Debugging Tips

  1. Verify Bundle Activation:

    • Check if metrics update in real-time:
      watch -n 1 'curl http://your-api.com/metrics | jq .global.total_calls'
      
    • If static, confirm:
      • enabled: true in config.
      • No matcher exclusions in the bundle’s event subscriber.
  2. Log Collection Issues:

    • Enable Symfony’s profiler to inspect the ApiInsightEventListener:
      framework:
          profiler:
              only_exceptions: false
      
    • Look for skipped events in the profiler’s "Events" tab.
  3. Time-Based Metrics Quirks:

    • The period parameter in /metrics/time defaults to day. For granular data, specify:
      curl http://your-api.com/metrics/time?period=minute
      
    • Note: Older periods (e.g., year) may return empty data if no calls were made.

Extension Points

  1. Custom Metrics:

    • Extend the ApiInsightEvent to log business-specific metrics (e.g., cart abandonment rate):
      // src/EventListener/CustomMetricsListener.php
      use ApiInsight\ApiInsightBundle\Event\ApiInsightEvent;
      
      class CustomMetricsListener {
          public function onApiInsight(ApiInsightEvent $event) {
              if ($event->getRouteName() === 'api_cart_checkout') {
                  $event->addCustomMetric('abandoned_carts', $this->isCartAbandoned());
              }
          }
      }
      
    • Register the listener in services.yaml:
      services:
          App\EventListener\CustomMetricsListener:
              tags:
                  - { name: kernel.event_listener, event: api_insight.collect, method: onApiInsight }
      
  2. Storage Backend:

    • Override the default MemoryStorage by implementing ApiInsight\ApiInsightBundle\Storage\StorageInterface and configure via:
      api_insight:
          storage: custom_service_id
      
  3. Alerting:

    • Use the /metrics endpoint to trigger alerts (e.g., via Symfony Messenger or external tools like PagerDuty):
      curl http://your-api.com/metrics | jq '.global.error_rate > 5'  # Example: Alert if >5%
      
    • For Pro users, leverage the dashboard to set up visual alerts.
  4. Prometheus Integration (Pro):

    • Enable in config:
      api_insight:
          prometheus:
              enabled: true
      
    • Expose metrics in Prometheus format at /metrics/prometheus (if supported in future versions).

---
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle