当前位置:首页 > CMS教程 > 其它CMS > 列表

Yii使用DbTarget实现日志功能的示例代码

发布:smiling 来源: PHP粉丝网  添加日期:2022-03-19 14:35:26 浏览: 评论:0 

这篇文章主要介绍了Yii使用DbTarget实现日志功能的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。

一:在配置文件的log组件中配置DbTarget

Yii使用DbTarget实现日志功能的示例代码

  1. 'log' => [ 
  2.  'traceLevel' => YII_DEBUG ? 3 : 0, 
  3.  'targets' => [ 
  4.   [ 
  5.    'class' => 'yii\log\FileTarget', 
  6.    'levels' => ['error', 'warning'], 
  7.   ], 
  8.   'test' => [ 
  9.    'class' => 'yii\log\DbTarget',//DaTarget类 
  10.    'logTable' => '{{%test_log}}',//日志表 
  11.    'levels' => ['error', 'info', 'warning'],//日志等级 
  12.   ], 
  13.  ], 
  14. ], 

二:生成日志表

在项目目录下执行如下命令生成日志表

php yii migrate --migrationPath=@yii/log/migrations/

三:使用日志

在需要使用日志的地方使用

Yii::info()

四:自定义DbTarget日志

1:首先创建一个自定义的日志表

(1)在项目目录下执行

php yii migrate/create create_test_log

(2):在创建的migrate文件下编写创建数据库的迁移脚本

  1. <?php 
  2. use yii\db\Migration; 
  3. /** 
  4.  * Class m200720_091126_create_test_log 
  5.  */ 
  6. class m200720_091126_create_test_log extends Migration 
  7. { 
  8.  /** 
  9.   * {@inheritdoc} 
  10.   */ 
  11.  public function safeUp() 
  12.  { 
  13.   $this->createTable('{{%test_log}}', [ 
  14.    'id' => $this->bigPrimaryKey(), 
  15.    'level' => $this->integer()->notNull()->comment('日志等级'), 
  16.    'category' => $this->string(100)->notNull()->comment('分类名称'), 
  17.    'prefix' => $this->text(), 
  18.    'route' => $this->string(100)->notNull()->comment('路由'), 
  19.    'method' => $this->string(20)->notNull()->comment('请求方式'), 
  20.    'app' => $this->string(20)->comment('请求应用'), 
  21.    'module' => $this->string(20)->comment('请求模块'), 
  22.    'request' => $this->text()->comment('请求参数'), 
  23.    'status' => $this->string(10)->notNull()->comment('状态码'), 
  24.    'message' => $this->text()->comment('日志内容'), 
  25.    'request_at' => $this->double()->notNull()->comment('请求时间'), 
  26.    'ip' => $this->string(63)->comment('请求IP'), 
  27.   ], 'CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci ENGINE=InnoDB COMMENT=\'请求日志表\''); 
  28.   //增加索引 
  29.   $this->createIndex('idx_log_level', '{{%test_log}}', 'level'); 
  30.   $this->createIndex('idx_log_category', '{{%test_log}}', 'category'); 
  31.   $this->createIndex('idx_log_route', '{{%test_log}}', 'route'); 
  32.   $this->createIndex('idx_log_method', '{{%test_log}}', 'method'); 
  33.   $this->createIndex('idx_log_status', '{{%test_log}}', 'status'); 
  34.  } 
  35.  /** 
  36.   * @inheritdoc 
  37.   */ 
  38.  public function safeDown() 
  39.  { 
  40.   $this->dropTable('{{%test_log}}'); 
  41.  } 
  42. } 

(3):执行如下命令生成DbTarget日志表

php yii migrate

2:编写一个DbTarget类来继承yiilogDbTarget类

  1. <?php 
  2. namespace app\components; 
  3. use Yii; 
  4. use yii\helpers\VarDumper; 
  5. use yii\log\LogRuntimeException; 
  6. use yii\web\HttpException; 
  7. use yii\web\Request; 
  8. /** 
  9.  * DbTarget stores log messages in a database table. 
  10.  * 
  11.  * @see yii\log\DbTarget 
  12.  * 
  13.  * @author wangjian 
  14.  * @since 1.0 
  15.  */ 
  16. class DbTarget extends \yii\log\DbTarget 
  17. { 
  18.  /** 
  19.   * @inheritdoc 
  20.   */ 
  21.  public $categories = [ 
  22.   'application', 
  23.   'yii\web\HttpException:*', 
  24.  ]; 
  25.  /** 
  26.   * @inheritdoc 
  27.   */ 
  28.  public $except = [ 
  29.   // 'yii\web\HttpException:404', 
  30.  ]; 
  31.  /** 
  32.   * @inheritdoc 
  33.   */ 
  34.  public $logVars = ['_GET', '_POST']; 
  35.  /** 
  36.   * @var string 用户组件ID 
  37.   */ 
  38.  public $userComponentId = 'user'; 
  39.  /** 
  40.   * @inheritdoc 
  41.   */ 
  42.  public function collect($messages, $final) 
  43.  { 
  44.   $this->messages = array_merge($this->messages, static::filterMessages($messages, $this->getLevels(), $this->categories, $this->except)); 
  45.   $count = count($this->messages); 
  46.   if ($count > 0 && ($final || $this->exportInterval > 0 && $count >= $this->exportInterval)) { 
  47.    $oldExportInterval = $this->exportInterval; 
  48.    $this->exportInterval = 0; 
  49.    $this->export(); 
  50.    $this->exportInterval = $oldExportInterval; 
  51.    $this->messages = []; 
  52.   } 
  53.  } 
  54.  /** 
  55.   * @inheritdoc 
  56.   */ 
  57.  public function getMessagePrefix($message) 
  58.  { 
  59.   if ($this->prefix !== null) { 
  60.    return call_user_func($this->prefix, $message); 
  61.   } 
  62.   if (Yii::$app === null) { 
  63.    return ''; 
  64.   } 
  65.   $ip = $this->getIp(); 
  66.   $ip = emptyempty($ip) ? '-' : $ip; 
  67.   return "[$ip]"; 
  68.  } 
  69.  /** 
  70.   * @inheritdoc 
  71.   */ 
  72.  public function export() 
  73.  { 
  74.   if ($this->db->getTransaction()) { 
  75.    $this->db = clone $this->db; 
  76.   } 
  77.   $tableName = $this->db->quoteTableName($this->logTable); 
  78.   $sql = "INSERT INTO $tableName ([[level]], [[category]], [[prefix]], [[route]], [[method]], [[app]], [[module]], [[request]], [[status]], [[message]], [[request_at]], [[ip]]) 
  79.     VALUES (:level, :category, :prefix, :route, :method, :app, :module, :request, :status, :message, :request_at, :ip)"; 
  80.   $command = $this->db->createCommand($sql); 
  81.   $request = Yii::$app->getRequest(); 
  82.   list($route, $params) = $request->resolve(); 
  83.   $method = $request->getMethod(); 
  84.   $module = Yii::$app->controller->module->id; 
  85.   $route = str_replace("{$module}/", '', $route); 
  86.   foreach ($this->messages as $message) { 
  87.    list($text, $level, $category, $timestamp) = $message; 
  88.    $statusCode = 200; 
  89.    if (!is_string($text)) { 
  90.     if ($text instanceof \Throwable || $text instanceof \Exception) { 
  91.      $statusCode = $text instanceof HttpException ? $text->statusCode : 500; 
  92.      $text = $text->getMessage(); 
  93.     } else { 
  94.      $text = VarDumper::export($text); 
  95.     } 
  96.    } 
  97.    if ($command->bindValues([ 
  98.      ':level' => $level, 
  99.      ':category' => $category, 
  100.      ':prefix' => $this->getMessagePrefix($message), 
  101.      ':route' => $route, 
  102.      ':method' => $method, 
  103.      ':app' => Yii::$app->id, 
  104.      ':module' => $module, 
  105.      ':request' => $this->getContextMessage(), 
  106.      ':status' => $statusCode, 
  107.      ':message' => $text, 
  108.      ':request_at' => $timestamp, 
  109.      ':ip' => $this->getIp(), 
  110.     ])->execute() > 0) { 
  111.     continue; 
  112.    } 
  113.    throw new LogRuntimeException('Unable to export log through database!'); 
  114.   } 
  115.  } 
  116.  /** 
  117.   * 获取当前IP 
  118.   */ 
  119.  protected function getIp() 
  120.  { 
  121.   $request = Yii::$app->getRequest(); 
  122.   return $request instanceof Request ? $request->getUserIP() : ''; 
  123.  } 
  124. } 

3:在配置文件中将yiilogDbTarget类改成我们自定义的类

  1. 'log' => [ 
  2.  'traceLevel' => YII_DEBUG ? 3 : 0, 
  3.  'targets' => [ 
  4.   [ 
  5.    'class' => 'yii\log\FileTarget', 
  6.    'levels' => ['error', 'warning'], 
  7.   ], 
  8.   'test' => [ 
  9.    'class' => 'app\components\DbTarget', 
  10.    'logTable' => '{{%test_log}}', 
  11.    'levels' => ['error', 'info', 'warning'], 
  12.   ], 
  13.  ], 
  14. ], 

4:使用DbTarget日志

同样的使用Yii::info来记录日志

Tags: DbTarget Yii日志

分享到: