PHPackages                             watchlog/laravel-apm - 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. watchlog/laravel-apm

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

watchlog/laravel-apm
====================

Lightweight APM integration for Laravel apps using Watchlog

0.2.0(5mo ago)00MITPHPPHP &gt;=7.4CI passing

Since May 18Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/watchlogserver/laravel-watchlog-apm)[ Packagist](https://packagist.org/packages/watchlog/laravel-apm)[ RSS](/packages/watchlog-laravel-apm/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (1)Versions (8)Used By (0)

Laravel APM – Watchlog Integration
==================================

[](#laravel-apm--watchlog-integration)

🎯 Lightweight, production-ready Application Performance Monitoring (APM) middleware for Laravel apps, designed for [Watchlog](https://watchlog.io).

Tracks request duration, memory usage, and status codes — stores metrics in a buffer file, and automatically flushes them to your Watchlog Agent every 10 seconds.

---

🚀 Features
----------

[](#-features)

- ✅ Compatible with Laravel 10 &amp; 12+
- 🧠 Smart file-based metric buffering (no database or queue needed)
- 🔁 Aggregates metrics per route (e.g. `/users/{id}`)
- 📊 Tracks duration, memory, and status codes
- 🔒 Safe and non-blocking — doesn't slow down your requests
- 🌐 Sends data automatically every 10 seconds to your Watchlog Agent
- 🏷️ Auto-detects service name from `.env` (`WATCHLOG_APM_SERVICE` or fallback to `APP_NAME`)

---

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

[](#-installation)

### 1. Link local package (for development)

[](#1-link-local-package-for-development)

```
composer config repositories.watchlog-apm path ../laravel-watchlog-apm
composer require "watchlog/laravel-apm:*"
```

> Adjust the path to match your local project structure.

---

⚙️ Usage (Laravel 12+)
----------------------

[](#️-usage-laravel-12)

In your `bootstrap/app.php`, register the middleware:

```
use Watchlog\LaravelAPM\Middleware\WatchlogAPM;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(...)
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->append(WatchlogAPM::class);
    })
    ->create();
```

---

🛠️ Configuration
----------------

[](#️-configuration)

### Service Identification

[](#service-identification)

You can define your service name explicitly in `.env`:

```
WATCHLOG_APM_SERVICE=orders-api
```

If not set, it will fallback to:

```
APP_NAME=laravel-app
```

### Agent URL Configuration

[](#agent-url-configuration)

The package automatically detects the agent endpoint, but you can override it for Docker:

**Option 1: Environment Variable (Recommended for Docker)**

```
WATCHLOG_APM_AGENT_URL=http://watchlog-agent:3774/apm
```

**Option 2: Config File**

Publish the config file (if available) or add to your `config/services.php`:

```
'watchlog' => [
    'apm' => [
        'agent_url' => env('WATCHLOG_APM_AGENT_URL', ''),
    ],
],
```

**Option 3: Direct Usage**

```
use Watchlog\LaravelAPM\Sender;

$sender = new Sender('http://watchlog-agent:3774/apm');
$sender->flush();
```

If not provided, the package will auto-detect:

- **Local / non-K8s**: `http://127.0.0.1:3774/apm`
- **Kubernetes**: `http://watchlog-node-agent.monitoring.svc.cluster.local:3774/apm`

---

📤 How it works
--------------

[](#-how-it-works)

### During each request:

[](#during-each-request)

- The middleware tracks route, status code, duration, and memory.
- The data is written to a file: `storage/logs/apm-buffer.json`

### After the request ends:

[](#after-the-request-ends)

- A shutdown function checks if 10 seconds have passed since the last flush.
- If yes, it:
    - Reads all pending metrics from `apm-buffer.json`
    - Aggregates them by route/method
    - Sends them to your Watchlog Agent as a JSON payload
    - Clears the buffer

---

📦 What gets sent?
-----------------

[](#-what-gets-sent)

```
{
  "collected_at": "2025-05-18T12:00:00Z",
  "platformName": "laravel",
  "metrics": [
    {
      "type": "aggregated_request",
      "service": "orders-api",
      "path": "hello/{id}",
      "method": "GET",
      "request_count": 3,
      "error_count": 0,
      "avg_duration": 6.1,
      "max_duration": 8.2,
      "avg_memory": {
        "rss": 18432000,
        "heapUsed": 23998464,
        "heapTotal": 25600000
      }
    }
  ]
}
```

---

📁 File structure
----------------

[](#-file-structure)

```
laravel-watchlog-apm/
├── src/
│   ├── Middleware/
│   │   └── WatchlogAPM.php
│   ├── Collector.php
│   └── Sender.php
├── composer.json
├── README.md
```

---

🧪 Debugging &amp; Testing
-------------------------

[](#-debugging--testing)

You can manually flush metrics via tinker:

```
php artisan tinker
>>> (new \Watchlog\LaravelAPM\Sender())->flush();
```

---

📁 Recommended `.gitignore`
--------------------------

[](#-recommended-gitignore)

Add the following to your Laravel app's `.gitignore`:

```
/storage/logs/apm-buffer.json
/storage/logs/apm-debug.log
/storage/framework/cache/watchlog-apm.lock
```

---

🐳 Docker Setup
--------------

[](#-docker-setup)

When running your Laravel app in Docker, configure the agent URL:

**Docker Compose Example:**

```
version: '3.8'

services:
  watchlog-agent:
    image: watchlog/agent:latest
    container_name: watchlog-agent
    ports:
      - "3774:3774"
    environment:
      - WATCHLOG_APIKEY=your-api-key
      - WATCHLOG_SERVER=https://log.watchlog.ir
    networks:
      - app-network

  laravel-app:
    build: .
    container_name: laravel-app
    ports:
      - "8000:8000"
    environment:
      - WATCHLOG_APM_AGENT_URL=http://watchlog-agent:3774/apm
      - WATCHLOG_APM_SERVICE=my-laravel-app
    depends_on:
      - watchlog-agent
    networks:
      - app-network

networks:
  app-network:
    driver: bridge
```

**Docker Run Example:**

```
# 1. Create network
docker network create app-network

# 2. Run Watchlog Agent
docker run -d \
  --name watchlog-agent \
  --network app-network \
  -p 3774:3774 \
  -e WATCHLOG_APIKEY="your-api-key" \
  -e WATCHLOG_SERVER="https://log.watchlog.ir" \
  watchlog/agent:latest

# 3. Run Laravel app (set WATCHLOG_APM_AGENT_URL in your .env or docker run)
docker run -d \
  --name laravel-app \
  --network app-network \
  -p 8000:8000 \
  -e WATCHLOG_APM_AGENT_URL="http://watchlog-agent:3774/apm" \
  my-laravel-app
```

**Important Notes:**

- When using Docker, use the container name as the hostname (e.g., `watchlog-agent`)
- Both containers must be on the same Docker network
- The agent must be running before your app starts
- Set `WATCHLOG_APM_AGENT_URL` in your `.env` file or as an environment variable
- If `WATCHLOG_APM_AGENT_URL` is not provided, auto-detection will be used (local or Kubernetes)

---

✅ Notes
-------

[](#-notes)

- The route path is captured via `$request->route()?->uri()` for correct dynamic segment grouping (`/users/{id}`)
- Multiple requests within 10 seconds are buffered, then aggregated and sent in a single payload
- The flush lock uses a simple file timestamp (`watchlog-apm.lock`) to prevent oversending
- The middleware is safe: flush failures won't crash your app

---

📝 License
---------

[](#-license)

MIT © Mohammadreza
Built for [Watchlog.io](https://watchlog.io)

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance70

Regular maintenance activity

Popularity0

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity31

Early-stage or recently created project

 Bus Factor1

Top contributor holds 66.7% 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 ~31 days

Recently: every ~47 days

Total

7

Last Release

169d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/b053172ac54dfbb975ef13907a6890515dae22627f2dc04ae76da56aa4267b9f?d=identicon)[mohammadnajm](/maintainers/mohammadnajm)

---

Top Contributors

[![mohammadnajm](https://avatars.githubusercontent.com/u/45530873?v=4)](https://github.com/mohammadnajm "mohammadnajm (8 commits)")[![semantic-release-bot](https://avatars.githubusercontent.com/u/32174276?v=4)](https://github.com/semantic-release-bot "semantic-release-bot (3 commits)")[![mehdinajm](https://avatars.githubusercontent.com/u/88393417?v=4)](https://github.com/mehdinajm "mehdinajm (1 commits)")

### Embed Badge

![Health badge](/badges/watchlog-laravel-apm/health.svg)

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

###  Alternatives

[spatie/laravel-health

Monitor the health of a Laravel application

85810.0M83](/packages/spatie-laravel-health)[beyondcode/laravel-server-timing

Add Server-Timing header information from within your Laravel apps.

5712.0M1](/packages/beyondcode-laravel-server-timing)[rollbar/rollbar-laravel

Rollbar error monitoring integration for Laravel projects

14110.4M7](/packages/rollbar-rollbar-laravel)[yadahan/laravel-authentication-log

Laravel Authentication Log provides authentication logger and notification for Laravel.

416632.8k5](/packages/yadahan-laravel-authentication-log)[kitloong/laravel-app-logger

Laravel log for your application

101.2M8](/packages/kitloong-laravel-app-logger)[label84/laravel-auth-log

Log user authentication actions in Laravel.

3654.0k](/packages/label84-laravel-auth-log)

PHPackages © 2026

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