Slim V3 and Monolog


#1

I have tried to implement Monolog based on an example

My code, in a simple way, looks like

use \Psr\Http\Message\ServerRequestInterface;
use \Psr\Http\Message\ResponseInterface;

require '../vendor/autoload.php';

$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);

/* Logger */
$container = $app->getContainer();

$container['logger'] = function($c) {
    $logger = new \Monolog\Logger('API_logger');
    $file_handler = new \Monolog\Handler\StreamHandler("../logs/API.log");
    $logger->pushHandler($file_handler);
    
    return $logger;
} ;

/** my routes here **/

$app->run();

but then when I try to execute Monolog and save to log via

$this->logger->addInfo("Something interesting happened");  

in my route function it throws an error Using $this when not in object context

Any clue why the code from an example is not working as expected?


#2

Please show the code around

$this->logger->addInfo("Something interesting happened");

#3
/** my routes here  - example code below**/
$app->get('/', 'api');

$app->run();

function api($request, $response) {
    $response->write('REST API v1');
    $this->logger->addInfo("Something interesting happened"); 

    return $response;
}

#4

In case someone bumps into this conversation:
I switched file path to:
$file_handler = new \Monolog\Handler\StreamHandler(“logs/API.log”);

and it started to log my messages.