Slim-4 How to get container logger inside routs?

I crate a container logger, and use it for addErrorMiddleware.
But how to reach this logger inside routes?

use DI\Container;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

$container = new Container();
$container->set(‘logger’, function () {
$logger = new Logger(‘app’);
$file_handler = new StreamHandler(DIR . ‘/…/logs/app.log’);
return $logger;

$app = AppFactory::create();

$errorMiddleware = $app->addErrorMiddleware(true, true, true, $container->get(‘logger’));

require ‘routes.php’;

and routes.php:
use …
$app->group(’/v1’, function( Group $group ) {
$group->group(’/user’, function( Group $grp ) {
$grp->get(’/hello/{name}’, function( Request $request, Response $response, array $args ) {
$name = $args[‘name’];
// how to rich $container->get(‘logger’) ?
$response->getBody()->write(“Hello, $name”);
return $response;

This is where single-action controllers come into play :slight_smile:

I only have a little experience with Slim, but if I’ve interpreted your code correctly, I believe it should be accessible within the routes by calling $this->get('logger'), for example:

$this->get('logger')->info('Test log entry');

Good luck.

1 Like

You are right [facepalm]

No problem at all!

For future reference, here is a link to to the relevant section of the documentation:

1 Like