ElasticsearchHandlerTest.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use Elasticsearch\ClientBuilder;
  12. use Monolog\Formatter\ElasticsearchFormatter;
  13. use Monolog\Formatter\NormalizerFormatter;
  14. use Monolog\Test\TestCase;
  15. use Monolog\Level;
  16. use Elasticsearch\Client;
  17. class ElasticsearchHandlerTest extends TestCase
  18. {
  19. /**
  20. * @var Client mock
  21. */
  22. protected $client;
  23. /**
  24. * @var array Default handler options
  25. */
  26. protected $options = [
  27. 'index' => 'my_index',
  28. 'type' => 'doc_type',
  29. ];
  30. public function setUp(): void
  31. {
  32. // Elasticsearch lib required
  33. if (!class_exists('Elasticsearch\Client')) {
  34. $this->markTestSkipped('elasticsearch/elasticsearch not installed');
  35. }
  36. // base mock Elasticsearch Client object
  37. $this->client = $this->getMockBuilder('Elasticsearch\Client')
  38. ->onlyMethods(['bulk'])
  39. ->disableOriginalConstructor()
  40. ->getMock();
  41. }
  42. /**
  43. * @covers Monolog\Handler\ElasticsearchHandler::write
  44. * @covers Monolog\Handler\ElasticsearchHandler::handleBatch
  45. * @covers Monolog\Handler\ElasticsearchHandler::bulkSend
  46. * @covers Monolog\Handler\ElasticsearchHandler::getDefaultFormatter
  47. */
  48. public function testHandle()
  49. {
  50. // log message
  51. $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
  52. // format expected result
  53. $formatter = new ElasticsearchFormatter($this->options['index'], $this->options['type']);
  54. $data = $formatter->format($msg);
  55. unset($data['_index'], $data['_type']);
  56. $expected = [
  57. 'body' => [
  58. [
  59. 'index' => [
  60. '_index' => $this->options['index'],
  61. '_type' => $this->options['type'],
  62. ],
  63. ],
  64. $data,
  65. ],
  66. ];
  67. // setup ES client mock
  68. $this->client->expects($this->any())
  69. ->method('bulk')
  70. ->with($expected);
  71. // perform tests
  72. $handler = new ElasticsearchHandler($this->client, $this->options);
  73. $handler->handle($msg);
  74. $handler->handleBatch([$msg]);
  75. }
  76. /**
  77. * @covers Monolog\Handler\ElasticsearchHandler::setFormatter
  78. */
  79. public function testSetFormatter()
  80. {
  81. $handler = new ElasticsearchHandler($this->client);
  82. $formatter = new ElasticsearchFormatter('index_new', 'type_new');
  83. $handler->setFormatter($formatter);
  84. $this->assertInstanceOf('Monolog\Formatter\ElasticsearchFormatter', $handler->getFormatter());
  85. $this->assertEquals('index_new', $handler->getFormatter()->getIndex());
  86. $this->assertEquals('type_new', $handler->getFormatter()->getType());
  87. }
  88. /**
  89. * @covers Monolog\Handler\ElasticsearchHandler::setFormatter
  90. */
  91. public function testSetFormatterInvalid()
  92. {
  93. $handler = new ElasticsearchHandler($this->client);
  94. $formatter = new NormalizerFormatter();
  95. $this->expectException(\InvalidArgumentException::class);
  96. $this->expectExceptionMessage('ElasticsearchHandler is only compatible with ElasticsearchFormatter');
  97. $handler->setFormatter($formatter);
  98. }
  99. /**
  100. * @covers Monolog\Handler\ElasticsearchHandler::__construct
  101. * @covers Monolog\Handler\ElasticsearchHandler::getOptions
  102. */
  103. public function testOptions()
  104. {
  105. $expected = [
  106. 'index' => $this->options['index'],
  107. 'type' => $this->options['type'],
  108. 'ignore_error' => false,
  109. ];
  110. $handler = new ElasticsearchHandler($this->client, $this->options);
  111. $this->assertEquals($expected, $handler->getOptions());
  112. }
  113. /**
  114. * @covers Monolog\Handler\ElasticsearchHandler::bulkSend
  115. * @dataProvider providerTestConnectionErrors
  116. */
  117. public function testConnectionErrors($ignore, $expectedError)
  118. {
  119. $hosts = [['host' => '127.0.0.1', 'port' => 1]];
  120. $client = ClientBuilder::create()
  121. ->setHosts($hosts)
  122. ->build();
  123. $handlerOpts = ['ignore_error' => $ignore];
  124. $handler = new ElasticsearchHandler($client, $handlerOpts);
  125. if ($expectedError) {
  126. $this->expectException($expectedError[0]);
  127. $this->expectExceptionMessage($expectedError[1]);
  128. $handler->handle($this->getRecord());
  129. } else {
  130. $this->assertFalse($handler->handle($this->getRecord()));
  131. }
  132. }
  133. /**
  134. * @return array
  135. */
  136. public function providerTestConnectionErrors()
  137. {
  138. return [
  139. [false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
  140. [true, false],
  141. ];
  142. }
  143. /**
  144. * Integration test using localhost Elasticsearch server
  145. *
  146. * @covers Monolog\Handler\ElasticsearchHandler::__construct
  147. * @covers Monolog\Handler\ElasticsearchHandler::handleBatch
  148. * @covers Monolog\Handler\ElasticsearchHandler::bulkSend
  149. * @covers Monolog\Handler\ElasticsearchHandler::getDefaultFormatter
  150. */
  151. public function testHandleIntegration()
  152. {
  153. $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
  154. $expected = $msg->toArray();
  155. $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
  156. $expected['context'] = [
  157. 'class' => ["stdClass" => []],
  158. 'foo' => 7,
  159. 0 => 'bar',
  160. ];
  161. $hosts = [['host' => '127.0.0.1', 'port' => 9200]];
  162. $client = ClientBuilder::create()
  163. ->setHosts($hosts)
  164. ->build();
  165. $handler = new ElasticsearchHandler($client, $this->options);
  166. try {
  167. $handler->handleBatch([$msg]);
  168. } catch (\RuntimeException $e) {
  169. $this->markTestSkipped('Cannot connect to Elasticsearch server on localhost');
  170. }
  171. // check document id from ES server response
  172. $documentId = $this->getCreatedDocId($client->transport->getLastConnection()->getLastRequestInfo());
  173. $this->assertNotEmpty($documentId, 'No elastic document id received');
  174. // retrieve document source from ES and validate
  175. $document = $this->getDocSourceFromElastic(
  176. $client,
  177. $this->options['index'],
  178. $this->options['type'],
  179. $documentId
  180. );
  181. $this->assertEquals($expected, $document);
  182. // remove test index from ES
  183. $client->indices()->delete(['index' => $this->options['index']]);
  184. }
  185. /**
  186. * Return last created document id from ES response
  187. *
  188. * @param array $info Elasticsearch last request info
  189. * @return string|null
  190. */
  191. protected function getCreatedDocId(array $info)
  192. {
  193. $data = json_decode($info['response']['body'], true);
  194. if (!empty($data['items'][0]['index']['_id'])) {
  195. return $data['items'][0]['index']['_id'];
  196. }
  197. }
  198. /**
  199. * Retrieve document by id from Elasticsearch
  200. *
  201. * @param Client $client Elasticsearch client
  202. * @param string $index
  203. * @param string $type
  204. * @param string $documentId
  205. * @return array
  206. */
  207. protected function getDocSourceFromElastic(Client $client, $index, $type, $documentId)
  208. {
  209. $params = [
  210. 'index' => $index,
  211. 'type' => $type,
  212. 'id' => $documentId,
  213. ];
  214. $data = $client->get($params);
  215. if (!empty($data['_source'])) {
  216. return $data['_source'];
  217. }
  218. return [];
  219. }
  220. }