Reputation: 2000
I want to log all HTTP requests to site, framework Yii.
Can i use standard capabilities of framework?
Upvotes: 3
Views: 3302
Reputation: 3640
In Yii2 the events are called beforeRequest
and afterRequest
(http://www.yiiframework.com/doc-2.0/guide-structure-applications.html)
For example:
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
});
But this is before response data has been prepared into response content (according to response format, eg. Response::FORMAT_JSON
) so if you want the true final response body you need to do this (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
});
Upvotes: 4
Reputation: 5955
We've done it using onBeginRequest
or onEndRequest
. See more info here: How to use events in Yii
In essence, you hook the global request event with a class of your own and then do whatever you want to do.
Upvotes: 4