Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 998
Coder1 Avatar asked Oct 29 '25 11:10

Coder1


2 Answers

By default all services in Symfony 4 are private (and is the recommended pratice) so you need to "inject" in each Controller each needed service (personally I use a custom CommonControllerServiceClass).

You can also create a public service "alias" to continue accessing the service as you did, but it's not the best pratice to follow (also because I guess you will have many other services to fix).

mylogger.db:
    alias: monolog.logger.db
    public: true

then you can get the service from the container:

$logger = $container->get('mylogger.db');
like image 119
gp_sflover Avatar answered Nov 01 '25 14:11

gp_sflover


Alister's answer is a good start, but you can utilise service arguments binding instead of creating a new service for each logger:

services:
    _defaults:
        autowire: true
        bind:
            $databaseLogger: '@monolog.logger.db'

Then just change the argument name in your class:

// in App\Util\MonologDBHandler.php 

use Psr\Log\LoggerInterface;

public function __construct(LoggerInterface $databaseLogger = null) {...}
like image 37
Oggy Avatar answered Nov 01 '25 13:11

Oggy