PHPackages                             edwinekr/otel-elk-laravel - 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. edwinekr/otel-elk-laravel

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

edwinekr/otel-elk-laravel
=========================

OpenTelemetry activity logging integration with ELK Stack for Laravel applications

v1.0.9(2mo ago)3108↓50%MITPHPPHP ^8.0

Since Feb 5Pushed 2mo agoCompare

[ Source](https://github.com/EDWNKR/otel-elk-laravel)[ Packagist](https://packagist.org/packages/edwinekr/otel-elk-laravel)[ RSS](/packages/edwinekr-otel-elk-laravel/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (10)Versions (12)Used By (0)

OpenTelemetry ELK Laravel
=========================

[](#opentelemetry-elk-laravel)

[![Latest Version on Packagist](https://camo.githubusercontent.com/939a0eb5d4fbe80b6be3b05978146ef94fd1b8e7913719334a24da91a905124c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f656477696e656b722f6f74656c2d656c6b2d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/edwinekr/otel-elk-laravel)[![Total Downloads](https://camo.githubusercontent.com/fa746e0f39e2bb3185b7ecfa9b7e9f55065197c753aebc3d372383ac1f0ccb9f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f656477696e656b722f6f74656c2d656c6b2d6c61726176656c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/edwinekr/otel-elk-laravel)

OpenTelemetry activity logging integration with ELK Stack (Elasticsearch, Logstash, Kibana) for Laravel applications.

Architecture
------------

[](#architecture)

```
Laravel App → OpenTelemetry SDK → Logstash HTTP (5044) → Elasticsearch → Kibana (Map View)

```

Features
--------

[](#features)

- 🚀 **Automatic HTTP Request Logging** - All requests are logged with response time, status codes, and user info
- 🔐 **Authentication Event Logging** - Login, logout, failed attempts, lockouts, and password resets
- 📊 **Model Activity Logging** - Track create, update, and delete operations on Eloquent models
- 🎯 **Custom Activity Logging** - Log any custom activity with metadata
- ⚡ **Async Logging** - Non-blocking log submission for better performance
- 🔒 **Sensitive Data Masking** - Automatically redact passwords, tokens, and other sensitive fields
- 🌍 **GeoIP Ready** - Works with Logstash GeoIP filter for location visualization in Kibana

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

[](#requirements)

- PHP 8.0+
- Laravel 10.x, 11.x, or 12.x
- Guzzle HTTP Client

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require edwinekr/otel-elk-laravel
```

The package will auto-register its service provider.

### Publish Configuration

[](#publish-configuration)

```
php artisan vendor:publish --tag=otel-elk-config
```

This will create `config/activity_log.php` in your application.

Configuration
-------------

[](#configuration)

Add the following to your `.env` file:

```
# ===========================================
# Activity Log / OpenTelemetry Configuration
# ===========================================

# Enable/disable activity logging (default: true)
ACTIVITY_LOG_ENABLED=true

# Logstash HTTP endpoint for receiving logs
ACTIVITY_LOG_ENDPOINT=http://localhost:5044

# Application name for log identification
ACTIVITY_LOG_APP_NAME=my-laravel-app

# Environment identifier (development, staging, production)
ACTIVITY_LOG_ENVIRONMENT=production

# Request timeout in seconds for sending logs
ACTIVITY_LOG_TIMEOUT=2

# Send logs asynchronously (recommended for performance)
ACTIVITY_LOG_ASYNC=true

# Log request body (⚠️ be careful with sensitive data)
ACTIVITY_LOG_REQUEST_BODY=false

# Auto-register middleware globally (default: true)
ACTIVITY_LOG_AUTO_MIDDLEWARE=true

# Log authentication events (default: true)
ACTIVITY_LOG_AUTH_EVENTS=true

# Exclude AJAX/XHR requests (default: true) - reduces DataTable noise
ACTIVITY_LOG_EXCLUDE_AJAX=true

# Exclude requests expecting JSON response (default: false)
ACTIVITY_LOG_EXCLUDE_JSON=false

# Exclude static assets - CSS, JS, images, fonts (default: true)
ACTIVITY_LOG_EXCLUDE_ASSETS=true

# Exclude redirect responses - 3xx status codes (default: true)
ACTIVITY_LOG_EXCLUDE_REDIRECTS=true

# Only log controller actions, exclude Closures (default: true)
ACTIVITY_LOG_ONLY_CONTROLLERS=true

# Only log HTML requests, exclude CSS/JS preloads (default: true)
ACTIVITY_LOG_ONLY_HTML=true

# Only log routes that have a name (default: true)
ACTIVITY_LOG_ONLY_NAMED_ROUTES=true

# Fallback IP for local development (default: Banten, Indonesia)
ACTIVITY_LOG_LOCAL_IP=103.28.12.1

# Use fallback IP when running locally (default: true)
ACTIVITY_LOG_USE_LOCAL_IP=true

# User resolver: 'default', 'session', or 'custom'
ACTIVITY_LOG_USER_RESOLVER=default

# Session key for user data (when using session resolver)
ACTIVITY_LOG_SESSION_USER_KEY=user
```

Usage
-----

[](#usage)

### Automatic HTTP Request Logging

[](#automatic-http-request-logging)

All HTTP requests are automatically logged when the middleware is enabled. No additional code required!

### Manual Activity Logging

[](#manual-activity-logging)

Use the `ActivityLog` facade or inject `ActivityLogService`:

```
use Edwinekr\OtelElkLaravel\Facades\ActivityLog;

// Log a custom activity
ActivityLog::log(
    action: 'order.checkout',
    entity: 'Order',
    entityId: $order->id,
    metadata: [
        'total' => $order->total,
        'items_count' => $order->items->count(),
        'payment_method' => $order->payment_method,
    ]
);
```

### Using Dependency Injection

[](#using-dependency-injection)

```
use Edwinekr\OtelElkLaravel\Services\ActivityLogService;

class OrderController extends Controller
{
    public function __construct(private ActivityLogService $activityLog)
    {
    }

    public function checkout(Request $request)
    {
        $order = Order::create([...]);

        $this->activityLog->log(
            action: 'order.checkout',
            entity: 'Order',
            entityId: $order->id,
            metadata: [
                'total' => $order->total,
                'items_count' => $order->items->count(),
            ]
        );

        return response()->json(['order' => $order]);
    }
}
```

### Model Activity Logging

[](#model-activity-logging)

Use the `LogsActivity` trait on your Eloquent models:

```
use Edwinekr\OtelElkLaravel\Traits\LogsActivity;

class Product extends Model
{
    use LogsActivity;

    // Model will automatically log created, updated, deleted events
}
```

You can also log custom activities on a model:

```
$product->logActivity('viewed', ['viewer_ip' => request()->ip()]);
```

### Authentication Events

[](#authentication-events)

Authentication events are automatically logged when enabled. These events are tracked:

- `auth.login` - User logged in
- `auth.logout` - User logged out
- `auth.failed` - Login attempt failed
- `auth.lockout` - User was locked out
- `auth.registered` - New user registered
- `auth.password_reset` - Password was reset

Real User Monitoring (RUM)
--------------------------

[](#real-user-monitoring-rum)

This package includes Elastic APM RUM (Real User Monitoring) support for browser-side performance monitoring and error tracking.

### RUM Configuration

[](#rum-configuration)

Add the following to your `.env` file:

```
# ===========================================
# Elastic APM RUM Configuration
# ===========================================

# Enable/disable RUM (default: false)
ELASTIC_APM_RUM_ENABLED=true

# Service name for RUM (default: APP_NAME)
ELASTIC_APM_RUM_SERVICE_NAME=my-laravel-app

# Elastic APM RUM endpoint URL (required)
ELASTIC_APM_RUM_URL=https://your-apm-server:8200

# Secret token for APM authentication (optional)
ELASTIC_APM_RUM_TOKEN=your-secret-token

# API key for APM authentication (optional, preferred over token)
ELASTIC_APM_RUM_API_KEY=your-api-key

# Service version for tracking deployments (default: 1.0.0)
ELASTIC_APM_RUM_SERVICE_VERSION=1.0.0

# Environment identifier (default: APP_ENV)
ELASTIC_APM_RUM_ENVIRONMENT=production

# Transaction sample rate 0.0 to 1.0 (default: 1.0 = 100%)
ELASTIC_APM_RUM_SAMPLE_RATE=1.0

# Page load transaction name (default: Page Load)
ELASTIC_APM_RUM_PAGE_LOAD_NAME="Page Load"

# Enable page load span ID (default: true)
ELASTIC_APM_RUM_PAGE_LOAD_SPAN_ID=true

# Custom CDN URL for RUM agent (optional)
ELASTIC_APM_RUM_CDN_URL=https://unpkg.com/@elastic/apm-rum@5.16.0/dist/bundles/elastic-apm-rum.umd.min.js
```

### Using the RUM Blade Component

[](#using-the-rum-blade-component)

Add the RUM script to your layout file (before closing `` tag):

```

    My App

    {{-- Include Elastic APM RUM Script --}}

    @yield('content')

```

The component will only render when RUM is enabled (`ELASTIC_APM_RUM_ENABLED=true`) and a valid server URL is configured.

### Using the RUM Facade

[](#using-the-rum-facade)

For more control, use the `Rum` facade:

```
use Edwinekr\OtelElkLaravel\Facades\Rum;

// Check if RUM is enabled
if (Rum::isEnabled()) {
    // Get the full RUM configuration
    $config = Rum::getConfig();

    // Get the initialization script as JSON string
    $initScript = Rum::getInitScript();

    // Get the CDN URL
    $cdnUrl = Rum::getCdnUrl();

    // Render the complete script HTML
    $html = Rum::renderScript();
}
```

### Using the RUM Helper

[](#using-the-rum-helper)

You can also use the helper class directly:

```
use Edwinekr\OtelElkLaravel\Helpers\RumHelper;

// Get the full script HTML for custom implementations
$scriptHtml = RumHelper::renderScript();
```

### Distributed Tracing Origins

[](#distributed-tracing-origins)

To enable distributed tracing between frontend and backend, configure the origins in `config/activity_log.php`:

```
'elastic_apm_rum' => [
    // ... other options
    'distributed_tracing_origins' => [
        'https://api.example.com',
        'https://backend.example.com',
    ],
],
```

### Publishing RUM Views

[](#publishing-rum-views)

To customize the RUM script template:

```
php artisan vendor:publish --tag=otel-elk-views
```

This will publish the views to `resources/views/vendor/otel-elk/`.

### Using Session-Based User Resolver

[](#using-session-based-user-resolver)

If your application uses session-based authentication instead of Laravel's built-in auth:

```
ACTIVITY_LOG_USER_RESOLVER=session
ACTIVITY_LOG_SESSION_USER_KEY=user
```

Make sure your session contains user data:

```
// Store user in session
Session::put('user', [
    'id' => $user->id,
    'name' => $user->name,
    'email' => $user->email,
]);
```

### Manual Middleware Registration

[](#manual-middleware-registration)

If you prefer to register the middleware manually, disable auto-registration:

```
ACTIVITY_LOG_AUTO_MIDDLEWARE=false
```

Then register it in your routes or kernel:

```
// In routes/api.php
Route::middleware(['activity-log'])->group(function () {
    // Your routes
});
```

Or for Laravel 11+ in `bootstrap/app.php`:

```
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Edwinekr\OtelElkLaravel\Middleware\ActivityLogMiddleware::class);
})
```

Excluding Paths and Methods
---------------------------

[](#excluding-paths-and-methods)

Configure excluded paths in `config/activity_log.php`:

```
'excluded_paths' => [
    'health',
    'ready',
    'livez',
    'metrics',
    '_debugbar/*',
    'telescope/*',
    'horizon/*',
    'sanctum/csrf-cookie',
    'api/internal/*',
],

'excluded_methods' => [
    'OPTIONS',
],
```

Sensitive Fields
----------------

[](#sensitive-fields)

Sensitive fields are automatically masked in request body logs:

```
'sensitive_fields' => [
    'password',
    'password_confirmation',
    'token',
    'secret',
    'api_key',
    'credit_card',
    'cvv',
],
```

Logstash Configuration
----------------------

[](#logstash-configuration)

Example Logstash configuration for receiving logs:

```
input {
    http {
        port => 5044
        codec => json
    }
}

filter {
    # Add GeoIP data based on client IP
    if [ip] {
        geoip {
            source => "ip"
            target => "geoip"
        }
    }

    # Parse timestamp
    date {
        match => ["timestamp", "ISO8601"]
        target => "@timestamp"
    }
}

output {
    elasticsearch {
        hosts => ["elasticsearch:9200"]
        index => "activity-logs-%{+YYYY.MM.dd}"
    }
}
```

Kibana Visualization
--------------------

[](#kibana-visualization)

After logs are ingested, you can create visualizations in Kibana:

1. Go to **Kibana → Maps**
2. Click **Add layer → Documents**
3. Select your index pattern `activity-logs-*`
4. Choose `geoip.location` as the geospatial field
5. Configure tooltips to show: `ip`, `user_email`, `action`, `path`

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Edwin KR](https://github.com/EDWNKR)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance86

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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 ~2 days

Total

10

Last Release

73d ago

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

v1.0.5PHP ^8.0

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/35441758?v=4)[Edwin Kurnia Rahman](/maintainers/EDWNKR)[@EDWNKR](https://github.com/EDWNKR)

---

Top Contributors

[![EDWNKR](https://avatars.githubusercontent.com/u/35441758?v=4)](https://github.com/EDWNKR "EDWNKR (3 commits)")

---

Tags

laravelloggingmonitoringelasticsearchopentelemetryotelactivity-logELKlogstashkibana

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/edwinekr-otel-elk-laravel/health.svg)

```
[![Health](https://phpackages.com/badges/edwinekr-otel-elk-laravel/health.svg)](https://phpackages.com/packages/edwinekr-otel-elk-laravel)
```

###  Alternatives

[rollbar/rollbar-laravel

Rollbar error monitoring integration for Laravel projects

14110.4M7](/packages/rollbar-rollbar-laravel)

PHPackages © 2026

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