Yii2 添加请求日志

#SQL
CREATE TABLE `log` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `action` varchar(50) NOT NULL DEFAULT '' COMMENT 'action',
  `url` varchar(500) DEFAULT NULL COMMENT 'url',
  `params` text COMMENT 'POST参数',
  `usetime` float(11,8) DEFAULT NULL COMMENT '耗时秒,action处理错误,此值为0',
  `return` text COMMENT '返回值,action处理错误,此值为空',
  `create_time` int(11) DEFAULT NULL COMMENT '添加时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COMMENT='访问日志';
public function beforeAction($action) {
        $data = [
            'params' => json_encode($this->params, 1),
            'url' => Yii::$app->request->url,
            'action' => $action->id,
            'create_time' => time(),
        ];
        
        $this->usetime = microtime(1);
        
        Yii::$app->db->createCommand()->insert('log', $data)->execute();
        $id = Yii::$app->db->getLastInsertID();
        $this->logid = $id;
        
        return parent::beforeAction($action);
    }
    
    public function afterAction($action, $result) {
        if($this->logid){
            $data = [
                'usetime' => round(microtime(1) - $this->usetime, 3),
                'return' => json_encode($result, 1)
            ];
            
            Yii::$app->db->createCommand()->update('log', $data, ['id'=>$this->logid])->execute();
        }
        return parent::afterAction($action, $result);
    }

此条目发表在yii2, 框架分类目录。将固定链接加入收藏夹。