[Slim4] Log all access and error to database?

Hello folks,

Is this possible to log all access to the application ?
Maybe with a custom middleware or with the default ErrorMiddleware ?

And obviously, logging to database/elk is the following question. Is this possible to access the container from a middleware (I have already added monolog to the container)?

Thanks a lot

Wilfried

I manage to create a middleware but i got some issues,
Is this the correct way to create a “pass through” middleware (for example a middleware who does nothing to the response) ?

class LogRouteMiddleware
{    
    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler) : 
    Response
    {
        // get the request
        $oldRequest = $handler->handle($request);
        $response = new Response();
        $response->getBody()->write((string) $oldRequest->getBody());
        $response = $response->withStatus($oldRequest->getStatusCode());
        foreach ($oldRequest->getHeaders() as $name => $value) {
            $response = $response->withAddedHeader($name, $value);
        }
    
        return $response;
    }
}

for some reasons i can’t simply do

return $handler->handle($request);

The PSR-15 handle method returns a response object and not a request.

So this must work:

return $handler->handle($request);

Is this possible to log all access to the application ?
Maybe with a custom middleware or with the default ErrorMiddleware ?

If you use the Slim ErrorMiddleware you could handle it in your custom default error handler:

$errorMiddleware = $app->addErrorMiddleware(true, false, false);
$errorMiddleware->setDefaultErrorHandler(
    $container->get(\App\Handler\MyDefaultErrorHandler::class)
);

Hello,

It was my mistake, i used the wrong use statement, with :

use Psr\Http\Message\ResponseInterface as Response;
[...]
return $handler->handle($request);

Everything is working as attended.

I declare the middleware as a service, then inside this middleware I can manipulate the request and log all access in the database (ugly, but it works).

I may be able to release the sourcecode if someone is interested (of course for the moment this is a POC, so the code may be ugly)