ElasticsearchHandlerTest.php 7.5 KB

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