Hi,
How I do it atm:
I’m currently logging every user action in a BaseController’s afterAction()
.
Looks like this:
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
UserAction::add( Yii::$app->user->id, $action, Yii::$app->controller->actionParams );
return $result;
}
And the class UserAction holds a static function to just store the data in a table:
public static function add($userId, $action, $actionParams="", $access=""){
if( $action instanceof Action ){
$action = $action->getUniqueId();
}
if( is_array($actionParams) && !empty($actionParams) ){
//$actionParams['method'] = Yii::$app->request->method;
$actionParams = Json::encode($actionParams);
}else{
$actionParams = "";
}
//todo: check proper escaping
Yii::$app->db->createCommand()->insert( self::tableName(),
[
"user_id" => $userId,
"requested_action" => $action,
"requested_params" => $actionParams,
"access" => $access, //-1 denied, 1 granted
"requested_at" => time()
])->execute();
}
I’ve chosen this, because I thought, static function calls are cheaper then creating an UserAction object after every action.
Turns out, in this way structured, I can’t gather many information. For e.g.: identifying the request method POST, is never available there.
Also injecting additional data from other components, like, if access was granted or not gets complicated to implement.
Yii app by default has a log
component at application level. Currently thinking of adopting this and add an extra userlog
component with the logic in afterAction()
placed there.
What do you guys suggest?