cpsit/request-logger
Composer 安装命令:
composer require cpsit/request-logger
包简介
A PSR-15 compatible request logging middleware
README 文档
README
A PSR-15 compatible request logging middleware for PHP applications that provides flexible and configurable HTTP request logging capabilities.
Overview
The Request Logger package allows you to log HTTP requests based on customizable matching rules. It integrates seamlessly with any PSR-15 compatible application and uses PSR-3 logging standards.
Features
- PSR-15 Middleware: Compatible with any PSR-15 compliant application
- PSR-3 Logging: Uses standard PSR-3 logging interface
- Flexible Request Matching: Configurable rules to determine which requests to log
- Customizable Data Extraction: Extract specific data from requests for logging
- Log Level Support: Full PSR log level support (emergency, alert, critical, error, warning, notice, info, debug)
- PHP 8.2+ Compatible: Modern PHP with type declarations and readonly classes
Requirements
- PHP ^8.2.0
- PSR HTTP Message ^1.0 || ^2.0
- Extensions: filter, json, mbstring
Installation
composer require cpsit/request-logger
Architecture
The package consists of several key components:
Core Components
LoggerMiddleware
The main middleware class (src/Middleware/LoggerMiddleware.php:29) that processes HTTP requests and logs them based on matching rules.
RequestMatcherInterface
Interface (src/RequestMatcherInterface.php:24) that defines how to match requests for logging. Implementations must provide:
matches(ServerRequestInterface $request): bool- Determines if a request should be loggedgetLevel(): LogLevel- Returns the log level for matched requestsgetDescription(): string- Provides a description of the matching rules
DataProviderInterface
Interface (src/Data/DataProviderInterface.php:23) for extracting data from requests to be logged.
DefaultDataProvider
Default implementation (src/Data/DefaultDataProvider.php:23) that extracts common request data:
- Headers
- URI
- Parsed body
- Query parameters
- Cookie parameters
LogLevel Enum
PSR-3 compatible log levels (src/Enum/LogLevel.php:24) supporting all standard levels from emergency to debug.
Basic Usage
1. Create a Request Matcher
First, implement the RequestMatcherInterface to define which requests should be logged:
<?php use Cpsit\RequestLogger\RequestMatcherInterface; use Cpsit\RequestLogger\Enum\LogLevel; use Psr\Http\Message\ServerRequestInterface; class ApiRequestMatcher implements RequestMatcherInterface { public function matches(ServerRequestInterface $request): bool { $path = $request->getUri()->getPath(); return str_starts_with($path, '/api/'); } public function getLevel(): LogLevel { return LogLevel::INFO; } public function getDescription(): string { return 'API requests logging matcher'; } }
2. Set Up the Middleware
<?php use Cpsit\RequestLogger\Middleware\LoggerMiddleware; use Cpsit\RequestLogger\Data\DefaultDataProvider; use Psr\Log\LoggerInterface; // Assume you have a PSR-3 logger instance $logger = new YourLoggerImplementation(); // Create the middleware $requestMatcher = new ApiRequestMatcher(); $dataProvider = new DefaultDataProvider(); $loggerMiddleware = new LoggerMiddleware( $logger, $requestMatcher, $dataProvider ); // Add to your middleware stack $app->add($loggerMiddleware);
TYPO3 v13 Integration
Installation in TYPO3
Add the package to your TYPO3 project:
composer require cpsit/request-logger
Configuration
1. Create a Custom Request Matcher
Create a request matcher for TYPO3-specific logging needs:
<?php // Classes/RequestLogger/BackendRequestMatcher.php declare(strict_types=1); namespace YourVendor\YourExtension\RequestLogger; use Cpsit\RequestLogger\RequestMatcherInterface; use Cpsit\RequestLogger\Enum\LogLevel; use Psr\Http\Message\ServerRequestInterface; final class BackendRequestMatcher implements RequestMatcherInterface { public function matches(ServerRequestInterface $request): bool { $path = $request->getUri()->getPath(); // Log all backend requests return str_starts_with($path, '/typo3/') || str_contains($path, '/typo3conf/'); } public function getLevel(): LogLevel { return LogLevel::INFO; } public function getDescription(): string { return 'TYPO3 Backend requests'; } }
2. Custom Data Provider for TYPO3
Create a TYPO3-aware data provider:
<?php // Classes/RequestLogger/Typo3DataProvider.php declare(strict_types=1); namespace YourVendor\YourExtension\RequestLogger; use Cpsit\RequestLogger\Data\DataProviderInterface; use Psr\Http\Message\ServerRequestInterface; use TYPO3\CMS\Core\Context\Context; use TYPO3\CMS\Core\Utility\GeneralUtility; final class Typo3DataProvider implements DataProviderInterface { public function get(ServerRequestInterface $request): array { $context = GeneralUtility::makeInstance(Context::class); return [ 'uri' => (string)$request->getUri(), 'method' => $request->getMethod(), 'userAgent' => $request->getHeaderLine('User-Agent'), 'referer' => $request->getHeaderLine('Referer'), 'remoteAddr' => $request->getServerParams()['REMOTE_ADDR'] ?? '', 'requestTime' => $request->getServerParams()['REQUEST_TIME'] ?? time(), 'typo3Context' => [ 'backend_user_id' => $context->getPropertyFromAspect('backend.user', 'id', 0), 'frontend_user_id' => $context->getPropertyFromAspect('frontend.user', 'id', 0), 'workspace_id' => $context->getPropertyFromAspect('workspace', 'id', 0), 'language_id' => $context->getPropertyFromAspect('language', 'id', 0), ], 'queryParams' => $request->getQueryParams(), ]; } }
3. Service Configuration
Register your services in Configuration/Services.yaml:
services: _defaults: autowire: true autoconfigure: true public: false YourVendor\YourExtension\RequestLogger\BackendRequestMatcher: tags: - name: 'request.logger.matcher' identifier: 'backend' YourVendor\YourExtension\RequestLogger\Typo3DataProvider: tags: - name: 'request.logger.data_provider' identifier: 'typo3' YourVendor\YourExtension\RequestLogger\RequestLoggerMiddleware: arguments: $logger: '@Psr\Log\LoggerInterface' $requestMatcher: '@YourVendor\YourExtension\RequestLogger\BackendRequestMatcher' $dataProvider: '@YourVendor\YourExtension\RequestLogger\Typo3DataProvider' tags: - name: 'request.middleware' identifier: 'request-logger' before: 'typo3/cms-core/normalized-params-attribute'
4. Middleware Registration
Register the middleware in Configuration/RequestMiddlewares.php:
<?php return [ 'frontend' => [ 'your-extension/request-logger' => [ 'target' => \Cpsit\RequestLogger\Middleware\LoggerMiddleware::class, 'before' => [ 'typo3/cms-core/normalized-params-attribute', ], ], ], 'backend' => [ 'your-extension/request-logger' => [ 'target' => \Cpsit\RequestLogger\Middleware\LoggerMiddleware::class, 'before' => [ 'typo3/cms-core/normalized-params-attribute', ], ], ], ];
Advanced TYPO3 Examples
Security-focused Request Matcher
<?php declare(strict_types=1); namespace YourVendor\YourExtension\RequestLogger; use Cpsit\RequestLogger\RequestMatcherInterface; use Cpsit\RequestLogger\Enum\LogLevel; use Psr\Http\Message\ServerRequestInterface; final class SecurityRequestMatcher implements RequestMatcherInterface { private array $suspiciousPatterns = [ '/\.\./', '/eval\s*\(/', '/script.*>/', '/union.*select/i', '/drop.*table/i', ]; public function matches(ServerRequestInterface $request): bool { $uri = (string)$request->getUri(); $body = (string)$request->getBody(); // Check for suspicious patterns in URI or body foreach ($this->suspiciousPatterns as $pattern) { if (preg_match($pattern, $uri) || preg_match($pattern, $body)) { return true; } } // Log failed login attempts if (str_contains($uri, '/typo3/login') && $request->getMethod() === 'POST') { return true; } return false; } public function getLevel(): LogLevel { return LogLevel::WARNING; } public function getDescription(): string { return 'Security-related requests (suspicious patterns, failed logins)'; } }
Performance Monitoring Matcher
<?php declare(strict_types=1); namespace YourVendor\YourExtension\RequestLogger; use Cpsit\RequestLogger\RequestMatcherInterface; use Cpsit\RequestLogger\Enum\LogLevel; use Psr\Http\Message\ServerRequestInterface; final class PerformanceRequestMatcher implements RequestMatcherInterface { private float $startTime; public function __construct() { $this->startTime = microtime(true); } public function matches(ServerRequestInterface $request): bool { $executionTime = microtime(true) - $this->startTime; // Log slow requests (>2 seconds) return $executionTime > 2.0; } public function getLevel(): LogLevel { return LogLevel::NOTICE; } public function getDescription(): string { return 'Slow request performance monitoring'; } }
Logging Configuration
Configure TYPO3 logging in Configuration/LocalConfiguration.php:
'LOG' => [ 'YourVendor' => [ 'YourExtension' => [ 'RequestLogger' => [ 'writerConfiguration' => [ \Psr\Log\LogLevel::INFO => [ \TYPO3\CMS\Core\Log\Writer\FileWriter::class => [ 'logFile' => 'typo3temp/logs/request-logger.log' ], ], \Psr\Log\LogLevel::WARNING => [ \TYPO3\CMS\Core\Log\Writer\FileWriter::class => [ 'logFile' => 'typo3temp/logs/security.log' ], ], ], ], ], ], ],
Testing
The package includes unit tests demonstrating proper usage. Key test scenarios:
- Non-matching requests are not logged (
tests/unit/Middleware/LoggerTest.php:56) - Matching requests are properly logged with correct data (
tests/unit/Middleware/LoggerTest.php:67)
Run tests:
composer test
Development
Available Scripts
composer lint- Run all linting toolscomposer test- Run unit testscomposer sca:php- Run static code analysis
Code Quality
The package maintains high code quality standards with:
- PHP CS Fixer for code style
- PHPStan for static analysis (level 6)
- EditorConfig for consistent formatting
- Comprehensive unit tests
License
GPL-3.0-or-later
Contributing
The package follows PSR standards and modern PHP practices. All contributions should maintain the existing code quality standards and include appropriate tests.
cpsit/request-logger 适用场景与选型建议
cpsit/request-logger 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 0 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 02 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 cpsit/request-logger 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 cpsit/request-logger 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 0
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 18
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: GPL-3.0-or-later
- 更新时间: 2026-02-19