-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
/
m141106_185632_log_init.php
95 lines (84 loc) · 2.94 KB
/
m141106_185632_log_init.php
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
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
use yii\base\InvalidConfigException;
use yii\db\Migration;
use yii\log\DbTarget;
/**
* Initializes log table.
*
* The indexes declared are not required. They are mainly used to improve the performance
* of some queries about message levels and categories. Depending on your actual needs, you may
* want to create additional indexes (e.g. index on `log_time`).
*
* @author Alexander Makarov <sam@rmcreative.ru>
* @since 2.0.1
*/
class m141106_185632_log_init extends Migration
{
/**
* @var DbTarget[] Targets to create log table for
*/
private $dbTargets = [];
/**
* @throws InvalidConfigException
* @return DbTarget[]
*/
protected function getDbTargets()
{
if ($this->dbTargets === []) {
$log = Yii::$app->getLog();
$usedTargets = [];
foreach ($log->targets as $target) {
if ($target instanceof DbTarget) {
$currentTarget = [
$target->db,
$target->logTable,
];
if (!in_array($currentTarget, $usedTargets, true)) {
// do not create same table twice
$usedTargets[] = $currentTarget;
$this->dbTargets[] = $target;
}
}
}
if ($this->dbTargets === []) {
throw new InvalidConfigException('You should configure "log" component to use one or more database targets before executing this migration.');
}
}
return $this->dbTargets;
}
public function up()
{
$targets = $this->getDbTargets();
foreach ($targets as $target) {
$this->db = $target->db;
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable($target->logTable, [
'id' => $this->bigPrimaryKey(),
'level' => $this->integer(),
'category' => $this->string(),
'log_time' => $this->double(),
'prefix' => $this->text(),
'message' => $this->text(),
], $tableOptions);
$this->createIndex('idx_log_level', $target->logTable, 'level');
$this->createIndex('idx_log_category', $target->logTable, 'category');
}
}
public function down()
{
$targets = $this->getDbTargets();
foreach ($targets as $target) {
$this->db = $target->db;
$this->dropTable($target->logTable);
}
}
}