I would like to log all requests to my Slim Rest server. 200 ok, 404 errors, etc...
With the following code I can only log Exceptions. I want to log all the incoming requests.
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%'
))
)
);
With slim v3, you can't use hooks anymore.
Here is the solution I came up with :
A middleware can be seen as a function which is applied to every incoming request. Therefore, it sort of intercepts every request, allowing us to log everything we need.
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;
});
Of course, you need to setup the Logger dependency in the container like so
$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;
};
With the logger settings
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"}
Hope this helps someone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With