ElasticsearchHandlerTest.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 Monolog\Formatter\ElasticsearchFormatter;
  12. use Monolog\Formatter\NormalizerFormatter;
  13. use Monolog\Level;
  14. use Elasticsearch\Client;
  15. use Elastic\Elasticsearch\Client as Client8;
  16. use Elasticsearch\ClientBuilder;
  17. use Elastic\Elasticsearch\ClientBuilder as ClientBuilder8;
  18. use PHPUnit\Framework\Attributes\CoversClass;
  19. use PHPUnit\Framework\Attributes\DataProvider;
  20. use PHPUnit\Framework\Attributes\Group;
  21. #[Group('Elasticsearch')]
  22. #[CoversClass(ElasticsearchHandler::class)]
  23. class ElasticsearchHandlerTest extends \Monolog\Test\MonologTestCase
  24. {
  25. protected Client|Client8 $client;
  26. /**
  27. * @var array Default handler options
  28. */
  29. protected array $options = [
  30. 'index' => 'my_index',
  31. 'type' => 'doc_type',
  32. 'op_type' => 'index',
  33. ];
  34. public function setUp(): void
  35. {
  36. $hosts = ['http://elastic:changeme@127.0.0.1:9200'];
  37. $this->client = $this->getClientBuilder()
  38. ->setHosts($hosts)
  39. ->build();
  40. try {
  41. $this->client->info();
  42. } catch (\Throwable $e) {
  43. $this->markTestSkipped('Could not connect to Elasticsearch on 127.0.0.1:9200');
  44. }
  45. }
  46. public function tearDown(): void
  47. {
  48. parent::tearDown();
  49. unset($this->client);
  50. }
  51. public function testSetFormatter()
  52. {
  53. $handler = new ElasticsearchHandler($this->client);
  54. $formatter = new ElasticsearchFormatter('index_new', 'type_new');
  55. $handler->setFormatter($formatter);
  56. $this->assertInstanceOf('Monolog\Formatter\ElasticsearchFormatter', $handler->getFormatter());
  57. $this->assertEquals('index_new', $handler->getFormatter()->getIndex());
  58. $this->assertEquals('type_new', $handler->getFormatter()->getType());
  59. }
  60. public function testSetFormatterInvalid()
  61. {
  62. $handler = new ElasticsearchHandler($this->client);
  63. $formatter = new NormalizerFormatter();
  64. $this->expectException(\InvalidArgumentException::class);
  65. $this->expectExceptionMessage('ElasticsearchHandler is only compatible with ElasticsearchFormatter');
  66. $handler->setFormatter($formatter);
  67. }
  68. public function testOptions()
  69. {
  70. $expected = [
  71. 'index' => $this->options['index'],
  72. 'type' => $this->options['type'],
  73. 'ignore_error' => false,
  74. 'op_type' => $this->options['op_type'],
  75. ];
  76. if ($this->client instanceof Client8 || $this->client::VERSION[0] === '7') {
  77. $expected['type'] = '_doc';
  78. }
  79. $handler = new ElasticsearchHandler($this->client, $this->options);
  80. $this->assertEquals($expected, $handler->getOptions());
  81. }
  82. #[DataProvider('providerTestConnectionErrors')]
  83. public function testConnectionErrors($ignore, $expectedError)
  84. {
  85. $hosts = ['http://127.0.0.1:1'];
  86. $client = $this->getClientBuilder()
  87. ->setHosts($hosts)
  88. ->build();
  89. $handlerOpts = ['ignore_error' => $ignore];
  90. $handler = new ElasticsearchHandler($client, $handlerOpts);
  91. if ($expectedError) {
  92. $this->expectException($expectedError[0]);
  93. $this->expectExceptionMessage($expectedError[1]);
  94. $handler->handle($this->getRecord());
  95. } else {
  96. $this->assertFalse($handler->handle($this->getRecord()));
  97. }
  98. }
  99. public static function providerTestConnectionErrors(): array
  100. {
  101. return [
  102. [false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
  103. [true, false],
  104. ];
  105. }
  106. /**
  107. * Integration test using localhost Elasticsearch server
  108. *
  109. * @covers Monolog\Handler\ElasticsearchHandler::__construct
  110. * @covers Monolog\Handler\ElasticsearchHandler::handleBatch
  111. * @covers Monolog\Handler\ElasticsearchHandler::bulkSend
  112. * @covers Monolog\Handler\ElasticsearchHandler::getDefaultFormatter
  113. */
  114. public function testHandleBatchIntegration()
  115. {
  116. $msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
  117. $expected = $msg->toArray();
  118. $expected['datetime'] = $msg['datetime']->format(\DateTime::ATOM);
  119. $expected['context'] = [
  120. 'class' => ["stdClass" => []],
  121. 'foo' => 7,
  122. 0 => 'bar',
  123. ];
  124. $hosts = ['http://elastic:changeme@127.0.0.1:9200'];
  125. $client = $this->getClientBuilder()
  126. ->setHosts($hosts)
  127. ->build();
  128. $handler = new ElasticsearchHandler($client, $this->options);
  129. $handler->handleBatch([$msg]);
  130. // check document id from ES server response
  131. if ($client instanceof Client8) {
  132. $messageBody = $client->getTransport()->getLastResponse()->getBody();
  133. $info = json_decode((string) $messageBody, true);
  134. $this->assertNotNull($info, 'Decoding failed');
  135. $documentId = $this->getCreatedDocIdV8($info);
  136. $this->assertNotEmpty($documentId, 'No elastic document id received');
  137. } else {
  138. $documentId = $this->getCreatedDocId($client->transport->getLastConnection()->getLastRequestInfo());
  139. $this->assertNotEmpty($documentId, 'No elastic document id received');
  140. }
  141. // retrieve document source from ES and validate
  142. $document = $this->getDocSourceFromElastic(
  143. $client,
  144. $this->options['index'],
  145. $this->options['type'],
  146. $documentId
  147. );
  148. $this->assertEquals($expected, $document);
  149. // remove test index from ES
  150. $client->indices()->delete(['index' => $this->options['index']]);
  151. }
  152. /**
  153. * Return last created document id from ES response
  154. *
  155. * @param array $info Elasticsearch last request info
  156. */
  157. protected function getCreatedDocId(array $info): ?string
  158. {
  159. $data = json_decode($info['response']['body'], true);
  160. if (!empty($data['items'][0]['index']['_id'])) {
  161. return $data['items'][0]['index']['_id'];
  162. }
  163. return null;
  164. }
  165. /**
  166. * Return last created document id from ES response
  167. *
  168. * @param array $data Elasticsearch last request info
  169. * @return string|null
  170. */
  171. protected function getCreatedDocIdV8(array $data)
  172. {
  173. if (!empty($data['items'][0]['index']['_id'])) {
  174. return $data['items'][0]['index']['_id'];
  175. }
  176. return null;
  177. }
  178. /**
  179. * Retrieve document by id from Elasticsearch
  180. *
  181. * @return array<mixed>
  182. */
  183. protected function getDocSourceFromElastic(Client|Client8 $client, string $index, string $type, string $documentId): array
  184. {
  185. $params = [
  186. 'index' => $index,
  187. 'id' => $documentId,
  188. ];
  189. if (!$client instanceof Client8 && $client::VERSION[0] !== '7') {
  190. $params['type'] = $type;
  191. }
  192. $data = $client->get($params);
  193. if (!empty($data['_source'])) {
  194. return $data['_source'];
  195. }
  196. return [];
  197. }
  198. /**
  199. * @return ClientBuilder|ClientBuilder8
  200. */
  201. private function getClientBuilder()
  202. {
  203. if (class_exists(ClientBuilder8::class)) {
  204. return ClientBuilder8::create();
  205. }
  206. return ClientBuilder::create();
  207. }
  208. }