Home > Software engineering >  Logging session destroy in Yii2
Logging session destroy in Yii2

Time:04-29

I am troubleshooting a problem in Yii2 where users are spontaneously/randomly logged out and returned to the login view. I want to insert some temporary Yii::info logging into the code where sessions are terminated for any reason other than the user logged out as normal. For example, if the user's session cookie is set, but its corresponding file in the session => savePath directory is missing, the session will terminate and I want to log that this occurred.

At first, I tried logging this in the yii\filters\AccessControl::beforeAction method right before the denyCallback is called, but this logged every time a guest user hit the login page (before login). I'm looking for a more appropriate place to place this logging behavior.

CodePudding user response:

I got the logging behavior I desired by adding the following to my web.php config.

$config = [
    //...
    'as beforeRequest' => [
        //...
        'denyCallback' => function () {
            if (Yii::$app->request->isAjax === false)
            {
                // If the user gets punted back to the login screen, log this event
                Yii::info('User redirected to login', __METHOD__);
            }
            return Yii::$app->response->redirect(['site/login']);
        },
    ],
    //...
];
  • Related