Files
webman_duanju/support/LogMiddleware.php
2025-08-18 11:15:32 +08:00

78 lines
2.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace support;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
class LogMiddleware implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
// 使用示例
$logFile = '/rh/webman_duanju/runtime/logs/webman-' . date('Y-m-d') . '.log';
// 确保目录存在
$logDir = dirname($logFile);
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true); // 创建目录权限755
}
$filePath = $logFile;
// 检查文件是否存在
if (!file_exists($filePath)) {
// 如果文件不存在,先创建文件
if (!touch($filePath)) {
error_log("无法创建文件: $filePath");
}
}
// 检查当前是否已有写入权限
if (is_writable($filePath)) {
// 已有写入权限,无需修改
}else {
// 尝试设置权限
if (chmod($filePath, 0664)) {
} else {
error_log("无法给文件设置权限:" . $filePath . "权限值:" . 0664);
}
}
// 定义颜色
$green = "\033[32m"; // 标题/分隔
$yellow = "\033[33m"; // 方法/状态码
$blue = "\033[34m"; // URL
$cyan = "\033[36m"; // 参数/头信息
$magenta = "\033[35m"; // Body
$reset = "\033[0m"; // 重置
// 打印请求日志
$requestLog = $green . "====== 请求开始 ======" . $reset . "\n" .
"方法: " . $yellow . $request->method() . $reset . "\n" .
"URL: " . $blue . $request->url() . $reset . "\n" .
"GET参数: " . $cyan . json_encode($request->get(), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . $reset . "\n" .
// "请求头: " . $cyan . json_encode($request->header(), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . $reset . "\n" .
"Body: " . $magenta . $request->rawBody() . $reset;
Log::info($requestLog);
// 处理请求
$response = $handler($request);
// 获取响应内容并截取前200字符
// $bodySnippet = mb_substr($response, 0, 200);
// 打印响应日志
// $responseLog = $green . "====== 请求结束 ======" . $reset . "\n" .
// "URL: " . $blue . $request->url() . $reset . "\n" .
// "Body前200: " . $magenta . $bodySnippet . $reset;
//
// Log::info($responseLog);
return $response;
}
}