PHPackages                             rcommerz/logger-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. rcommerz/logger-laravel

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

rcommerz/logger-laravel
=======================

Production-ready structured logging for Laravel microservices with OpenTelemetry support

v1.0.4(2mo ago)017MITPHPPHP ^8.2|^8.3CI passing

Since Feb 22Pushed 2mo agoCompare

[ Source](https://github.com/rcommerz/logger-laravel)[ Packagist](https://packagist.org/packages/rcommerz/logger-laravel)[ RSS](/packages/rcommerz-logger-laravel/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (13)Versions (7)Used By (0)

RCOMMERZ Logger for Laravel
===========================

[](#rcommerz-logger-for-laravel)

![Tests](https://camo.githubusercontent.com/6e2b45ac31c13515c8cefeecef356b51cfd147a647c8354bc13ee798f058a3b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f74657374732d333125323070617373696e672d627269676874677265656e)![PHP Version](https://camo.githubusercontent.com/67c3c669880c1494574a6bb754eac4e2ebb1d47e05f6e29d3e70220935405c79/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e32253230253743253230253545382e332d626c7565)![Laravel](https://camo.githubusercontent.com/13996d9392ccc5353cd52a993163d46cc2f44c41b33eecfa77cfc830b40ca5a2/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d25354531302e3025323025374325323025354531312e3025323025374325323025354531322e3025323025374325323025354531332e302d726564)![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)

Production-ready structured JSON logging for Laravel microservices with OpenTelemetry support. Built on top of Monolog with ECS (Elastic Common Schema) compatible output.

Features
--------

[](#features)

- ✅ **Structured JSON Logging** - ECS-compatible format for seamless integration with Elasticsearch, Datadog, and other log aggregators
- ✅ **OpenTelemetry Integration** - Automatic trace context injection (trace\_id, span\_id, trace\_flags)
- ✅ **HTTP Request/Response Logging** - Middleware for automatic API logging with configurable filtering
- ✅ **Security Built-in** - Automatic sensitive header redaction (Authorization, Cookie, API keys)
- ✅ **Laravel Auto-Discovery** - Zero configuration needed, works out of the box
- ✅ **Monolog Based** - Extends Monolog with custom formatter and processor for maximum flexibility
- ✅ **Type-Safe** - Fully typed with PHP 8.1+ features
- ✅ **100% Test Coverage** - 31 tests, 62 assertions, production-ready

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

[](#requirements)

- PHP 8.2 or higher (PHP 8.3+ required for Laravel 13)
- Laravel 10.x, 11.x, 12.x, or 13.x
- Monolog 3.5+

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

[](#installation)

Install via Composer:

```
composer require rcommerz/logger-laravel
```

The service provider will be automatically registered thanks to Laravel's package auto-discovery.

### Publish Configuration (Optional)

[](#publish-configuration-optional)

```
php artisan vendor:publish --tag=rcommerz-logger-config
```

This creates `config/rcommerz_logger.php` where you can customize settings.

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

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Rcommerz\Logger\Logger;

// Get logger instance (singleton)
$logger = Logger::getInstance();

// Log messages with context
$logger->info('User logged in', ['user_id' => 'usr-123', 'email' => 'user@example.com']);
$logger->error('Payment failed', ['order_id' => 'ord-456', 'error' => 'Insufficient funds']);
$logger->debug('Cache hit', ['key' => 'user:123', 'ttl' => 3600]);
```

### Using Facade

[](#using-facade)

```
use Rcommerz\Logger\Facades\Logger;

Logger::info('Order created', ['order_id' => 'ord-789']);
Logger::security('Unauthorized access attempt', ['ip' => request()->ip()]);
Logger::audit('User role changed', ['user_id' => 'usr-123', 'old_role' => 'user', 'new_role' => 'admin']);
```

### HTTP Middleware

[](#http-middleware)

Add to your middleware stack to automatically log all HTTP requests/responses:

```
// app/Http/Kernel.php
protected $middleware = [
    // ... other middleware
    \Rcommerz\Logger\Middleware\HttpLoggerMiddleware::class,
];
```

Or apply to specific routes:

```
// routes/api.php
Route::middleware(['api', \Rcommerz\Logger\Middleware\HttpLoggerMiddleware::class])
    ->group(function () {
        Route::get('/users', [UserController::class, 'index']);
    });
```

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

[](#configuration)

### Environment Variables

[](#environment-variables)

Configure via `.env`:

```
# Service Identity
SERVICE_NAME=my-laravel-app
SERVICE_VERSION=1.0.0
APP_ENV=production

# Logging Level (DEBUG, INFO, WARNING, ERROR)
LOG_LEVEL=INFO

# HTTP Middleware Options
LOG_INCLUDE_HEADERS=false
LOG_INCLUDE_BODY=false
```

### Configuration File

[](#configuration-file)

After publishing, edit `config/rcommerz_logger.php`:

```
return [
    'service_name' => env('SERVICE_NAME', config('app.name', 'laravel-app')),
    'service_version' => env('SERVICE_VERSION', '1.0.0'),
    'env' => env('APP_ENV', 'production'),
    'level' => env('LOG_LEVEL', 'INFO'),

    // Paths to exclude from HTTP logging
    'exclude_paths' => [
        'health',
        'metrics',
        'api/health',
        'api/metrics',
    ],

    'include_headers' => env('LOG_INCLUDE_HEADERS', false),
    'include_body' => env('LOG_INCLUDE_BODY', false),
];
```

Available Log Levels
--------------------

[](#available-log-levels)

```
$logger->debug('Debug information');    // DEBUG
$logger->info('Informational message'); // INFO
$logger->warn('Warning message');       // WARNING
$logger->error('Error occurred');       // ERROR
$logger->http('HTTP request');          // INFO with http context
$logger->security('Security event');    // WARNING with security flag
$logger->audit('Audit trail');          // INFO with audit flag
```

Log Output Format
-----------------

[](#log-output-format)

All logs are output as single-line JSON to stdout in ECS-compatible format:

```
{
  "@timestamp": "2026-02-22T18:30:45.123Z",
  "log.level": "info",
  "message": "User logged in",
  "service.name": "my-laravel-app",
  "service.version": "1.0.0",
  "service.environment": "production",
  "user_id": "usr-123",
  "email": "user@example.com",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
  "span_id": "00f067aa0ba902b7",
  "trace_flags": "01"
}
```

### HTTP Request Log Example

[](#http-request-log-example)

```
{
  "@timestamp": "2026-02-22T18:30:45.123Z",
  "log.level": "info",
  "message": "POST /api/users - 201",
  "service.name": "my-laravel-app",
  "http.method": "POST",
  "http.path": "/api/users",
  "http.status_code": 201,
  "http.duration_ms": 45.23,
  "client.ip": "192.168.1.100",
  "user.id": "usr-123",
  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736"
}
```

OpenTelemetry Integration
-------------------------

[](#opentelemetry-integration)

The logger automatically detects and includes OpenTelemetry trace context when available. Install OpenTelemetry SDK:

```
composer require open-telemetry/sdk
```

Configure OpenTelemetry instrumentation, and trace context will be automatically injected into all logs.

Advanced Usage
--------------

[](#advanced-usage)

### Access Underlying Monolog Instance

[](#access-underlying-monolog-instance)

```
$monolog = Logger::getInstance()->getMonolog();

// Add custom handlers
$monolog->pushHandler(new \Monolog\Handler\SlackWebhookHandler($webhookUrl));

// Add custom processors
$monolog->pushProcessor(function ($record) {
    $record->extra['custom_field'] = 'value';
    return $record;
});
```

### Exception Logging

[](#exception-logging)

Exceptions are automatically formatted with detailed information:

```
try {
    processPayment($order);
} catch (\Exception $e) {
    $logger->error('Payment processing failed', [
        'order_id' => $order->id,
        'exception' => $e  // Automatically extracts: error.type, error.message, error.stack_trace
    ]);
}
```

### Context Preservation

[](#context-preservation)

Add persistent context to all subsequent log calls:

```
use Monolog\Processor\UidProcessor;

$logger->getMonolog()->pushProcessor(new UidProcessor());
```

Testing
-------

[](#testing)

The package includes comprehensive tests:

```
# Install dependencies
composer install

# Run tests
vendor/bin/phpunit

# Run tests with coverage
vendor/bin/phpunit --coverage-html coverage
```

Security
--------

[](#security)

### Automatic Sensitive Header Redaction

[](#automatic-sensitive-header-redaction)

The HTTP middleware automatically redacts these headers:

- `Authorization`
- `Cookie`
- `X-API-Key`
- `X-Auth-Token`

### Custom Sensitive Data Filtering

[](#custom-sensitive-data-filtering)

Extend the middleware to add custom filtering:

```
class CustomHttpLogger extends \Rcommerz\Logger\Middleware\HttpLoggerMiddleware
{
    protected function buildContext($request, $response, $duration): array
    {
        $context = parent::buildContext($request, $response, $duration);

        // Remove sensitive fields from body
        if (isset($context['http.request.body.password'])) {
            $context['http.request.body.password'] = '[REDACTED]';
        }

        return $context;
    }
}
```

Comparison with Laravel's Default Logging
-----------------------------------------

[](#comparison-with-laravels-default-logging)

FeatureRCOMMERZ LoggerLaravel DefaultStructured JSON✅ ECS-compatible❌ Plain text/JSON mixOpenTelemetry✅ Automatic❌ Manual setupHTTP Logging✅ Middleware included❌ ManualSensitive Data Redaction✅ Automatic❌ ManualMicroservices Ready✅ Built-in⚠️ Requires configSingle-line JSON✅ Always❌ Multi-lineContributing
------------

[](#contributing)

Contributions are welcome! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details.

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for all changes.

License
-------

[](#license)

This package is open-source software licensed under the [MIT license](LICENSE).

Credits
-------

[](#credits)

- Built with [Monolog](https://github.com/Seldaek/monolog)
- OpenTelemetry integration via [open-telemetry/api](https://github.com/open-telemetry/opentelemetry-php)
- Inspired by [Elastic Common Schema](https://www.elastic.co/guide/en/ecs/current/index.html)

Support
-------

[](#support)

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

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance83

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity54

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

Total

5

Last Release

85d ago

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

v1.0.4PHP ^8.2|^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/91b9c896b9abdb600ecb5ef0d8c2fec8a3c512979a12723012f9bd3ab0321585?d=identicon)[islam\_maruf](/maintainers/islam_maruf)

---

Top Contributors

[![islamMaruf](https://avatars.githubusercontent.com/u/42338037?v=4)](https://github.com/islamMaruf "islamMaruf (12 commits)")

---

Tags

laravelloggingopentelemetrymicroservicesstructured-loggingobservability

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rcommerz-logger-laravel/health.svg)

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

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[keepsuit/laravel-opentelemetry

OpenTelemetry integration for laravel

167558.4k1](/packages/keepsuit-laravel-opentelemetry)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45444.2k1](/packages/pressbooks-pressbooks)[naoray/laravel-github-monolog

Log driver to store logs as github issues

10823.1k](/packages/naoray-laravel-github-monolog)[api-platform/laravel

API Platform support for Laravel

58171.8k14](/packages/api-platform-laravel)

PHPackages © 2026

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