Files
webman_duanju/support/LogMiddleware.php
2025-08-18 11:12:37 +08:00

88 lines
2.8 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
{
function setFileWritePermission($filePath, $permission = 0664) {
// 检查文件是否存在
if (!file_exists($filePath)) {
// 如果文件不存在,先创建文件
if (!touch($filePath)) {
error_log("无法创建文件: $filePath");
return false;
}
}
// 检查当前是否已有写入权限
if (is_writable($filePath)) {
return true; // 已有写入权限,无需修改
}
// 尝试设置权限
if (chmod($filePath, $permission)) {
return true;
} else {
error_log("无法给文件设置权限:" . $filePath . "权限值:" . $permission);
return false;
}
}
// 使用示例
$logFile = '/rh/webman_duanju/runtime/logs/webman-' . date('Y-m-d') . '.log';
// 确保目录存在
$logDir = dirname($logFile);
if (!is_dir($logDir)) {
mkdir($logDir, 0755, true); // 创建目录权限755
}
// 给文件设置写入权限使用0664权限比0666更安全
setFileWritePermission($logFile);
// 定义颜色
$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;
}
}