webman如何記錄http請求日志?
webman如何記錄http請求日志?我想用webman做api后端開發(fā),前端請求接口的時候,提示404,我不知道完整的請求url,怎么記錄完整的http請求日志呢?
給你一個我在用的方法,作用是有接口請求時在控制臺顯示請求信息。
新建中間件,在目錄 app\common\middleware 下新建 RequestDebug.php 文件,內(nèi)容如下:
<?php
declare(strict_types=1);
namespace app\common\middleware;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
// 請求調(diào)試中間件,在控制臺打印請求的路徑和數(shù)據(jù)
class RequestDebug implements MiddlewareInterface
{
// 顯示請求信息
public static function showRequestInfo(Request $request)
{
$now = date('Y-m-d H:i:s');
echo "================================== 請求開始 {$now} ====================================", PHP_EOL;
echo '請求路徑:';
echo $request->path(), PHP_EOL;
echo '完整路徑:';
echo $request->fullUrl(), PHP_EOL;
echo '請求數(shù)據(jù):', PHP_EOL;
echo json_encode($request->all(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), PHP_EOL;
echo '請求頭數(shù)據(jù):', PHP_EOL;
echo json_encode($request->header(), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT), PHP_EOL;
}
public function process(Request $request, callable $handler): Response
{
$start_time = microtime(true);
self::showRequestInfo($request);
$response = $handler($request);
$end_time = microtime(true);
$cost_time = ($end_time - $start_time) * 1000;
echo "響應數(shù)據(jù):", PHP_EOL;
echo $response->rawBody(), PHP_EOL;
$now = date('Y-m-d H:i:s');
echo "================================== 請求結(jié)束 {$now} 耗時:{$cost_time}MS ====================================", PHP_EOL;
return $response;
}
}
在 config/middleware.php 文件中注冊該中間件:
return [
// 全局中間件
'' => [
app\common\middleware\RequestDebug::class,
// ... 這里省略其它中間件
],
];
正常請求就可以顯示請求信息了,但是如果請求的路由不存在,顯示404時該中間件是不起作用的,這時候要用路由的fallback功能了。在config/route.php文件中新增以下代碼:
Route::fallback(function (Request $request) {
\app\common\middleware\RequestDebug::showRequestInfo($request);
// 后續(xù)處理流程
});
大功告成,404請求也會顯示請求信息了。具體需要顯示的請求信息你可以自己修改。