PHPackages                             methorz/http-request-logger - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. methorz/http-request-logger

ActiveLibrary[HTTP &amp; Networking](/categories/http)

methorz/http-request-logger
===========================

PSR-3 HTTP request logging middleware with request tracking and performance monitoring

v1.1.0(4mo ago)050MITPHPPHP ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0CI passing

Since Dec 1Pushed 4mo agoCompare

[ Source](https://github.com/MethorZ/http-request-logger)[ Packagist](https://packagist.org/packages/methorz/http-request-logger)[ RSS](/packages/methorz-http-request-logger/feed)WikiDiscussions main Synced 1mo ago

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

MethorZ Structured Logging
==========================

[](#methorz-structured-logging)

**PSR-3 structured logging with request tracking and performance monitoring for PSR-15 applications**

[![CI](https://github.com/MethorZ/http-request-logger/actions/workflows/ci.yml/badge.svg)](https://github.com/MethorZ/http-request-logger/actions/workflows/ci.yml)[![codecov](https://camo.githubusercontent.com/4e2f17c382d69b1c0233d600dc42530fabe5fff34c6fce728873113405c1a5d9/68747470733a2f2f636f6465636f762e696f2f67682f4d6574686f725a2f687474702d726571756573742d6c6f676765722f67726170682f62616467652e737667)](https://codecov.io/gh/MethorZ/http-request-logger)[![PHPStan](https://camo.githubusercontent.com/1bc07920f0d36e55c17e1d38b1caa132cc605f51a82b388c962870b9a747b898/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230392d627269676874677265656e2e737667)](https://phpstan.org/)[![PHP Version](https://camo.githubusercontent.com/c9f64f714c636ba27a3bba6dfd52f98426832db1262747efa54b212d16943651/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e322d626c7565)](https://php.net)[![License](https://camo.githubusercontent.com/f8df3091bbe1149f398a5369b2c39e896766f9f6efba3477c63e9b4aa940ef14/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e)](LICENSE)

Automatically add request IDs and performance metrics to all logs in PSR-15 middleware applications. Zero configuration, framework-agnostic, production-ready.

---

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

[](#-features)

- 🔖 **Request ID Tracking** - Unique ID for every request, added to all logs automatically
- ⏱️ **Performance Monitoring** - Track execution time and memory usage for requests and operations
- 🎯 **PSR-15 Middleware** - Drop-in middleware for automatic logging
- 📊 **Structured Logs** - JSON-compatible context for easy parsing and analysis
- 🔧 **PSR-3 Compatible** - Works with any PSR-3 logger (Monolog, etc.)
- 🌐 **Response Headers** - Optionally adds `X-Request-ID` header to responses
- 🚀 **Zero Configuration** - Works out-of-the-box with sensible defaults
- 🎨 **Customizable** - Full control over processors and logging behavior

---

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

[](#-installation)

```
composer require methorz/http-request-logger
```

---

🚀 Quick Start
-------------

[](#-quick-start)

### **1. Add Middleware to Your Application**

[](#1-add-middleware-to-your-application)

```
use MethorZ\RequestLogger\Middleware\LoggingMiddleware;

// Mezzio / Laminas
$app->pipe(new LoggingMiddleware($logger));

// Any PSR-15 application
$dispatcher->pipe(new LoggingMiddleware($logger));
```

That's it! Every request will now have:

- Unique request ID in all logs
- Request start/end logging
- Automatic performance metrics
- Exception logging with context

---

📖 Detailed Usage
----------------

[](#-detailed-usage)

### **Request ID Processor**

[](#request-id-processor)

Adds a unique request ID to all log records:

```
use MethorZ\RequestLogger\Processor\RequestIdProcessor;
use Monolog\Logger;

$logger = new Logger('app');
$logger->pushProcessor(new RequestIdProcessor());

$logger->info('User logged in', ['user_id' => 123]);
// Log output includes: {"message": "User logged in", "extra": {"request_id": "req_..."}"}
```

**Custom Request ID**:

```
$processor = new RequestIdProcessor('custom-request-id');
```

**Retrieve Request ID**:

```
$requestId = $processor->getRequestId();
```

### **Performance Logger**

[](#performance-logger)

Track performance metrics for operations:

```
use MethorZ\RequestLogger\Logger\PerformanceLogger;

$perfLogger = new PerformanceLogger($logger);

// Method 1: Start/End
$perfLogger->start('database-query');
$users = $repository->findAll();
$perfLogger->end('database-query', ['query' => 'SELECT * FROM users']);

// Method 2: Measure callable
$result = $perfLogger->measure('api-call', function () use ($apiClient) {
    return $apiClient->fetchData();
}, ['endpoint' => '/api/users']);

// Method 3: Log request performance
$startTime = microtime(true);
// ... handle request ...
$perfLogger->logRequest($startTime, [
    'method' => 'POST',
    'uri' => '/api/users',
    'status' => 201,
]);
```

**Logged Performance Metrics**:

```
{
    "message": "Performance: database-query",
    "context": {
        "operation": "database-query",
        "duration_ms": 45.23,
        "memory_peak_mb": 12.5,
        "query": "SELECT * FROM users"
    }
}
```

### **Logging Middleware**

[](#logging-middleware)

PSR-15 middleware for automatic request logging:

```
use MethorZ\RequestLogger\Middleware\LoggingMiddleware;
use MethorZ\RequestLogger\Processor\RequestIdProcessor;

// Basic usage
$middleware = new LoggingMiddleware($logger);

// Custom request ID processor
$processor = new RequestIdProcessor('custom-id');
$middleware = new LoggingMiddleware($logger, $processor);

// Disable X-Request-ID header
$middleware = new LoggingMiddleware($logger, null, false);
```

**What It Logs**:

Request start:

```
{
    "message": "Request started",
    "context": {
        "method": "POST",
        "uri": "https://example.com/api/users",
        "request_id": "req_673e5c2f47a0c1.23456789"
    }
}
```

Request completion:

```
{
    "message": "Request completed",
    "context": {
        "method": "POST",
        "uri": "https://example.com/api/users",
        "status": 201,
        "duration_ms": 127.45,
        "memory_peak_mb": 15.2,
        "request_id": "req_673e5c2f47a0c1.23456789"
    }
}
```

Exception:

```
{
    "message": "Request failed with exception",
    "context": {
        "method": "POST",
        "uri": "https://example.com/api/users",
        "exception": "User not found",
        "exception_class": "App\\Exception\\NotFoundException",
        "request_id": "req_673e5c2f47a0c1.23456789"
    }
}
```

---

🎯 Use Cases
-----------

[](#-use-cases)

### **Distributed Tracing**

[](#distributed-tracing)

Correlate logs across services using request IDs:

```
// Service A
$requestId = $processor->getRequestId();
$client->request('POST', '/api/service-b', [
    'headers' => ['X-Request-ID' => $requestId],
]);

// Service B receives request with same ID
// All logs from both services share the request ID
```

### **Performance Bottleneck Detection**

[](#performance-bottleneck-detection)

Track slow operations:

```
$perfLogger->start('slow-operation');
$result = $this->processData($largeDataset);
$perfLogger->end('slow-operation', [
    'records_processed' => count($largeDataset),
], LogLevel::WARNING); // Use WARNING level if it's slow
```

### **Production Debugging**

[](#production-debugging)

Find all logs for a specific request:

```
# Filter logs by request ID
cat app.log | jq 'select(.extra.request_id == "req_673e5c2f47a0c1.23456789")'
```

---

🔧 Configuration
---------------

[](#-configuration)

### **Mezzio Configuration**

[](#mezzio-configuration)

```
// config/autoload/logging.global.php
use MethorZ\RequestLogger\Middleware\LoggingMiddleware;
use MethorZ\RequestLogger\Processor\RequestIdProcessor;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

return [
    'dependencies' => [
        'factories' => [
            LoggerInterface::class => function (ContainerInterface $container): Logger {
                $logger = new Logger('app');
                $logger->pushHandler(new StreamHandler('php://stdout', Logger::INFO));
                return $logger;
            },
            RequestIdProcessor::class => fn() => new RequestIdProcessor(),
            LoggingMiddleware::class => function (ContainerInterface $container): LoggingMiddleware {
                return new LoggingMiddleware(
                    $container->get(LoggerInterface::class),
                    $container->get(RequestIdProcessor::class),
                );
            },
        ],
    ],
];

// config/pipeline.php
$app->pipe(LoggingMiddleware::class);
```

---

📊 Log Structure
---------------

[](#-log-structure)

All logs follow a consistent structure for easy parsing:

```
{
    "message": "User action",
    "context": {
        "user_id": 123,
        "action": "login"
    },
    "level": 200,
    "level_name": "INFO",
    "channel": "app",
    "datetime": "2024-11-26T10:30:45.123456+00:00",
    "extra": {
        "request_id": "req_673e5c2f47a0c1.23456789"
    }
}
```

---

🔍 Monolog Integration
---------------------

[](#-monolog-integration)

Works seamlessly with Monolog:

```
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\JsonFormatter;
use MethorZ\RequestLogger\Processor\RequestIdProcessor;

$logger = new Logger('app');

// JSON formatter for structured logs
$handler = new StreamHandler('php://stdout', Logger::INFO);
$handler->setFormatter(new JsonFormatter());
$logger->pushHandler($handler);

// Add request ID processor
$logger->pushProcessor(new RequestIdProcessor());
```

---

🧪 Testing
---------

[](#-testing)

```
# Run tests
composer test

# Static analysis
composer analyze

# Code style
composer cs-check
composer cs-fix
```

---

🔗 Related Packages
------------------

[](#-related-packages)

This package is part of the MethorZ HTTP middleware ecosystem:

PackageDescription**[methorz/http-dto](https://github.com/methorz/http-dto)**Automatic HTTP ↔ DTO conversion with validation**[methorz/http-problem-details](https://github.com/methorz/http-problem-details)**RFC 7807 error handling middleware**[methorz/http-cache-middleware](https://github.com/methorz/http-cache-middleware)**HTTP caching with ETag support**[methorz/http-request-logger](https://github.com/methorz/http-request-logger)**Structured logging (this package)**[methorz/openapi-generator](https://github.com/methorz/openapi-generator)**Automatic OpenAPI spec generationThese packages work together seamlessly in PSR-15 applications.

---

📄 License
---------

[](#-license)

MIT License. See [LICENSE](LICENSE) for details.

---

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

[](#-contributing)

Contributions welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

---

🔗 Links
-------

[](#-links)

- [Changelog](CHANGELOG.md)
- [Contributing](CONTRIBUTING.md)
- [Security](SECURITY.md)
- [Issues](https://github.com/MethorZ/http-request-logger/issues)

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance75

Regular maintenance activity

Popularity8

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

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

Total

2

Last Release

136d ago

### Community

Maintainers

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

---

Tags

composerframework-agnosticloggingmiddlewaremonitoringpackagistperformancephpphp8psr-15psr-3request-idrequest-logginghttppsr-3middlewareloggingmonitoringperformancepsr-15request id

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/methorz-http-request-logger/health.svg)

```
[![Health](https://phpackages.com/badges/methorz-http-request-logger/health.svg)](https://phpackages.com/packages/methorz-http-request-logger)
```

###  Alternatives

[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M97](/packages/mezzio-mezzio)[mezzio/mezzio-authentication

Authentication middleware for Mezzio and PSR-7 applications

121.6M26](/packages/mezzio-mezzio-authentication)[middlewares/access-log

Middleware to generate access logs

20121.2k2](/packages/middlewares-access-log)[idealo/php-middleware-stack

Implementation of HTTP Middleware PSR-15 specification

318.9k](/packages/idealo-php-middleware-stack)

PHPackages © 2026

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