Log the URLs users visited in Yii 2

In this example we will use Yii 2 behavior to log the URLs user have visited on our Yii 2 powered application.
Lets get started.

1.Create a behavior folder in the commons directory,then create LogactionBehavior class.

<?php
namespace common\behaviors;

use Yii;
use yii\web\Controller;
use yii\base\Behavior;
use yii\web\Request;

class LogactionBehavior extends Behavior
{
    /**
     * 
     * @var yii\web\Request
     */
    private $request;

    /**
     * Use dependency injection to inject yii\web\Request
     * @param array $config
     * @param yii\web\Request  $request
     */
    public function __construct($config =[],Request $request)
    {
        parent::__construct($config);
        $this->request = $request;
    }

    /**
     * Activation of events
     * Register beforeAction to  Controller::EVENT_BEFORE_ACTION 
     * Register afterAction to Controller::EVENT_AFTER_ACTION 
     * @return array
     */
    public function events()
    {
        return [
            Controller::EVENT_BEFORE_ACTION => 'beforeAction',
            Controller::EVENT_AFTER_ACTION => 'afterAction'
        ];
    }

    /**
     * log
     */
    public function beforeAction()
    {
        $date =date("Y/m/d h:i:sa");
        $url = $this->request->url;
        $ip = $this->request->userIP;
        $params = $this->request->getRawBody();
        $log = $date."   ".$url."  ".$params."   ".$ip;
        Yii::info($log);
        Yii::beginProfile('myBenchmark');//log user activty to´╝îmyBenchmark---change modify the name
    }

    public function afterAction()
    {
        Yii::endProfile('myBenchmark');//end analysis
    }
}

 

2 Controller behavior

public function behaviors()
{
    return [
        LogactionBehavior::className(),
    ];

 

3 Add to application configuration

'log'=>[
    'targets' => [
        [
            'class'=> 'yii\log\FileTarget',
            'levels' => ['info','profile'],
            'logVars' => [],
        ]

    ]
]

 

Get Yii RESTful guide

Leave a Reply

Your email address will not be published. Required fields are marked *