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

时间:2022-12-05 09:46:40

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
'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'],//日志等级
  ],
 ],
],

二:生成日志表

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

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

三:使用日志

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

?
1
yii::info()

四:自定义dbtarget日志

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

(1)在项目目录下执行

?
1
php yii migrate/create create_test_log

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?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日志表

?
1
php yii migrate

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
<?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类改成我们自定义的类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
'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 日志内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://segmentfault.com/a/1190000023313633