PHPackages                             rylxes/laravel-observability - 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. rylxes/laravel-observability

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

rylxes/laravel-observability
============================

Production-grade observability and APM plugin for Laravel applications with OpenTelemetry, Prometheus, and AI-powered anomaly detection

v1.3.0(3mo ago)05MITPHPPHP ^8.1CI passing

Since Feb 11Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/rylxes/laravel-observability)[ Packagist](https://packagist.org/packages/rylxes/laravel-observability)[ Docs](https://github.com/rylxes/laravel-observability)[ RSS](/packages/rylxes-laravel-observability/feed)WikiDiscussions main Synced today

READMEChangelog (1)Dependencies (22)Versions (10)Used By (0)

Laravel Observability Plugin
============================

[](#laravel-observability-plugin)

> **[Full Documentation](https://rylxes.com/docs/laravel-observability)** — Complete usage guide, configuration reference, and API docs.

🔍 **Production-Grade Observability &amp; APM for Laravel Applications**

A lightweight, database-agnostic alternative to full APM tools, optimized specifically for Laravel apps. Features request tracing, performance profiling, slow query detection, OpenTelemetry/Prometheus integration, AI-based anomaly detection, and smart alerting.

[![Latest Version](https://camo.githubusercontent.com/34e695c6016bc2a934a96bed696e29b2f2ab562a7134d65a55d00653cd506bea/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e302d626c75652e737667)](https://github.com/rylxes/laravel-observability)[![PHP Version](https://camo.githubusercontent.com/5725429798ad8294996efd8b55180211a7ce48e0ff87fc6157b75cd93eeaaca3/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e31253743253545382e32253743253545382e332d626c75652e737667)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/552ea80ea7c6f1343f4a9d615105686241f5cb554891af2271f54aa4305d0ce9/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d25354531302e3025374325354531312e302d7265642e737667)](https://laravel.com)

---

✨ Features
----------

[](#-features)

### Core Capabilities

[](#core-capabilities)

- 📊 **Request Tracing** - Capture HTTP requests with route, controller, duration, memory usage, headers
- 🗄️ **Database Query Monitoring** - Track all queries, detect N+1 problems, identify slow queries
- ⚡ **Performance Profiling** - Per-route metrics, P50/P95/P99 latency, bottleneck identification
- 🐌 **Slow Query Detector** - Automatic detection with stack traces and optimization recommendations
- 🤖 **AI Anomaly Detection** - Statistical analysis (Z-score) to detect unusual patterns
- 📈 **OpenTelemetry Export** - OTLP protocol support for distributed tracing
- 📊 **Prometheus Metrics** - `/metrics` endpoint for Prometheus scraping
- 🔔 **Smart Alerting** - Slack/Telegram notifications with throttling and deduplication
- 🎨 **Built-In Dashboard UI + API** - Authenticated web dashboard at `/admin/observability` plus API endpoints for custom implementations
- 🗃️ **Database Agnostic** - Works with MySQL, PostgreSQL, SQLite, SQL Server

---

📦 Installation
--------------

[](#-installation)

### 1. Install via Composer

[](#1-install-via-composer)

```
composer require rylxes/laravel-observability
```

### 2. Run Installation Command

[](#2-run-installation-command)

```
php artisan observability:install
```

This will:

- Publish configuration file to `config/observability.php`
- Run migrations (creates observability tables)
- Display middleware setup instructions

### 3. Register Middleware

[](#3-register-middleware)

Add to `app/Http/Kernel.php` (Laravel 10) or `bootstrap/app.php` (Laravel 11):

**Laravel 10:**

```
protected $middleware = [
    // ... other middleware
    \Rylxes\Observability\Middleware\RequestTracingMiddleware::class,
];
```

**Laravel 11:**

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Rylxes\Observability\Middleware\RequestTracingMiddleware::class);
})
```

### 4. Configure Environment

[](#4-configure-environment)

Add to `.env`:

```
OBSERVABILITY_ENABLED=true
OBSERVABILITY_TRACING_ENABLED=true
OBSERVABILITY_SLOW_QUERY_THRESHOLD=1000

# Optional: Slack Notifications
OBSERVABILITY_SLACK_ENABLED=true
OBSERVABILITY_SLACK_WEBHOOK_URL=https://hooks.slack.com/services/YOUR/WEBHOOK/URL

# Optional: Telegram Notifications
OBSERVABILITY_TELEGRAM_ENABLED=true
OBSERVABILITY_TELEGRAM_BOT_TOKEN=your_bot_token
OBSERVABILITY_TELEGRAM_CHAT_ID=your_chat_id

# Optional: Prometheus
OBSERVABILITY_PROMETHEUS_ENABLED=true
```

---

🚀 Usage
-------

[](#-usage)

### Using the Facade

[](#using-the-facade)

```
use Rylxes\Observability\Facades\Observability;

// Get performance analysis
$analysis = Observability::analyze(days: 7);

// Detect slow queries
$slowQueries = Observability::slowQueries()->analyze();

// Detect anomalies
$anomalies = Observability::anomalies()->detectAnomalies('response_time');

// Export Prometheus metrics
$metrics = Observability::exportMetrics();
```

### Artisan Commands

[](#artisan-commands)

**Analyze Performance:**

```
php artisan observability:analyze --days=7 --notify
```

**Prune Old Data:**

```
php artisan observability:prune --force
```

### Web Dashboard (Authenticated)

[](#web-dashboard-authenticated)

By default, the package includes a web dashboard at:

```
/admin/observability

```

It uses your app's configured auth guards (`observability.dashboard.guards`), so it works with your existing login/session setup while still exposing the API for internal tools.

### API Endpoints

[](#api-endpoints)

All endpoints are prefixed with `/api/observability`:

EndpointDescription`GET /metrics`Prometheus metrics (text format)`GET /dashboard`Performance dashboard data (JSON, supports `?days=1..30`)`GET /traces`Recent request traces`GET /traces/{traceId}`Single trace detail`GET /alerts`Recent alerts`POST /alerts/{id}/resolve`Resolve an alert`GET /health`Health check**Example:**

```
curl http://yourapp.test/api/observability/metrics
curl http://yourapp.test/api/observability/dashboard | jq
```

---

⚙️ Configuration
----------------

[](#️-configuration)

### Database Connection

[](#database-connection)

By default, uses your app's default database connection. To use a separate database:

```
OBSERVABILITY_DB_CONNECTION=observability_db
```

Then configure the connection in `config/database.php`.

### Request Tracing

[](#request-tracing)

```
'tracing' => [
    'enabled' => true,
    'capture_headers' => true,
    'capture_payload' => false, // Be careful with sensitive data
    'excluded_routes' => ['telescope.*', 'horizon.*'],
    'sample_rate' => 1.0, // 0.0 to 1.0 (1.0 = trace all)
],
```

### Slow Query Detection

[](#slow-query-detection)

```
'queries' => [
    'enabled' => true,
    'log_all' => false, // Only log slow queries
    'slow_threshold_ms' => 1000,
    'detect_duplicates' => true, // N+1 detection
],
```

### Anomaly Detection (AI)

[](#anomaly-detection-ai)

```
'anomaly_detection' => [
    'enabled' => true,
    'z_score_threshold' => 3.0, // Standard deviations
    'min_data_points' => 100,
    'baseline_window_days' => 7,
],
```

### Notifications

[](#notifications)

```
'notifications' => [
    'slack' => ['enabled' => true, 'webhook_url' => env('...')],
    'telegram' => ['enabled' => true, 'bot_token' => env('...')],
    'throttle' => [
        'enabled' => true,
        'window_minutes' => 15,
        'max_alerts_per_window' => 1,
    ],
],
```

### Data Retention

[](#data-retention)

```
'retention' => [
    'traces_days' => 7,
    'queries_days' => 7,
    'metrics_days' => 30,
    'alerts_days' => 30,
],
```

### Dashboard UI

[](#dashboard-ui)

```
'dashboard' => [
    'enabled' => true,
    'route_prefix' => 'admin/observability',
    'middleware' => ['web'],
    'guards' => ['web', 'sanctum'],
    'refresh_interval_seconds' => 30,
],
```

---

📊 Integrations
--------------

[](#-integrations)

### Prometheus

[](#prometheus)

Enable in `.env`:

```
OBSERVABILITY_PROMETHEUS_ENABLED=true
OBSERVABILITY_PROMETHEUS_STORAGE=redis # or 'memory', 'apc'
```

Configure Prometheus to scrape:

```
scrape_configs:
  - job_name: 'laravel-app'
    static_configs:
      - targets: ['yourapp.test']
    metrics_path: '/api/observability/metrics'
```

### OpenTelemetry

[](#opentelemetry)

```
OBSERVABILITY_OTEL_ENABLED=true
OBSERVABILITY_OTEL_ENDPOINT=http://localhost:4318
```

### Grafana Dashboard

[](#grafana-dashboard)

Import the included Grafana dashboard template:

```
# Coming soon - dashboard JSON in /docs folder
```

---

🤖 AI Anomaly Detection
----------------------

[](#-ai-anomaly-detection)

The plugin uses statistical analysis (Z-score method) to detect anomalies:

1. **Baseline Calculation**: Analyzes last 7 days (configurable)
2. **Statistical Analysis**: Calculates mean and standard deviation
3. **Anomaly Detection**: Flags values &gt; 3σ from baseline
4. **Auto-Alerting**: Creates alerts for critical anomalies

**Monitored Metrics:**

- Response time
- Memory usage
- Error rate
- Query execution time

**Example:**

```
$result = Observability::anomalies()->detectAnomalies('response_time');

if ($result['status'] === 'success') {
    foreach ($result['anomalies'] as $anomaly) {
        echo "Anomaly: {$anomaly['metric_name']} - ";
        echo "Value: {$anomaly['value']} (Baseline: {$anomaly['baseline']})";
        echo "Deviation: {$anomaly['deviation_percent']}%";
    }
}
```

---

📈 Performance Insights
----------------------

[](#-performance-insights)

### Dashboard Data Structure

[](#dashboard-data-structure)

```
{
  "overall_metrics": {
    "total_requests": 12500,
    "avg_response_time_ms": 145.3,
    "p95_response_time_ms": 450,
    "p99_response_time_ms": 890,
    "avg_memory_mb": 28.5,
    "error_rate": 1.2
  },
  "route_performance": [
    {
      "route": "api.users.index",
      "requests": 3400,
      "avg_duration_ms": 89,
      "error_rate": 0.5
    }
  ],
  "bottlenecks": [
    {
      "type": "slow_routes",
      "severity": "warning",
      "data": ["api.reports.generate"]
    }
  ]
}
```

---

🔒 Security Considerations
-------------------------

[](#-security-considerations)

- **Sensitive Data**: Disable `capture_payload` and `capture_headers` in production
- **Authentication**: All API endpoints require authentication by default
- **Data Sanitization**: Passwords, tokens automatically redacted
- **Rate Limiting**: Consider adding rate limits to metrics endpoints

---

🧪 Testing
---------

[](#-testing)

Run tests:

```
composer test
```

### Local Development Loop (Deploy Once)

[](#local-development-loop-deploy-once)

```
cd ..
composer create-project laravel/laravel observability-sandbox
cd observability-sandbox
composer config repositories.observability '{"type":"path","url":"../Observability Plugin","options":{"symlink":true}}'
composer require rylxes/laravel-observability:@dev
php artisan observability:install
php artisan migrate
```

This lets you test package changes locally through `/admin/observability`, then ship one release after validation.

With coverage:

```
composer test-coverage
```

---

📊 Database Schema
-----------------

[](#-database-schema)

The plugin creates 4 tables (with configurable prefix):

TablePurpose`observability_traces`HTTP request traces`observability_queries`Database query logs`observability_metrics`Aggregated performance metrics`observability_alerts`Generated alerts**All tables use your app's database connection** (MySQL, PostgreSQL, SQLite, SQL Server).

---

🤝 Contributing
--------------

[](#-contributing)

Contributions welcome! Please see [CONTRIBUTING.md](https://github.com/rylxes/laravel-observability/blob/main/docs/CONTRIBUTING.md) for details.

---

📝 License
---------

[](#-license)

MIT License. See [LICENSE](LICENSE) file.

---

🙏 Credits
---------

[](#-credits)

Built with ❤️ for the Laravel community by [Sherriff Agboola](https://github.com/rylxes).

- OpenTelemetry PHP:
- Prometheus PHP: [https://github.com/PromPHP/prometheus\_client\_php](https://github.com/PromPHP/prometheus_client_php)

---

📞 Support
---------

[](#-support)

- **Issues**: [GitHub Issues](https://github.com/rylxes/laravel-observability/issues)
- **Discussions**: [GitHub Discussions](https://github.com/rylxes/laravel-observability/discussions)
- **Email**:

---

**⭐ If you find this useful, please star the repository!**

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance78

Regular maintenance activity

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3 days

Total

9

Last Release

118d ago

PHP version history (2 changes)v1.0.0PHP ^8.1|^8.2|^8.3

v1.1.1PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/1958058?v=4)[Agboola Sherriff](/maintainers/rylxes)[@rylxes](https://github.com/rylxes)

---

Top Contributors

[![rylxes](https://avatars.githubusercontent.com/u/1958058?v=4)](https://github.com/rylxes "rylxes (19 commits)")

---

Tags

laravelmonitoringperformanceprofilingapmtracingopentelemetryobservabilityprometheusrylxes

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rylxes-laravel-observability/health.svg)

```
[![Health](https://phpackages.com/badges/rylxes-laravel-observability/health.svg)](https://phpackages.com/packages/rylxes-laravel-observability)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M131](/packages/roots-acorn)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)[api-platform/laravel

API Platform support for Laravel

58171.6k14](/packages/api-platform-laravel)[fleetbase/core-api

Core Framework and Resources for Fleetbase API

1235.9k20](/packages/fleetbase-core-api)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
