首页 > 解决方案 > Yii2 save 登录数据库

问题描述

我对使用 Yii2 的日志有一些问题。我以这种方式设置日志目标:

'log' => [
    'traceLevel' => YII_DEBUG ? 3 : 0,
    'flushInterval' => 1,//test
    'targets' => [
        [
          'class' => 'common\components\SaDbTarget',
          'levels' => ['error', 'warning','trace','info'],
          'exportInterval' => 1,//test
          //'categories' => ['application'],
          /*'except' => [
                'yii\db\*',
            ],*/
         ],
       ],
  ],

我创建了扩展 DbTarget 类的 SaDbTarget,这工作正常,因为我在表中找到了一些日志。之后,在控制器中,我尝试像这样设置日志

public function actionIndex(){
    $searchModel = new CategorySearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    Yii::trace('trace log', __METHOD__);
    Yii::warning('warning log');
    // here is the rest of the code
}

我可以在调试工具栏中看到这 2 个日志,但在我的数据库表中看不到。根据文档

要使每条日志消息立即出现在日志目标中,您应该将 flushInterval 和 exportInterval 都设置为 1

我试图设置这个值,但仍然不起作用。

我不知道我做错了什么。

更新这是我的 SaDbTarget

namespace common\components;

use Yii;
use yii\log\DbTarget;
use yii\log\Logger;

class SaDbTarget extends DbTarget{ 

    //set custom table db for saving log
    public $logTable = 'authlog';

    //overwrite export();
    public function export(){

        $tableName = $this->db->quoteTableName($this->logTable);
        $sql = "INSERT INTO $tableName ([[authlog_login]], [[authlog_ip]], [[authlog_area]], [[authlog_act]], [[authlog_time]], [[authlog_data]])
            VALUES (:login, :ip, :area, :act, :time, :data )";

        $command = $this->db->createCommand($sql);

        //Get username
        $user=Yii::$app->user->getId();

        //Get user ip address
        $ip = Yii::$app->request->getUserIP();

        //Get area/controller
        $controller=Yii::$app->controller->uniqueId;

        //Get action
        $event= Yii::$app->controller->module->requestedAction->id;

        //Set timezone
        $time =  Yii::$app->formatter->asDate('now', 'php:Y-m-d H:i:s'); 

        //Set Data
        $data = $this->messages[0];

        $command->bindValues([
            ':login' => $user,
            ':ip' => $ip,
            ':area' => $controller,        
            ':act' => $event,
            ':time' => $time,
            ':data' => $data,
        ])->execute();
    }

标签: yii2yii2-advanced-app

解决方案


推荐阅读