I am sorry, but I am a newbie to Slim 4 and I have a simple question to logging something to the default logfile app.log. I created a new sample project with composer and got the following app in routes.php which is running fine:
<?php declare(strict_types=1); use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\App; return function (App $app) { $app->get('/', function (Request $request, Response $response) { // Here I want to log something to app.log $response->getBody()->write('Hello world!'); return $response; }); }; As I saw there is a logging ContainerBuilder function prepared for this in dependencies.php but I dont know how to use that in my apps route functions. I want to log a string into app.log at the point marked with a comment in the app above. Can anyone point me to the solution for this please? Regards, Tomtry so
<?php declare(strict_types=1);
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
return function (App $app) {
$app->get('/', function (Request $request, Response $response) use ($app) {
// Here I want to log something to app.log
$logger = $app->getContainer()->get('LoggerInterface::class');
$logger->info('message');
$response->getBody()->write('Hello world!');
return $response;
});
};
Thx for you fast reponse Mikalay. When I add the 2 lines to my app, I get a server error 500 with the message “Call to a member function getContainer() on null”.
in route.php
<?php
declare(strict_types=1);
use App\Application\Actions\User\ListUsersAction;
use App\Application\Actions\User\ViewUserAction;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Log\LoggerInterface;
use Slim\App;
use Slim\Interfaces\RouteCollectorProxyInterface as Group;
return function (App $app) {
$container = $app->getContainer();
$app->get('/', function (Request $request, Response $response) use ($container) {
// Here I want to log something to app.log
$logger = $container->get(LoggerInterface::class);
$logger->info('message123');
$response->getBody()->write('Hello world!');
return $response;
});
$app->group('/users', function (Group $group) use ($container) {
$group->get('', ListUsersAction::class);
$group->get('/{id}', ViewUserAction::class);
});
};
Cool - thats exactly what I needed!
Thanky you very much Mikalay!