Working on a class library I´d like to add logging to a number of classes. I use Psr\Log\LoggingInterface
to give the classes access to a logger object. But how do I set the logger in all classes in a decent way. There is a dependency to the logger as it is being used everywhere in the classes
I can use
Constructor
Add the logger to the constructor with
public function __constructor (
readonly \Psr\Log\LoggingInterface $logger = new \Psr\Log\NullLoger()
);
Setlogger
Use a public setLogger()
public function setLogger( \Psr\Log\LoggingInterface $logger ): self
{
$this->logger = $logger;
return $this;
}
private \Psr\Log\LoggingInterface $logger;
public function __constructor()
{
...
// Make sure a logger is set
$this->logger = new \Psr\Log\NullLogger();
...
}
What would be the best way to do this? Is there a better way.
rj
April 1, 2024 at 09:10 amOne way to achieve this is by using Dependency Injection to inject the logger into the classes that need it. Here's an example of how you can do this:
Implement this interface in the classes that need logging:
When instantiating your classes, inject the logger:
Finally, you can use a factory to instantiate your classes and inject the logger: