Search code examples
monologslim-3

How to use monolog in slim 3?


In my app.php file:

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

class App extends \DI\Brifge\Slim\app
{
 public function configureContainer(ContainerBuilder $builder)
 {
  $dependencies = [
            'logger' => function (Container $container) { 
            $logger = new Monolog\Logger('logger');
            $filename = _DIR__ . '/../log/error.log';
            $stream = new Monolog\Handler\StreamHandler($filename, Monolog\Logger::DEBUG);
            $fingersCrossed = new Monolog\Handler\FingersCrossedHandler(
            $stream, Monolog\Logger::ERROR);
            $logger->pushHandler($fingersCrossed);

            return $logger;
        },
      ];
    }
   }

In my custom error handler:

class CustomErrorHandler
{
 protected $logger;

 public function __construct(Logger $logger)
 {
    $this->logger = $logger;
 }

 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $exception)
 {
    $output = ['success'=>0, 'error'=>"Oops! Something's not right "];

    $this->logger->critical($output);

    return $response->withStatus(500)
                    ->withHeader('Content-Type', 'application/json')
                    ->write(json_encode($output));
 }
}

When an error is thrown, following message is displayed:

Fatal error: Uncaught Error: Class 'App\Monolog\Logger' not found in C:\xampp\htdocs\backend\app\App.php:103 Stack trace: #0 [internal function]: App\App->App{closure}(Object(DI\Container)) #1 C:\xampp\htdocs\backend\vendor\php-di\invoker\src\Invoker.php(82): call_user_func_array(Object(Closure), Array) #2 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Definition\Resolver\FactoryResolver.php(81): Invoker\Invoker->call(Object(Closure), Array) #3 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Definition\Resolver\ResolverDispatcher.php(58): DI\Definition\Resolver\FactoryResolver->resolve(Object(DI\Definition\FactoryDefinition), Array) #4 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Container.php(287): DI\Definition\Resolver\ResolverDispatcher->resolve(Object(DI\Definition\FactoryDefinition), Array) #5 C:\xampp\htdocs\backend\vendor\php-di\php-di\src\DI\Container.php(124): DI\Container->resolveDefinition(Object(DI\Definition\FactoryDefinition)) #6 C:\xampp\htdocs\backend\app\App.php(95): DI\Container->get('l in C:\xampp\htdocs\backend\app\App.php on line 103

I have included the statement use Monolog\Logger; in App.php file but I get the above error.


Solution

  • I understood where I was wrong. No need to include the lines:

    use Monolog\Logger;
    use Monolog\Handler\StreamHandler;
    

    While instantiating, I have included the complete path.