在symfony 1.4中记录API

时间:2013-04-25 10:53:25

标签: php api logging symfony-1.4

我正在研究Symfony 1.4中的REST API

我想记录进出我的“api”应用程序的所有内容。在log / api文件夹中,我将跟踪各种文件中的api调用。要调用myModule / myAction,我将有三个文件:

    所有请求的
  • myModule_myAction_RQ.log
  • 所有回复的
  • myModule_myAction_RS.log
  • 所有错误回复的
  • myModule_myAction_error.log

我知道如何手动执行此操作,在每个操作的开头和结尾添加一些代码。我是这样的:

class myActions extends sfActions
{   
/**
 * log function
 */
private static function customLog($message, $seed, $url, $content, $type)
{
    $file =  sprintf('%s/%s_%s.log', sfConfig::get('sf_log_dir', "no_log_dir")."/api", $message, $type);
    $logger = new sfFileLogger(
                new sfEventDispatcher(), 
                array('file'=> $file)
            );

    $logger->log( sprintf("#%s# (%s) %s ", $seed, $url, $content),
                    0, 
                    "info"
    );
}

/**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
    try {           
        $json_msg = $request->getContent();
        // LOG !!!
        $seed = rand();
        $current_uri = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        self::customLog("availability", $seed, $current_uri, $json_msg, 'RQ');

                    // Do some API logic to set $response_msg
                    // ...

                    $this->response_msg = $response_msg;

        // LOG !!!
        self::customLog("myModule_index", $seed, $current_uri, $response_msg, 'RS');

    }
    catch(Exception $e)
    {
        // throw $e;
        $this->setTemplate("error");
        $this->error = $e;

        // LOG !!!
        self::customLog("myModule_index", $seed, $current_uri, $e->getCode().":".$e->getMessage(), 'error');
    }

  }

以下是记录信息的一些示例:

 myModule_index_RQ.log:
 Apr 25 11:49:31 symfony [emerg] #958824120# (http://host.local/api_dev.php/users/1/index {"price_km":0.66,"reservation_type":3, "position":{"long":2.139015,"lat":41.37947}} 
 Apr 25 11:56:27 symfony [emerg] #512729287# (http://host.local/api_dev.php/users/1/index {"price_km":0.66,"reservation_type":3,"position":{"long":2.161576,"lat":41.396896}}

myModule_index_RS.log:
Apr 25 11:49:32 symfony [emerg] #958824120# (http://host.local/api_dev.php/users/1/index) {"id_availability":539,"alternatives":[{"id_alternative":1,"duration":9,"reservation_type":3,"distance":3.5,"price":1.62,"original_price":2.31}]} 
Apr 25 11:56:27 symfony [emerg] #512729287# (http://host.local/api_dev.php/users/1/index) {"id_availability":540} 

myModule_index_error.log:
 Apr 25 11:38:20 symfony [emerg] #1059359810# (http://host.local/api_dev.php/users/1/index) 4205:Position to out of service area 

现在这很快就会变得单调乏味......

据我所知,通过对Symfony内部的充分了解,我可以很好地实现这一目标(DRYly)。所以这里有我的问题:

  • 事件可能是完成任务的方法。我对吗 ?如果是这样,我应该使用哪些事件?我怎么把它放在一起?
  • 使用$ request-> getContent(),我可以获取发送给我的邮件内容。如何获取我的回复内容? (因为我的观点的内容只有在我的行动结束后才知道,这不是“可以像往常一样”完成的事情。)。
  • 那么,过滤器可能是实现所有这些日志功能的方法吗?
  • 也许这个问题太标准了,我可以在一些配置文件中设置它?这很傻吗?或者某些模块可能就是这么做的?

这个级别的Symfony内部对我来说还是一个新手,所以任何提示,代码......都会非常受欢迎!

1 个答案:

答案 0 :(得分:1)

好吧,似乎过滤器就是这样做的... 首先,我在应用程序的lib文件夹中建立了一个过滤器类:

<?php
class LogFilter extends sfFilter{

 public function execute($filterChain){

      $request = $this->context->getRequest();
      $response = $this->context->getResponse();

      $seed = rand();
      $this->customLog($seed, $request->getContent(), 'RQ');

      $filterChain->execute($filterChain);    

      $this->customLog($seed, $response->getContent(), 'RS');
  }


/**
 * just log
 *  @param integer $seed: a random number that will be identical across request and response.
 *  @param string $content: the content of the message to be logged
 *  @param type: the type of the message (RQ = request, RS = response)
 */
private function customLog($seed, $content, $type)
{
    // get the current action information
    $moduleName = $this->context->getModuleName();
    $actionName = $this->context->getActionName();
    $message = $moduleName."-".$actionName;
    $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

    $file =  sprintf('%s/%s-%s.log', sfConfig::get('sf_log_dir', "no_log_dir")."/api-in", $message, $type);
    $logger = new sfFileLogger(
                new sfEventDispatcher(), 
                array('file'=> $file)
            );

    $logger->log( sprintf("#%s# (%s) %s ", $seed, $url, $content),
                    0, 
                    "info"
    );
}

}

在filters.yml配置文件(在app config文件夹中),安全性和缓存之间注册过滤器:

rendering: ~
security:  ~

# insert your own filters here
MyCustomFilter:  
  class: LogFilter

cache:     ~
execution: ~

而且......就是这样!