我想将所有请求记录到我的Slim Rest服务器。 200 ok,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 - 纤细: how to log all request to the framework,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21288532/

10-13 07:04