-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGelfMessage.php
92 lines (79 loc) · 2.32 KB
/
GelfMessage.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
<?php
namespace welltime\graylog;
use Gelf\Message;
use Yii;
class GelfMessage extends Message
{
const LOGGER_ID_FIELD = 'LoggerId';
const USER_ID_FIELD = 'UserId';
const CATEGORY_FIELD = 'category';
public static function create()
{
return new self();
}
public function __construct()
{
parent::__construct();
$this->version = '1.1';
}
public function setSource($source)
{
if ($source) {
$this->host = $source;
}
return $this;
}
public function setCategory($category)
{
$this->setAdditional(self::CATEGORY_FIELD, $category);
return $this;
}
public function setLoggerId($loggerId = null)
{
$this->setAdditional(
self::LOGGER_ID_FIELD,
$loggerId !== null ? $loggerId : $this->getLoggerId()
);
return $this;
}
public function setUserId($userId = null)
{
if ($userId === null && Yii::$app instanceof \yii\web\Application && Yii::$app->user->getIdentity(false)) {
$userId = Yii::$app->user->getIdentity(false)->getId();
}
if ($userId) {
$this->setAdditional(self::USER_ID_FIELD, $userId);
}
return $this;
}
public function toArray()
{
$message = array(
'host' => $this->getHost(),
'short_message' => $this->getShortMessage(),
'full_message' => $this->getFullMessage(),
'level' => $this->getSyslogLevel(),
'timestamp' => $this->getTimestamp(),
'_facility' => $this->getFacility(),
'_file' => $this->getFile(),
);
// add additionals
foreach ($this->additionals as $key => $value) {
$message["_" . $key] = $value;
}
// return after filtering false, null and empty strings
return array_filter($message, 'strlen');
}
private function getLoggerId()
{
static $loggerId;
if (!$loggerId) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$loggerId = '';
for ($i = 0; $i < 8; $i++) {
$loggerId .= $characters[rand(0, strlen($characters) - 1)];
}
}
return $loggerId;
}
}