在ZF2中记录每个请求 [英] Log each request in ZF2

查看:78
本文介绍了在ZF2中记录每个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在将zend framework 2用于新的应用程序,我想拥有相同的Rails日志系统或类似的日志系统,我想拥有每个请求的日志,是否可以在Zend中做到这一点?

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?

推荐答案

这取决于您要记录的 .如果只是访问日志,则应尝试使用Web服务器的日志.来自Apache/nginx/IIS等的日志的性能要比您在ZF2应用程序中获得的更好.

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.

如果需要登录ZF2应用程序,则有两种选择.第一个选项位于bootstrap.这是您可以使用的最早的选项之一,因此可能是最好的.但是,您也可以查看routedispatch.在应用程序的运行"阶段将调用这两个事件.对于这些事件,例如,您具有可用的路由匹配,因此您知道(或不知道)您的请求是否匹配任何控制器(或者如果您不匹配,则为404).

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).

一些例子.假设您在ServiceManager键下的ServiceManager中配置了一个记录器.然后登录bootstrap:

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!');
  }
}

或者例如,如果您等待route,则为route事件附加一个侦听器:

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

这篇关于在ZF2中记录每个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆