如何记录所有的HTTP请求网站,使用Yii框架


How to log all HTTP requests to site, using Yii Framework?

我想记录所有HTTP请求到站点,框架Yii.

我可以使用框架的标准功能吗?

我们已经用onBeginRequestonEndRequest完成了。在这里查看更多信息:如何在Yii中使用事件

本质上,你用你自己的类来钩住全局请求事件,然后做任何你想做的事情。

在yiii中,事件被称为beforeRequestafterRequest (http://www.yiiframework.com/doc-2.0/guide-structure-applications.html)

例如:

Yii::$app->on('afterRequest', function($event) {
    //do something...
    //response object is in $event->sender->response
    //response data is in $event->sender->response->data
    //request object is in $event->sender->request
});

但这是在响应数据被准备成响应内容(根据响应格式,例如:Response::FORMAT_JSON),所以如果你想要真正的最终响应体,你需要这样做(http://www.yiiframework.com/doc-2.0/guide-runtime-responses.html#sending-response):

Yii::$app->response->on('yii'web'Response::EVENT_AFTER_SEND, function($event) {  //alternatively use EVENT_AFTER_PREPARE
    //now you can access $event->sender->content and eg. $event->sender->getHeaders()
    //Also, you have access to the request through Yii::$app->request
});