欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-11-14 19:11:04
一:在配置文件的log组件中配置dbtarget'log' => [ 'tracelevel' => yii_debug ? 3 : 0, 'targets' => [ [...

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

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

'log' => [
 'tracelevel' => yii_debug ? 3 : 0,
 'targets' => [
  [
   'class' => 'yii\log\filetarget',
   'levels' => ['error', 'warning'],
  ],
  'test' => [
   'class' => 'yii\log\dbtarget',//datarget类
   'logtable' => '{{%test_log}}',//日志表
   'levels' => ['error', 'info', 'warning'],//日志等级
  ],
 ],
],

二:生成日志表

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

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

三:使用日志

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

yii::info()

四:自定义dbtarget日志

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

(1)在项目目录下执行

php yii migrate/create create_test_log

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

<?php
use yii\db\migration;
/**
 * class m200720_091126_create_test_log
 */
class m200720_091126_create_test_log extends migration
{
 /**
  * {@inheritdoc}
  */
 public function safeup()
 {
  $this->createtable('{{%test_log}}', [
   'id' => $this->bigprimarykey(),
   'level' => $this->integer()->notnull()->comment('日志等级'),
   'category' => $this->string(100)->notnull()->comment('分类名称'),
   'prefix' => $this->text(),
   'route' => $this->string(100)->notnull()->comment('路由'),
   'method' => $this->string(20)->notnull()->comment('请求方式'),
   'app' => $this->string(20)->comment('请求应用'),
   'module' => $this->string(20)->comment('请求模块'),
   'request' => $this->text()->comment('请求参数'),
   'status' => $this->string(10)->notnull()->comment('状态码'),
   'message' => $this->text()->comment('日志内容'),
   'request_at' => $this->double()->notnull()->comment('请求时间'),
   'ip' => $this->string(63)->comment('请求ip'),
  ], 'character set utf8mb4 collate utf8mb4_unicode_ci engine=innodb comment=\'请求日志表\'');
  //增加索引
  $this->createindex('idx_log_level', '{{%test_log}}', 'level');
  $this->createindex('idx_log_category', '{{%test_log}}', 'category');
  $this->createindex('idx_log_route', '{{%test_log}}', 'route');
  $this->createindex('idx_log_method', '{{%test_log}}', 'method');
  $this->createindex('idx_log_status', '{{%test_log}}', 'status');
 }
 /**
  * @inheritdoc
  */
 public function safedown()
 {
  $this->droptable('{{%test_log}}');
 }
}

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

php yii migrate

2:编写一个dbtarget类来继承yiilogdbtarget类

<?php
namespace app\components;
use yii;
use yii\helpers\vardumper;
use yii\log\logruntimeexception;
use yii\web\httpexception;
use yii\web\request;
/**
 * dbtarget stores log messages in a database table.
 *
 * @see yii\log\dbtarget
 *
 * @author wangjian
 * @since 1.0
 */
class dbtarget extends \yii\log\dbtarget
{
 /**
  * @inheritdoc
  */
 public $categories = [
  'application',
  'yii\web\httpexception:*',
 ];
 /**
  * @inheritdoc
  */
 public $except = [
  // 'yii\web\httpexception:404',
 ];
 /**
  * @inheritdoc
  */
 public $logvars = ['_get', '_post'];
 /**
  * @var string 用户组件id
  */
 public $usercomponentid = 'user';
 /**
  * @inheritdoc
  */
 public function collect($messages, $final)
 {
  $this->messages = array_merge($this->messages, static::filtermessages($messages, $this->getlevels(), $this->categories, $this->except));
  $count = count($this->messages);
  if ($count > 0 && ($final || $this->exportinterval > 0 && $count >= $this->exportinterval)) {
   $oldexportinterval = $this->exportinterval;
   $this->exportinterval = 0;
   $this->export();
   $this->exportinterval = $oldexportinterval;
   $this->messages = [];
  }
 }
 /**
  * @inheritdoc
  */
 public function getmessageprefix($message)
 {
  if ($this->prefix !== null) {
   return call_user_func($this->prefix, $message);
  }
  if (yii::$app === null) {
   return '';
  }
  $ip = $this->getip();
  $ip = empty($ip) ? '-' : $ip;
  return "[$ip]";
 }
 /**
  * @inheritdoc
  */
 public function export()
 {
  if ($this->db->gettransaction()) {
   $this->db = clone $this->db;
  }
  $tablename = $this->db->quotetablename($this->logtable);
  $sql = "insert into $tablename ([[level]], [[category]], [[prefix]], [[route]], [[method]], [[app]], [[module]], [[request]], [[status]], [[message]], [[request_at]], [[ip]])
    values (:level, :category, :prefix, :route, :method, :app, :module, :request, :status, :message, :request_at, :ip)";
  $command = $this->db->createcommand($sql);
  $request = yii::$app->getrequest();
  list($route, $params) = $request->resolve();
  $method = $request->getmethod();
  $module = yii::$app->controller->module->id;
  $route = str_replace("{$module}/", '', $route);
  foreach ($this->messages as $message) {
   list($text, $level, $category, $timestamp) = $message;
   $statuscode = 200;
   if (!is_string($text)) {
    if ($text instanceof \throwable || $text instanceof \exception) {
     $statuscode = $text instanceof httpexception ? $text->statuscode : 500;
     $text = $text->getmessage();
    } else {
     $text = vardumper::export($text);
    }
   }
   if ($command->bindvalues([
     ':level' => $level,
     ':category' => $category,
     ':prefix' => $this->getmessageprefix($message),
     ':route' => $route,
     ':method' => $method,
     ':app' => yii::$app->id,
     ':module' => $module,
     ':request' => $this->getcontextmessage(),
     ':status' => $statuscode,
     ':message' => $text,
     ':request_at' => $timestamp,
     ':ip' => $this->getip(),
    ])->execute() > 0) {
    continue;
   }
   throw new logruntimeexception('unable to export log through database!');
  }
 }
 /**
  * 获取当前ip
  */
 protected function getip()
 {
  $request = yii::$app->getrequest();
  return $request instanceof request ? $request->getuserip() : '';
 }
}

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

'log' => [
 'tracelevel' => yii_debug ? 3 : 0,
 'targets' => [
  [
   'class' => 'yii\log\filetarget',
   'levels' => ['error', 'warning'],
  ],
  'test' => [
   'class' => 'app\components\dbtarget',
   'logtable' => '{{%test_log}}',
   'levels' => ['error', 'info', 'warning'],
  ],
 ],
],

4:使用dbtarget日志

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

到此这篇关于yii使用dbtarget实现日志功能的示例代码的文章就介绍到这了,更多相关yii dbtarget 日志内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!