PHPackages                             sidcorp-resource/api-metrics-exporter - 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. sidcorp-resource/api-metrics-exporter

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

sidcorp-resource/api-metrics-exporter
=====================================

Laravel 9+ API metrics exporter for Prometheus and Grafana dashboards

v1.0.0(11mo ago)2241MITPHPPHP ^8.1

Since Jun 6Pushed 9mo agoCompare

[ Source](https://github.com/yenc-coding/laravel-api-metrics-exporter)[ Packagist](https://packagist.org/packages/sidcorp-resource/api-metrics-exporter)[ RSS](/packages/sidcorp-resource-api-metrics-exporter/feed)WikiDiscussions main Synced 1mo ago

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

Laravel API Metrics Exporter
============================

[](#laravel-api-metrics-exporter)

A robust, production-ready metrics collection library for Laravel 9+ APIs. Effortlessly collect Prometheus-compatible metrics for your API endpoints with zero configuration and seamless integration.

[![Latest Version on Packagist](https://camo.githubusercontent.com/8e4dc222d0da491fea2bdb70cebb18519fcc2f014109feeee9ae8b70011bbae3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736964636f72702d7265736f757263652f6170692d6d6574726963732d6578706f727465722e737667)](https://packagist.org/packages/sidcorp-resource/api-metrics-exporter)[![PHP Version Support](https://camo.githubusercontent.com/3c1a1a3a1e26804ccb6e9013f766ad16f8f684750a3d7795e298b6e2b3a0ddc5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f736964636f72702d7265736f757263652f6170692d6d6574726963732d6578706f727465722e737667)](https://packagist.org/packages/sidcorp-resource/api-metrics-exporter)[![Laravel Version Support](https://camo.githubusercontent.com/abfa18104e3330c2fff7251bdc35363d67a00aa9fcccbdbb706836dc12215403/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d253345253344392e302d726564)](https://laravel.com/)[![License](https://camo.githubusercontent.com/4a08e368c7bf8a99a5aa43f2f4f5aadcc09abd7e26f36089ddc01c172dde7eec/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f736964636f72702d7265736f757263652f6170692d6d6574726963732d6578706f727465722e737667)](LICENSE)

---

Features
--------

[](#features)

- **Zero-configuration setup** – Works out of the box with sensible defaults
- **Automatic API metrics collection**:
    - Request counts by endpoint, method, status, and user
    - Response time histograms for percentile analysis
    - Daily unique user tracking
- **Prometheus OpenMetrics format** – Standard `/metrics` endpoint with proper naming conventions
- **Multiple storage backends**:
    - **Redis** (recommended for production, requires phpredis extension)
    - **InMemory** (for testing/development)
- **Production-ready** – Graceful error handling and lightweight middleware
- **Strict Prometheus compliance** – All metrics follow Prometheus naming conventions and exposition format

---

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 9.0 or higher
- PHP Redis extension (ext-redis) for production use

---

Quick Start
-----------

[](#quick-start)

### 1. Install

[](#1-install)

```
composer require sidcorp-resource/api-metrics-exporter
```

### 2. Add Middleware

[](#2-add-middleware)

Add the middleware to your `app/Http/Kernel.php`:

```
protected $middlewareGroups = [
    'api' => [
        // ... other middleware
        \SidcorpResource\ApiMetricsExporter\Middleware\MetricsMiddleware::class,
    ],
];
```

### 3. View Metrics

[](#3-view-metrics)

Visit `http://your-app.com/metrics` to see your metrics in Prometheus format.

The library will automatically start collecting metrics using Redis (with InMemory fallback if Redis is unavailable).

---

Configuration (Optional)
------------------------

[](#configuration-optional)

You can customize the default configuration by publishing the config file:

```
php artisan vendor:publish --provider="SidcorpResource\ApiMetricsExporter\ApiMetricsServiceProvider" --tag="config"
```

Key configuration options in `config/api-metrics.php`:

```
return [
    'driver' => env('API_METRICS_DRIVER', 'redis'),
    'endpoint' => [
        'path' => env('API_METRICS_ENDPOINT_PATH', 'metrics'),
        'middleware' => ['api'],
    ],
    'collection' => [
        'enabled' => env('API_METRICS_ENABLED', true),
        'excluded_paths' => ['health', 'metrics', 'debug*'],
    ],
    'redis' => [
        'connection' => 'default',
        'prefix' => 'api_metrics:',
        'ttl' => 86400,
    ],
];
```

---

Securing the /metrics Endpoint
------------------------------

[](#securing-the-metrics-endpoint)

### HTTP Basic Authentication

[](#http-basic-authentication)

You can enable HTTP Basic Auth for the `/metrics` endpoint to restrict access:

1. Set the following in your `.env` file:

    ```
    API_METRICS_BASIC_AUTH_ENABLED=true
    API_METRICS_BASIC_AUTH_USERNAME=your_username
    API_METRICS_BASIC_AUTH_PASSWORD=your_password
    ```
2. The exporter will require these credentials for all requests to `/metrics`.

### TLS/HTTPS

[](#tlshttps)

> **Note:** TLS/HTTPS is handled by your web server (Nginx, Apache, etc.) or Laravel Valet/Homestead. The library does not manage TLS certificates directly.

### IP Whitelisting / Network Security

[](#ip-whitelisting--network-security)

> For additional security, you should restrict access to `/metrics` at the firewall, load balancer, or web server level (e.g. allow-list Prometheus server IPs only).

---

Prometheus Scrape Config Examples
---------------------------------

[](#prometheus-scrape-config-examples)

### Basic Auth Example

[](#basic-auth-example)

```
scrape_configs:
  - job_name: 'my-app'
    metrics_path: '/metrics'
    basic_auth:
      username: 'myuser'      # Must match API_METRICS_BASIC_AUTH_USERNAME
      password: 'mypassword'  # Must match API_METRICS_BASIC_AUTH_PASSWORD
    static_configs:
      - targets: ['myapp.example.com:443']
```

---

Usage
-----

[](#usage)

### Default Metrics

[](#default-metrics)

The middleware automatically collects:

- `api_requests_total` – Total requests by endpoint/method/status/user
- `api_request_duration_seconds` – Response time histogram
- `unique_users_total` – Daily unique users per endpoint

### Custom Metrics

[](#custom-metrics)

Currently, the library does not support registering custom drivers, exporters, or decorators via API. These features may be considered for future releases.

---

### Dependency Injection

[](#dependency-injection)

You can inject the collector into your controller:

```
use SidcorpResource\ApiMetricsExporter\Contracts\MetricsCollectorInterface;

class CustomController extends Controller
{
    public function __construct(private MetricsCollectorInterface $metrics) {}

    public function index()
    {
        $this->metrics->incrementCounter('custom_actions_total');
        // Your logic...
    }
}
```

---

Monitoring &amp; Grafana
------------------------

[](#monitoring--grafana)

### Prometheus Configuration

[](#prometheus-configuration)

```
scrape_configs:
  - job_name: 'laravel_api'
    scrape_interval: 15s
    metrics_path: '/metrics'
    static_configs:
      - targets: ['your-api-host:80']
```

### Example Grafana Queries

[](#example-grafana-queries)

**Request Rate:**

```
sum by(endpoint) (rate(api_requests_total[5m]))

```

**95th Percentile Response Time:**

```
histogram_quantile(0.95, sum(rate(api_request_duration_seconds_bucket[5m])) by (le, endpoint))

```

**Error Rate:**

```
sum by(endpoint) (rate(api_requests_total{status=~"5.."}[5m])) / sum by(endpoint) (rate(api_requests_total[5m])) * 100

```

**Unique Users (per endpoint per day):**

```
sum by(endpoint, date) (unique_users_total)

```

---

Management
----------

[](#management)

### Flush Metrics

[](#flush-metrics)

```
# Reset all metrics data
php artisan api-metrics:flush

# Flush specific driver
php artisan api-metrics:flush --driver=redis
```

Or programmatically:

```
use SidcorpResource\ApiMetricsExporter\Facades\Metrics;

$success = Metrics::flushMetrics();
```

---

Troubleshooting
---------------

[](#troubleshooting)

If you encounter errors related to Redis (e.g., `Class "Redis" not found`), ensure the PHP Redis extension is installed:

```
# Ubuntu/Debian
sudo apt-get install php-redis

# CentOS/RHEL
sudo yum install php-redis

# macOS with Homebrew
brew install php-redis
pecl install redis
```

Then restart your web server and verify the extension is loaded with:

```
php -m | grep redis
```

---

Environment Check
-----------------

[](#environment-check)

Create a simple compatibility check:

```
