Php – Best way to access a logger across an application/website in PHP

loggingPHP

I've recently read up on PSR-3 and am interested in learning about the best way(s) of approaching a logger implementation across a web application or website. I understand how a logger is defined and how they can be implemented per PSR-3, but what about accessing/referencing them across the application for various logging needs such as caught exceptions, notable events, etc.?

These three options came to mind. Are there any more? Which is the best approach?

  1. Global object – $logger->debug('foo')
  2. Global static instance – Logger::debug('foo')
  3. via some kind of method – $app->getLogger()->debug('foo')
  4. …etc…

One of my considerations is keeping the code needed for referencing the logger at a minimum. For example, option 3 above seems like it would get rather tedious to retrieve the logger like that for every appropriate caught exception, notable event, etc., throughout the application.

Best Answer

I personally like to use Dependency Injection. Here is some example:

class MyClass
{
   public function __constructor(\Psr\Log\LoggerInterface $logger)
   {
       $this->logger = $logger;
   }

   public function someMethod()
   {
      $this->logger->warning('some warning');
   }
}

The only thing that you must do is configure the dependency injection container to use your concrete logger class that implements PSR3.

Related Topic