Search code examples
symfonysymfony4

monolog.logger.db service has been removed


I'm trying to refactor some Symfony 3 code to Symfony 4.

I am getting the following error when attempting to log:

The "monolog.logger.db" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the conta iner directly and use dependency injection instead.

My logging code:

$logger = $container->get('monolog.logger.db');
        $logger->info('Import command triggered');

Monolog config:

monolog:
    channels: ['db']
    handlers:
        db:
            channels: ['db']
            type: service
            id: app.monolog.db_handler

app.monolog.db_handler config (Note, I tried public: true here and it had no affect:

app.monolog.db_handler:
    class: App\Util\MonologDBHandler
    arguments: ['@doctrine.orm.entity_manager']

How can I get this wired up correctly in Symfony 4?


Solution

  • It appears that App\Util\MonologDBHandler may be the only thing that is actively using monolog.logger.db - via a container->get('...') call. (If not, you will want to use this technique to tag the specific sort of logger into more services).

    You would be better to allow the framework to build the app.monolog.db_handler service itself, and use the container to help to build it. Normally, to inject a logger service, you will just need to type-hint it:

    // in App\Util\MonologDBHandler.php
    use Psr\Log\LoggerInterface;
    
    public function __construct(LoggerInterface $logger = null) {...}
    

    However, that will, by default, setup with the default @logger, so you need to add an extra hint in the service definition of the handler that you want a different type of logger:

    services:
        App\Log\CustomLogger:
            arguments: ['@logger']
            tags:
                - { name: monolog.logger, channel: db }
    

    Now, the logger in CustomLogger should be what you had previously known as monolog.logger.db.

    You can also alias a different interface (similar to how the LoggerInterface is aliased to inject '@logger') to the allow for the tagging.