the-caretakers/laravel-request-logger
Composer 安装命令:
composer require the-caretakers/laravel-request-logger
包简介
Log HTTP requests and responses in Laravel applications.
README 文档
README
Log incoming HTTP requests and their corresponding responses within your Laravel application. This package provides middleware to capture request/response details, sanitize sensitive data, and store logs on a configurable filesystem disk (like local or S3). Includes a command for log rotation to manage retention for disk space.
Installation
You can install the package via composer:
composer require the-caretakers/laravel-request-logger
Configuration
Publish the configuration file using the vendor:publish Artisan command:
php artisan vendor:publish --provider="TheCaretakers\RequestLogger\Providers\RequestLoggerServiceProvider" --tag="request-logger-config"
This will create a config/request-logger.php file. Review the configuration options:
disk: Filesystem disk for storing logs (defaults toconfig('filesystems.default')). Can be set viaREQUEST_LOGGER_DISKenv variable.log_profile: (Optional) Class to determine if a request should be logged.log_writer: (Optional) Class to handle writing the log entry.sensitive_keywords: Array of keys whose values will be sanitized in logs.truncate_limit: Max length for logged string values before truncation.log_path_structure: Path format for log files (e.g.,http-logs/{Y}-{m}-{d}.log).log_format: Log entry format (jsonrecommended).log_channel: (Optional) Log via a specific Laravel log channel instead of direct filesystem access.log_request_body: Boolean to enable/disable logging request body.log_response_body: Boolean to enable/disable logging response body.
Important: Ensure the configured filesystem disk (e.g., s3) is properly set up in your config/filesystems.php.
Usage
Middleware Registration
Laravel 10 and below (app/Http/Kernel.php)
Add the RequestLoggerMiddleware to the desired middleware group(s) in your app/Http/Kernel.php:
Web Routes:
protected $middlewareGroups = [ 'web' => [ // ... other middleware \TheCaretakers\RequestLogger\Http\Middleware\RequestLoggerMiddleware::class, ], // ... ];
API Routes:
protected $middlewareGroups = [ // ... 'api' => [ // ... other middleware \TheCaretakers\RequestLogger\Http\Middleware\RequestLoggerMiddleware::class, ], ];
Or apply it to specific routes or route groups.
Laravel 11+ (bootstrap/app.php)
In Laravel 11 and later, middleware registration is typically done in the bootstrap/app.php file. Use the withMiddleware method:
<?php use Illuminate\Foundation\Application; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; return Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', health: '/up', ) ->withMiddleware(function (Middleware $middleware) { // Add the request logger middleware globally $middleware->append(\TheCaretakers\RequestLogger\Http\Middleware\RequestLoggerMiddleware::class); // You can also apply it conditionally or to specific groups if needed // $middleware->web(...) // $middleware->api(...) }) ->create();
Log Rotation
The package includes an Artisan command to delete old log files.
php artisan request-logger:rotate
Options:
--days=30: Specify the number of days of logs to keep (default: 30).--disk=s3: Override the configured disk for this run.--dry-run: Simulate the rotation without actually deleting files.
You should schedule this command to run periodically (e.g., daily) in your app/Console/Kernel.php:
protected function schedule(Schedule $schedule) { // ... $schedule->command('request-logger:rotate --days=60')->daily(); // Keep 60 days of logs }
Querying Logs
The package provides a RequestLogQueryBuilder class to help retrieve and filter logged request data directly from the stored log files.
Basic Usage:
use TheCaretakers\RequestLogger\Query\RequestLogQueryBuilder; use Illuminate\Support\Facades\Date; // Get all logs from today's files $logsToday = \TheCaretakers\RequestLogger\RequestLog::query() ->whereDate(\Illuminate\Support\Carbon::now()) ->get(); // Returns an Illuminate\Support\Collection // Count logs from yesterday $countYesterday = \TheCaretakers\RequestLogger\RequestLog::query() ->whereDate(\Illuminate\Support\Carbon::yesterday()) ->count(); // Returns an integer count // Get the latest log entry $latestLog = \TheCaretakers\RequestLogger\RequestLog::query() ->last(); // Returns the last log entry (as an array)
Important Notes:
-
whereDate()Filtering: ThewhereDate()method filters which log files are read based on the date and yourlog_path_structureconfiguration. It expects a date string (e.g.,Y-m-d) or aDateTimeInterfaceobject. -
Collection Filtering: Any filtering beyond the date (e.g., by status code, specific URL, user ID) must be done on the
Collectionreturned by theget()method or on the items within thePaginatorinstance returned bypaginate().$specificUserLogs = (new RequestLogQueryBuilder()) ->whereDate(Date::now()->toDateString()) ->get() ->filter(fn ($log) => $log['user_id'] === 123); $errorLogs = (new RequestLogQueryBuilder()) ->whereDate(Date::now()->toDateString()) ->get() ->filter(fn ($log) => $log['response']['status_code'] >= 500);
-
Configuration: The query builder relies on the
disk,log_path_structure, andlog_formatsettings defined in yourconfig/request-logger.php. Ensure these are correctly configured. Currently, only thejsonlog format is supported for querying. -
Performance: Querying large numbers of log files or very large individual files can be resource-intensive. Ensure your
log_path_structureallows for efficient date-based filtering (e.g., including{Y},{m},{d}).
Customization (Advanced)
- Log Profile: Create a class implementing
TheCaretakers\RequestLogger\Contracts\LogProfilewith ashouldLog(Request $request): boolmethod. Register it in thelog_profileconfig key. - Log Writer: Create a class implementing
TheCaretakers\RequestLogger\Contracts\LogWriterwith awrite(array $logData): voidmethod. Register it in thelog_writerconfig key.
Security Vulnerabilities
Please report any security vulnerabilities to The Caretakers. Your discretion is appreciated. Please do not use the issue tracker for security vulnerabilities.
Credits
License
The MIT License (MIT).
the-caretakers/laravel-request-logger 适用场景与选型建议
the-caretakers/laravel-request-logger 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 125 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 05 月 06 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 the-caretakers/laravel-request-logger 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 the-caretakers/laravel-request-logger 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 125
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 5
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-05-06