|
1
|
|
|
<?php |
|
2
|
|
|
namespace RazonYang\Yii2\Log\Db; |
|
3
|
|
|
|
|
4
|
|
|
use yii\helpers\VarDumper; |
|
5
|
|
|
use yii\log\DbTarget as BaseTarget; |
|
6
|
|
|
use yii\log\LogRuntimeException; |
|
7
|
|
|
use Yii; |
|
8
|
|
|
|
|
9
|
|
|
class Target extends BaseTarget |
|
10
|
|
|
{ |
|
11
|
2 |
|
public function export() |
|
12
|
|
|
{ |
|
13
|
2 |
|
if ($this->db->getTransaction()) { |
|
14
|
|
|
// create new database connection, if there is an open transaction |
|
15
|
|
|
// to ensure insert statement is not affected by a rollback |
|
16
|
|
|
$this->db = clone $this->db; |
|
17
|
|
|
} |
|
18
|
|
|
|
|
19
|
2 |
|
$tableName = $this->db->quoteTableName($this->logTable); |
|
20
|
2 |
|
$sql = "INSERT INTO $tableName ([[request_id]], [[level]], [[category]], [[log_time]], [[prefix]], [[message]]) |
|
21
|
|
|
VALUES (:request_id, :level, :category, :log_time, :prefix, :message)"; |
|
22
|
2 |
|
$command = $this->db->createCommand($sql); |
|
23
|
2 |
|
foreach ($this->messages as $message) { |
|
24
|
2 |
|
list($text, $level, $category, $timestamp) = $message; |
|
25
|
2 |
|
if (!is_string($text)) { |
|
26
|
|
|
// exceptions may not be serializable if in the call stack somewhere is a Closure |
|
27
|
|
|
if ($text instanceof \Throwable || $text instanceof \Exception) { |
|
28
|
|
|
$text = (string) $text; |
|
29
|
|
|
} else { |
|
30
|
|
|
$text = VarDumper::export($text); |
|
31
|
|
|
} |
|
32
|
|
|
} |
|
33
|
2 |
|
if ($command->bindValues([ |
|
34
|
2 |
|
':request_id' => $this->getRequestId(), |
|
35
|
2 |
|
':level' => $level, |
|
36
|
2 |
|
':category' => $category, |
|
37
|
2 |
|
':log_time' => $timestamp, |
|
38
|
2 |
|
':prefix' => $this->getMessagePrefix($message), |
|
39
|
2 |
|
':message' => $text, |
|
40
|
2 |
|
])->execute() > 0) { |
|
41
|
|
|
continue; |
|
42
|
|
|
} |
|
43
|
|
|
throw new LogRuntimeException('Unable to export log through database!'); |
|
44
|
|
|
} |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
protected $requestId; |
|
48
|
|
|
|
|
49
|
3 |
|
protected function getRequestId(): string |
|
50
|
|
|
{ |
|
51
|
3 |
|
if ($this->requestId === null) { |
|
52
|
3 |
|
$this->requestId = dechex($_SERVER['REQUEST_TIME_FLOAT'] * 1000000); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
3 |
|
return $this->requestId; |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|