gpt4 book ai didi

php - slim : how to log all request to the framework

转载 作者:可可西里 更新时间:2023-11-01 13:35:18 24 4
gpt4 key购买 nike

我想将所有请求记录到我的 Slim Rest 服务器。 200 正常,404 错误等...

使用以下代码我只能记录异常。我想记录所有传入的请求。

require 'Slim/Slim.php';

\Slim\Slim::registerAutoloader();

require 'Slim/Extras/Log/DateTimeFileWriter.php';

$app = new \Slim\Slim (
array(
'debug' => true,
'log.enabled' => true,
'log.level' => \Slim\Log::DEBUG,
'log.writer' => new \Slim\Extras\Log\DateTimeFileWriter(array(
'path' => '/tmp/slim',
'name_format' => 'Y-m-d',
'message_format' => '%label% - %date% - %message%'
))
)
);

最佳答案

使用 slim v3,您 can't use hooks anymore .

这是我想出的解决方案:

添加一个新的中间件

中间件可以看作是应用于每个传入请求的函数。因此,它可以拦截每个请求,让我们能够记录所需的一切。

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

$app->add(function (Request $request, Response $response, callable $next) {
$route = $request->getAttribute('route');
$this->logger->info($request->getMethod() . ' ' . $route->getPattern(), [$route->getArguments()]);
$response = $next($request, $response);
$this->logger->info($response->getStatusCode() . ' ' . $response->getReasonPhrase(), [(string)$response->getBody()]);

return $response;
});

记录器设置

当然,你需要像这样在容器中设置Logger依赖

$container = $app->getContainer();

// monolog
$container['logger'] = function ($c) {
$settings = $c->get('settings')['logger'];
$logger = new Monolog\Logger($settings['name']);
$logger->pushProcessor(new Monolog\Processor\UidProcessor());
$logger->pushHandler(new Monolog\Handler\StreamHandler($settings['path'], $settings['level']));
return $logger;
};

使用记录器设置

return [
'determineRouteBeforeAppMiddleware' => true, //VERY IMPORTANT for route logging
'settings' => [
// Monolog settings
'logger' => [
'name' => 'slim-app',
'path' => __DIR__ . '/../logs/app.log',
'level' => \Monolog\Logger::DEBUG,
]
]
]

输出

[2017-06-18 03:40:19] slim-app.INFO: GET /api/publication/{id:[0-9]+} [{"id":"0"}] {"uid":"6e64305"}
[2017-06-18 03:40:19] slim-app.INFO: 200 OK ["[]"] {"uid":"6e64305"}

希望这对某人有帮助

关于php - slim : how to log all request to the framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21288532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com