YII是提供修改输出参数格式的,但是可供用户定制化的空间非常小。
如想把prefix中的userID和ip分别插入到数据库中不同的两列,就需要需改框架文件:
/basic/vendor/yiisoft/yii2/log/Target与/basic/vendor/yiisoft/yii2/log/DbTarget如下:
9 public function getMessagePrefixCustomized($message) 10 { 11 if ($this->prefix !== null) { 12 return call_user_func($this->prefix, $message); 13 } 14 15 if (Yii::$app === null) { 16 return ''; 17 } 18 19 $request = Yii::$app->getRequest(); 20 $ip = $request instanceof Request ? $request->getUserIP() : '-'; 21 22 /* @var $user yiiwebUser */ 23 $user = Yii::$app->has('user', true) ? Yii::$app->get('user') : null; 24 if ($user && ($identity = $user->getIdentity(false))) { 25 $userID = $identity->getId(); 26 } else { 27 $userID = '-'; 28 } 29 30 /* @var $session yiiwebSession */ 31 $session = Yii::$app->has('session', true) ? Yii::$app->get('session') : null; 32 $sessionID = $session && $session->getIsActive() ? $session->getId() : '-'; 33 34 $results = array('ip' => $ip, 'userID' => $userID, 'sessionID' => $sessionID);
//return "[$ip][$userID][$sessionID]"; 35 return $results;//原来是返回一个string这里返回一个数组 36 }
1 public function export() 2 { 3 $tableName = $this->db->quoteTableName($this->logTable); 4 $sql = "INSERT INTO $tableName ([[level]], [[category]], [[log_time]], [[message]], [[IP]], [[customerID]]) 5 VALUES (:level, :category, :log_time, :message, :IP, :customerID)";//在这里修改在数据库中要显示的字段 6 $command = $this->db->createCommand($sql); 7 foreach ($this->messages as $message) { 8 list($text, $level, $category, $timestamp) = $message; 9 if (!is_string($text)) { 10 $text = VarDumper::export($text); 11 } 12 $command->bindValues([ 13 ':level' => $level, 14 ':category' => $category, 15 ':log_time' => date('Y-m-d H:i:s'),//如需修改时间戳格式在这里修改 16 ':customerID' => $this->getMessagePrefixCustomized($message)['userID'],//从上边的函数里边的返回值 17 ':IP' => $this->getMessagePrefixCustomized($message)['ip'], 18 ':message' => $text, 19 ])->execute(); 20 } 21 }