Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 017cacb

Browse files
committed
[Monolog] Added ElasticsearchLogstashHandler
1 parent e3927b6 commit 017cacb

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
3+
namespace Symfony\Bridge\Monolog\Handler;
4+
5+
use Monolog\Formatter\FormatterInterface;
6+
use Monolog\Formatter\LogstashFormatter;
7+
use Monolog\Handler\AbstractProcessingHandler;
8+
use Monolog\Logger;
9+
use Symfony\Component\HttpClient\HttpClient;
10+
use Symfony\Contracts\HttpClient\HttpClientInterface;
11+
12+
/**
13+
* Push logs directly to Elasticsearch and format them according to Logstash specification
14+
*
15+
* @author Grégoire Pineau <[email protected]>
16+
*/
17+
class ElasticsearchLogstashHandler extends AbstractProcessingHandler
18+
{
19+
private $endpoint;
20+
private $index;
21+
private $client;
22+
private $responses;
23+
24+
public function __construct($endpoint = 'http://elasticsearch:9200', $index = 'monolog', HttpClientInterface $client = null, $level = Logger::DEBUG, $bubble = true)
25+
{
26+
if (!class_exists(HttpClientInterface::class)) {
27+
throw new \LogicException(sprintf('%s handler needs symfony/http-client, please run `composer require symfony/http-client`.', __CLASS__));
28+
}
29+
30+
parent::__construct($level, $bubble);
31+
$this->endpoint = $endpoint;
32+
$this->index = $index;
33+
$this->client = $client ?: HttpClient::create();
34+
$this->responses = new \SplObjectStorage();
35+
}
36+
37+
protected function write(array $record)
38+
{
39+
$this->sendToElasticsearch(array($record));
40+
}
41+
42+
protected function getDefaultFormatter()
43+
{
44+
return new LogstashFormatter('application', null, null, 'ctxt_', LogstashFormatter::V1);
45+
}
46+
47+
private function sendToElasticsearch(array $documents)
48+
{
49+
$body = '';
50+
foreach ($documents as $document) {
51+
$body .= json_encode([
52+
'index' => [
53+
'_index' => $this->index,
54+
'_type' => '_doc',
55+
],
56+
]);
57+
$body .= "\n";
58+
$body .= $document['formatted'];
59+
$body .= "\n";
60+
}
61+
62+
$response = $this->client->request('POST', $this->endpoint.'/_bulk', [
63+
'body' => $body,
64+
'headers' => [
65+
'Content-Type' => 'application/json',
66+
],
67+
]);
68+
69+
$this->responses->attach($response);
70+
71+
foreach ($this->client->stream($this->responses, 0) as $response => $chunk) {
72+
if (!$chunk->isTimeout() && $chunk->isFirst()) {
73+
$this->responses->detach($response);
74+
}
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)