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

103 views Asked by At

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.

1

There are 1 answers

1
Penicylline On

I prefer to get logger by dependence injection for logger or your third option.

DI::getInstance()->get('logger')

It's easy to replace default logger by a dummy for unit test or a high performance once for production environment.