phploggingzend-framework2zend-log

Log each request in ZF2


We are using zend framework 2 for a new application, i would like to have the same logging system of Rails or similar, i would like have a log for each request, is possible to do this in Zend?


Solution

  • It depends what you want to log. If it is just an access log, you should try to use the webserver's log. The logs from Apache/nginx/IIS etc perform better than you will achieve in your ZF2 app.

    If you need to log inside the ZF2 application, you have two choices. First option is at bootstrap. It's one of the earliest options you can use, so probably therefore the best. However, you can also look at route or dispatch. Those two events are called during the "run" phase of the application. With these events, you have for example a route match available and therefore you know (or not) if your request did match any controller (or in case you don't have the match, it's a 404).

    Some examples. Let's assume you have a logger configured in the ServiceManager under the logger key. Then to log at bootstrap:

    namespace Application;
    
    class Module
    {
      public function onBootstrap($e)
      {
        $app = $e->getApplication();
        $sm  = $app->getServiceManager();
    
        $logger = $sm->get('logger');
        $logger->debug('Log here!');
      }
    }
    

    Or for example if you wait for route, you attach a listener for the route event:

    namespace Application;
    
    use Zend\Mvc\MvcEvent;
    use Zend\Mvc\Router\RouteMatch;
    
    class Module
    {
      public function onBootstrap($e)
      {
        $app = $e->getApplication();
        $em  = $app->getEventManager();
        $sm  = $app->getServiceManager();
    
        $logger = $sm->get('logger');
        $em->attach(MvcEvent::EVENT_ROUTE, function($e) use ($logger) {
          $match = $e->getRouteMatch();
    
          // No route, this is a 404
          if (!$match instanceof RouteMatch) {
            return;
          }
    
          $logger->debug(sprintf(
            'Route event with route %s',
            $match->getMatchedRouteName()
          ));
        });
      }
    }