Symfony 4 Custom Bundle use Logger Interface

Viewed 627

I am trying to implement a custom Symfony bundle and inside my service I need to pass the global symfony logger that I defined in my Symfony App and it is an instance of Psr\Log\LoggerInterface. The problem is that when I am configuring my services with the ContainerBuilder the logger service is not yet initialised.

In my bundle service I am passing the Logger like this:

public function __construct(LoggerInterface $logger, $argument1, $argument2);

The two arguments are being delivered from the packages/my_custom_bundle_config.yaml file. However I can't pass the App's Logger as a parameter even in the above config file.

Any help or any comments will be much appreciated.

Thank you.

1 Answers

There are three things you need to do:

  1. Create a compiler pass. You can search for them in the documentation. Basically, they allow you to modify the container just before it is compiled, when all definitions and aliases have been registered.

  2. Is really good practice in your configuration class to define a service id for the logger, in case your users want to use a different implementation. In your extension class, you should pass that reference as an argument.

  3. Usually all bundles that rely on psr interfaces register an alias of it to a default implementation. They are usually called logger.default or something similar. You can search in monolog bundle extension class for the definitions they use or use the interface, that will have an alias.

Related