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