1
|
|
|
<?php |
2
|
|
|
namespace Bankiru\MonologLogstash; |
3
|
|
|
|
4
|
|
|
use Ekho\Logstash\Lumberjack; |
5
|
|
|
use Monolog\Handler\AbstractProcessingHandler; |
6
|
|
|
|
7
|
|
|
class LumberjackHandler extends AbstractProcessingHandler |
8
|
|
|
{ |
9
|
|
|
const DEFAULT_WINDOW_SIZE = 5000; |
10
|
|
|
|
11
|
|
|
/** @var Lumberjack\Client */ |
12
|
|
|
private $client; |
13
|
|
|
|
14
|
|
|
private $enabled = true; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param string $host IP or hostname |
18
|
|
|
* @param int $port Port where Logstash listen connections with input lumberjack |
19
|
|
|
* @param string $cafile path to certificate file |
20
|
|
|
* @param array $options various lumberjack options (@see Lumberjack\Client) |
21
|
|
|
* @return LumberjackHandler |
22
|
|
|
*/ |
23
|
|
|
public function init($host, $port, $cafile, array $options = array()) |
24
|
|
|
{ |
25
|
|
|
$windowSize = self::DEFAULT_WINDOW_SIZE; |
26
|
|
|
|
27
|
|
|
if (array_key_exists('window_size', $options)) { |
28
|
|
|
$windowSize = $options['window_size'] ?: self::DEFAULT_WINDOW_SIZE; |
29
|
|
|
unset($options['window_size']); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
try { |
33
|
|
|
$this->client = new Lumberjack\Client( |
34
|
|
|
new Lumberjack\SecureSocket( |
35
|
|
|
$host, |
36
|
|
|
$port, |
37
|
|
|
array('ssl_cafile' => $cafile) + $options |
38
|
|
|
), |
39
|
|
|
new Lumberjack\Encoder(), |
40
|
|
|
$windowSize |
41
|
|
|
); |
42
|
|
|
} catch (Lumberjack\Exception $ex) { |
43
|
|
|
$this->enabled = false; |
44
|
|
|
error_log($ex->getMessage()); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return $this; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @return Lumberjack\Client |
52
|
|
|
*/ |
53
|
|
|
public function getClient() |
54
|
|
|
{ |
55
|
|
|
return $this->client; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param Lumberjack\Client $client |
60
|
|
|
* @return LumberjackHandler |
61
|
|
|
*/ |
62
|
|
|
public function setClient(Lumberjack\Client $client) |
63
|
|
|
{ |
64
|
|
|
$this->client = $client; |
65
|
|
|
return $this; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* {@inheritdoc} |
70
|
|
|
*/ |
71
|
|
|
public function isHandling(array $record) |
72
|
|
|
{ |
73
|
|
|
return $this->enabled && parent::isHandling($record); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* {@inheritdoc} |
78
|
|
|
* @throws \RuntimeException |
79
|
|
|
*/ |
80
|
|
|
protected function write(array $record) |
81
|
|
|
{ |
82
|
|
|
if (isset($record['formatted']) && is_array($record['formatted'])) { |
83
|
|
|
$record = $record['formatted']; |
84
|
|
|
} else { |
85
|
|
|
unset($record['formatted']); |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
try { |
89
|
|
|
$this->client->write($record); |
90
|
|
|
} catch (Lumberjack\Exception $ex) { |
91
|
|
|
$this->enabled = false; |
92
|
|
|
error_log($ex->getMessage()); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|