Zend Expressive 2
我需要所有输入和所有输出。 我的,pipeline.php
$app->pipe(\Zend\Stratigility\Middleware\ErrorHandler::class);
$app->pipe(\Zend\Expressive\Helper\ServerUrlMiddleware::class);
$app->pipe(\App\Middleware\LogRequestsMiddleware::class);
$app->pipeRoutingMiddleware();
$app->pipe(\Zend\Expressive\Middleware\ImplicitHeadMiddleware::class);
$app->pipe(\Zend\Expressive\Middleware\ImplicitOptionsMiddleware::class);
$app->pipe(\Zend\Expressive\Helper\UrlHelperMiddleware::class);
$app->pipeDispatchMiddleware();
$app->pipe(\App\Middleware\LogResponseMiddleware::class);
$app->pipe(\Zend\Expressive\Middleware\NotFoundHandler::class);
LogResponseMiddleware不执行。如果错误也需要。
答案 0 :(得分:0)
正确的顺序:
$app->pipe(\App\Middleware\LogResponseMiddleware::class);
$app->pipe(\Zend\Stratigility\Middleware\ErrorHandler::class);
$app->pipe(\Zend\Expressive\Helper\ServerUrlMiddleware::class);
$app->pipeRoutingMiddleware();
$app->pipe(\Zend\Expressive\Middleware\ImplicitHeadMiddleware::class);
$app->pipe(\Zend\Expressive\Middleware\ImplicitOptionsMiddleware::class);
$app->pipe(\Zend\Expressive\Helper\UrlHelperMiddleware::class);
$app->pipeDispatchMiddleware();
$app->pipe(\App\Middleware\LogRequestsMiddleware::class);
$app->pipe(\Zend\Expressive\Middleware\NotFoundHandler::class);
详细信息:https://framework.zend.com/blog/2017-03-15-nested-middleware-in-expressive.html
答案 1 :(得分:0)
您可以非常轻松地记录请求和响应,只需创建一个中间件:
<?php
namespace Acme\Middleware;
use Psr\Log\LoggerInterface;
use Interop\Http\ServerMiddleware\DelegateInterface;
use Interop\Http\ServerMiddleware\MiddlewareInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class LoggingMiddleware implements MiddlewareInterface
{
/**
* @var Psr\Log\LoggerInterface $logger
*/
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function process(ServerRequestInterface $request, DelegateInterface $delegate) {
// log the request
$this->logger->log(Logger::INFO, 'Request', []);
$response = $delegate->process($request);
// log the response
$this->logger->log(Logger::INFO, 'Response', []);
return $response;
}
}
在您的工厂中,您可以使用任何PSR记录器,例如monolog:
<?php
namespace Acme\Middleware;
use Interop\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
class LoggingMiddlewareFactory
{
public function __invoke(ContainerInterface $container)
{
$logger = $container->get(LoggerInterface::class);
return new LoggingMiddleware($logger);
}
}
最后,必须在ServerUrlMiddleware:
之后准确地将日志记录中间件添加到管道中<?php
// config/pipeline.php
$app->pipe(ErrorHandler::class);
$app->pipe(ServerUrlMiddleware::class);
$app->pipe(LoggingMiddleware::class);
那就是它。