ElasticsearchHandlerTest.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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\Logger;
  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. ->setMethods(['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 = [
  52. 'level' => Logger::ERROR,
  53. 'level_name' => 'ERROR',
  54. 'channel' => 'meh',
  55. 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
  56. 'datetime' => new \DateTimeImmutable("@0"),
  57. 'extra' => [],
  58. 'message' => 'log',
  59. ];
  60. // format expected result
  61. $formatter = new ElasticsearchFormatter($this->options['index'], $this->options['type']);
  62. $data = $formatter->format($msg);
  63. unset($data['_index'], $data['_type']);
  64. $expected = [
  65. 'body' => [
  66. [
  67. 'index' => [
  68. '_index' => $this->options['index'],
  69. '_type' => $this->options['type'],
  70. ],
  71. ],
  72. $data,
  73. ],
  74. ];
  75. // setup ES client mock
  76. $this->client->expects($this->any())
  77. ->method('bulk')
  78. ->with($expected);
  79. // perform tests
  80. $handler = new ElasticsearchHandler($this->client, $this->options);
  81. $handler->handle($msg);
  82. $handler->handleBatch([$msg]);
  83. }
  84. /**
  85. * @covers Monolog\Handler\ElasticsearchHandler::setFormatter
  86. */
  87. public function testSetFormatter()
  88. {
  89. $handler = new ElasticsearchHandler($this->client);
  90. $formatter = new ElasticsearchFormatter('index_new', 'type_new');
  91. $handler->setFormatter($formatter);
  92. $this->assertInstanceOf('Monolog\Formatter\ElasticsearchFormatter', $handler->getFormatter());
  93. $this->assertEquals('index_new', $handler->getFormatter()->getIndex());
  94. $this->assertEquals('type_new', $handler->getFormatter()->getType());
  95. }
  96. /**
  97. * @covers Monolog\Handler\ElasticsearchHandler::setFormatter
  98. */
  99. public function testSetFormatterInvalid()
  100. {
  101. $this->expectException(\InvalidArgumentException::class);
  102. $this->expectExceptionMessage('ElasticsearchHandler is only compatible with ElasticsearchFormatter');
  103. $handler = new ElasticsearchHandler($this->client);
  104. $formatter = new NormalizerFormatter();
  105. $handler->setFormatter($formatter);
  106. }
  107. /**
  108. * @covers Monolog\Handler\ElasticsearchHandler::__construct
  109. * @covers Monolog\Handler\ElasticsearchHandler::getOptions
  110. */
  111. public function testOptions()
  112. {
  113. $expected = [
  114. 'index' => $this->options['index'],
  115. 'type' => $this->options['type'],
  116. 'ignore_error' => false,
  117. ];
  118. $handler = new ElasticsearchHandler($this->client, $this->options);
  119. $this->assertEquals($expected, $handler->getOptions());
  120. }
  121. /**
  122. * @covers Monolog\Handler\ElasticsearchHandler::bulkSend
  123. * @dataProvider providerTestConnectionErrors
  124. */
  125. public function testConnectionErrors($ignore, $expectedError)
  126. {
  127. $hosts = [['host' => '127.0.0.1', 'port' => 1]];
  128. $client = ClientBuilder::create()
  129. ->setHosts($hosts)
  130. ->build();
  131. $handlerOpts = ['ignore_error' => $ignore];
  132. $handler = new ElasticsearchHandler($client, $handlerOpts);
  133. if ($expectedError) {
  134. $this->expectException($expectedError[0]);
  135. $this->expectExceptionMessage($expectedError[1]);
  136. $handler->handle($this->getRecord());
  137. } else {
  138. $this->assertFalse($handler->handle($this->getRecord()));
  139. }
  140. }
  141. /**
  142. * @return array
  143. */
  144. public function providerTestConnectionErrors()
  145. {
  146. return [
  147. [false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
  148. [true, false],
  149. ];
  150. }
  151. /**
  152. * Integration test using localhost Elasticsearch server
  153. *
  154. * @covers Monolog\Handler\ElasticsearchHandler::__construct
  155. * @covers Monolog\Handler\ElasticsearchHandler::handleBatch
  156. * @covers Monolog\Handler\ElasticsearchHandler::bulkSend
  157. * @covers Monolog\Handler\ElasticsearchHandler::getDefaultFormatter
  158. */
  159. public function testHandleIntegration()
  160. {
  161. $msg = [
  162. 'level' => Logger::ERROR,
  163. 'level_name' => 'ERROR',
  164. 'channel' => 'meh',
  165. 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
  166. 'datetime' => new \DateTimeImmutable("@0"),
  167. 'extra' => [],
  168. 'message' => 'log',
  169. ];
  170. $expected = $msg;
  171. $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
  172. $expected['context'] = [
  173. 'class' => ["stdClass" => []],
  174. 'foo' => 7,
  175. 0 => 'bar',
  176. ];
  177. $hosts = [['host' => '127.0.0.1', 'port' => 9200]];
  178. $client = ClientBuilder::create()
  179. ->setHosts($hosts)
  180. ->build();
  181. $handler = new ElasticsearchHandler($client, $this->options);
  182. try {
  183. $handler->handleBatch([$msg]);
  184. } catch (\RuntimeException $e) {
  185. $this->markTestSkipped('Cannot connect to Elasticsearch server on localhost');
  186. }
  187. // check document id from ES server response
  188. $documentId = $this->getCreatedDocId($client->transport->getLastConnection()->getLastRequestInfo());
  189. $this->assertNotEmpty($documentId, 'No elastic document id received');
  190. // retrieve document source from ES and validate
  191. $document = $this->getDocSourceFromElastic(
  192. $client,
  193. $this->options['index'],
  194. $this->options['type'],
  195. $documentId
  196. );
  197. $this->assertEquals($expected, $document);
  198. // remove test index from ES
  199. $client->indices()->delete(['index' => $this->options['index']]);
  200. }
  201. /**
  202. * Return last created document id from ES response
  203. *
  204. * @param array $info Elasticsearch last request info
  205. * @return string|null
  206. */
  207. protected function getCreatedDocId(array $info)
  208. {
  209. $data = json_decode($info['response']['body'], true);
  210. if (!empty($data['items'][0]['index']['_id'])) {
  211. return $data['items'][0]['index']['_id'];
  212. }
  213. }
  214. /**
  215. * Retrieve document by id from Elasticsearch
  216. *
  217. * @param Client $client Elasticsearch client
  218. * @param string $index
  219. * @param string $type
  220. * @param string $documentId
  221. * @return array
  222. */
  223. protected function getDocSourceFromElastic(Client $client, $index, $type, $documentId)
  224. {
  225. $params = [
  226. 'index' => $index,
  227. 'type' => $type,
  228. 'id' => $documentId,
  229. ];
  230. $data = $client->get($params);
  231. if (!empty($data['_source'])) {
  232. return $data['_source'];
  233. }
  234. return [];
  235. }
  236. }