3

There is example of using Monolog with PHP-DI (from manual, there are 2 files - index.php and config.php:

<?php
// config.php

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

return [
    // ...

    Psr\Log\LoggerInterface::class => DI\factory(function () {
        $logger = new Logger('mylog');

        $fileHandler = new StreamHandler('path/to/your.log', Logger::DEBUG);
        $fileHandler->setFormatter(new LineFormatter());
        $logger->pushHandler($fileHandler);

        return $logger;
    }),
];

This config.php is using in the below code:

// index.php    
use DI\ContainerBuilder;

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

$containerBuilder = new ContainerBuilder;
$containerBuilder->addDefinitions(__DIR__ . '/config.php');
$container = $containerBuilder->build();

How could I use it now in index.php? Regularly I use Monolog this way:

$log = new Logger('name'); 
$log->warning('Foo');

But how to call it with Container? I was able to do it in simple $container->set(), $container->get() mode. But in this way using Container Builder I can't find a way to do it. Moreover when I make var_dump($container) there are no any logger's signs in it.

szerz
  • 247
  • 2
  • 10

1 Answers1

2

You need to replace $log = new Logger('name') with:

$log = $container->get(\Psr\Log\LoggerInterface::class);

See this part of the documentation: http://php-di.org/doc/getting-started.html#3-create-the-objects

Matthieu Napoli
  • 48,448
  • 45
  • 173
  • 261