Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slim : how to log all request to the framework

Tags:

php

slim

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%'
        ))
    )
);
like image 875
user3149715 Avatar asked Jan 22 '14 16:01

user3149715


1 Answers

With slim v3, you can't use hooks anymore.

Here is the solution I came up with :

Add a new middleware

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;
});

Logger settings

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,
        ]
    ]
]

Output

[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

like image 130
Gabriel Bourgault Avatar answered Sep 19 '22 09:09

Gabriel Bourgault