服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - Yii使用DbTarget实现日志功能的示例代码

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

2021-10-20 13:28huaweichenai PHP教程

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

一:在配置文件的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

延伸 · 阅读

精彩推荐
  • PHP教程php readfile下载大文件失败的解决方法

    php readfile下载大文件失败的解决方法

    这篇文章主要介绍了php readfile下载大文件失败的解决方法,涉及php针对大文件的分割及逐块下载操作实现技巧,需要的朋友可以参考下...

    陈小峰_iefreer5262021-05-20
  • PHP教程PHP的curl实现get,post和cookie(实例介绍)

    PHP的curl实现get,post和cookie(实例介绍)

    本篇文章是对PHP的curl实现get,post和cookie的方法进行了详细的分析介绍,需要的朋友参考下 ...

    PHP教程网3922020-04-15
  • PHP教程PHP常用处理静态操作类

    PHP常用处理静态操作类

    本文给大家分享的是我们在php开发的时候经常需要用到的一些静态操作类,都是个人整理的,推荐给大家,有需要的小伙伴可以参考下。...

    PHP教程网2482020-09-17
  • PHP教程使用php伪造referer的方法 利用referer防止图片盗链

    使用php伪造referer的方法 利用referer防止图片盗链

    当浏览器向web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器籍此可以获得一些信息用于处理,不过这个Referer是...

    PHP教程网2532020-06-06
  • PHP教程thinkphp3.2实现跨控制器调用其他模块的方法

    thinkphp3.2实现跨控制器调用其他模块的方法

    这篇文章主要介绍了thinkphp3.2实现跨控制器调用其他模块的方法,结合实例形式分析了thinkPHP跨模块、跨控制器调用方法的常见操作技巧,需要的朋友可以参考...

    chinalorin4182021-04-30
  • PHP教程php PDO判断连接是否可用的实现方法

    php PDO判断连接是否可用的实现方法

    下面小编就为大家带来一篇php PDO判断连接是否可用的实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    jingxian12132021-05-07
  • PHP教程PHP将URL转换成短网址的算法分享

    PHP将URL转换成短网址的算法分享

    短网址(Short URL)顾名思义就是在形式上比较短的网址。在Web 2.0的今天,不得不说这是一个潮流。目前已经有许多类似服务,借助短网址您可以用简短的网...

    PHP教程网10712021-02-28
  • PHP教程php实现的操作excel类详解

    php实现的操作excel类详解

    这篇文章主要介绍了php实现的操作excel类,较为详细的分析说明了PHP操作excel的具体技巧,包括PHP针对excel的创建、打开、读取、修改等,需要的朋友可以参考下...

    乘着风在飞2992020-12-16