ElasticsearchHandlerTest.php 7.5 KB

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