How to add logging to an abstract class in php

29 Views Asked by At

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.

0

There are 0 best solutions below