jrebs / laravel-log-requests
以最小的努力记录请求和响应。
dev-master
2021-04-20 23:20 UTC
Requires
- php: ^7.2
- laravel/framework: >=6.20.12
This package is auto-updated.
Last update: 2024-09-21 07:00:17 UTC
README
这是一个快速简单的Laravel包,用于添加对HTTP请求和响应的简单记录。无需任何配置,只需将提供的中间件与您要包括的路由关联即可。
创建此包时,我考虑了以下几点
- 捕获应用中API调用的请求和响应
- 利用最新的Laravel特性,实现轻松的包注入
- 通过合理的零配置默认设置,轻松跨应用重用
- 允许轻松覆盖应用或环境自定义的处理程序
要求
php >= 7.2laravel/framework >= 5.8
安装
composer require jrebs/laravel-log-requests
要使用默认设置,将迁移发布到您的应用程序并执行迁移
php artisan vendor:publish --provider=Jrebs\\LogRequests\\Providers\\LogRequestsServiceProvider php artisan migrate
现在,您只需声明要记录的路由。然后,您的App\Http\Kernel可能包含如下内容
protected $middlewareGroups = [ // ... 'api' => [ 'throttle:60,1', 'bindings', 'log-requests', // Record all API requests to api_requests table ], ];
现在,当您访问api路由时,应发现它们被存储,并且可以使用Jrebs\LogRequests\LoggedRequest模型进行访问。
或者,您可以在路由文件中应用中间件
// routes/web.php Route::middleware('log-requests')->group(function () { // routes defined in this group closure will all be passed to the handler });
访问日志
默认日志处理程序使用提供的Jrebs\LogRequests\LoggedRequest。如果您打算编写任何代码来访问提供的日志模型,我建议您扩展LoggedRequest类到您的App命名空间中的某个类,然后您可以在模型上设置关系,例如将user_id属性与您的App\User模型或类似模型进行连接。
自定义处理程序示例
要使用您自己的存储方法,请跳过发布迁移,而是只发布config,这样您就可以提供自己的处理程序
php artisan vendor:publish --provider=Jrebs\\LogRequests\\Providers\\LogRequestsServiceProvider --tag=config
现在您需要在config/log-requests.php中声明您的自定义处理程序
return [ // Set an app-provided Handler to override the package handler 'handler' => env('LOG_REQUESTS_HANDLER', App\CustomHandler::class), ];
如您所见,您也可以通过编辑.env文件来在运行时覆盖此设置
# Override both the package and the app-provided handler LOG_REQUESTS_HANDLER=App\CustomHandler
自定义处理程序需要实现LogRequestsHandler接口,提供一个接受请求、响应和持续时间的静态log()方法。以下是在app/CustomHandler.php中提供您自己的自定义处理程序的简单示例
/** * Example handler - app/CustomHandler.php */ namespace App; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Jrebs\LogRequests\LogRequestsHandler; class CustomHandler implements LogRequestHandler { public static function log($request, $response, $duration): void { /** * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response $response * @param float $duration */ Log::debug(sprintf( "Request: %s\nResponse: %s\nDuration: %s", serialize($request->input()), serialize($response->getContent()), $duration )); } }
待办事项
- 编写待办事项列表
- 弄清楚是否有某种合理的方式可以单独测试此包