I usually use Monolog for my PHP logging and debugging, but have found I end up with each of my classes instantiating there own Monolog\Logger, which is fine for a project with just one or two classes in it, but I want to share these classes across multiple projects using Composer etc. To avoid having each class use its own logger I currently use the following code which simply allows me to pass an instance of Logger if its is configured and if not then the class sets up a Null logger itself :
/**
* Basic Constructor
*
* @param Logger|Null Logging instance or Null to do no logging at all
*/
public function __construct($logger = null)
{
if ($logger !== null) {
$this->logger = $logger;
} else {
$this->logger = new Logger('dummy');
$this->logger->pushHandler(new NullHandler());
}
}
private function test($var1,$var2) {
$this->logger->debug('test method called with '.$var1.' and '.$var2);
}
Is this the best way to configure debugging for my classes or is there something that is more universal/just plain better coding practice?
I have also used a method inside my classes in the past that tests if $this->debug is not null and if so then calls Logger with the data, rather than sending everything to a null Logger but this then requires multiple methods for each log level:
/**
* If debug enabled, send all passed parameters to debugger
*/
public function debug()
{
if (is_null($this->debug)) {
return;
}
$args = func_get_args();
$this->debug->debug(print_r($args, true));
}
I am not using any pre built frameworks, but i would think the same problem would still occur when using my own classes with a framework.