Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2: How to log controller and action id for each request?

I am trying to log every controller's actions by same code:

public function afterAction($action, $result)
{
    \Yii::$app->logger->write(0, $action->controller->id, $action->id);
    return parent::afterAction($action, $result);
}

But, I don't want redeclare this method on every controller, and I don't want to use some BaseController with same method. I know, base/Controller has AfterAction Event, but how to log controller actions, using his event handler ?

like image 357
Max Maximov Avatar asked Nov 04 '25 02:11

Max Maximov


1 Answers

You can create a Class-Level Event Handler in the boostrap process like this (most likely in the web.php configuration file, which holds the configuration for the application object):

use yii\base\ActionEvent;
use yii\base\Controller;
use yii\base\Event;

$config = [
    ...
    'bootstrap'    => [
        ...
        function () {
            Event::on(Controller::class, Controller::EVENT_AFTER_ACTION, function (ActionEvent $event) {
                Yii::info('Called controller/action: ' . $event->action->id . '/' . $event->action->controller->id);
            });
        },
        ...
    ],
    ...
];
like image 98
robsch Avatar answered Nov 06 '25 17:11

robsch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!