Log each request in ZF2

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 03:44:06

问题


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?


回答1:


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()
      ));
    });
  }
}



回答2:


Sounds like you could attach a listener to the dispatch event on Zend\Mvc\Application.

For reference, Rob Allen has created a handy list of ZF2 events.



来源:https://stackoverflow.com/questions/14348307/log-each-request-in-zf2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!