ElasticaFormatter.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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\Formatter;
  11. use Elastica\Document;
  12. use Monolog\LogRecord;
  13. /**
  14. * Format a log message into an Elastica Document
  15. *
  16. * @author Jelle Vink <jelle.vink@gmail.com>
  17. */
  18. class ElasticaFormatter extends NormalizerFormatter
  19. {
  20. /**
  21. * @var string Elastic search index name
  22. */
  23. protected string $index;
  24. /**
  25. * @var ?string Elastic search document type
  26. */
  27. protected $type;
  28. /**
  29. * @param string $index Elastic Search index name
  30. * @param ?string $type Elastic Search document type, deprecated as of Elastica 7
  31. */
  32. public function __construct(string $index, ?string $type)
  33. {
  34. // elasticsearch requires a ISO 8601 format date with optional millisecond precision.
  35. parent::__construct('Y-m-d\TH:i:s.uP');
  36. $this->index = $index;
  37. $this->type = $type;
  38. }
  39. /**
  40. * @inheritDoc
  41. */
  42. public function format(LogRecord $record)
  43. {
  44. $record = parent::format($record);
  45. return $this->getDocument($record);
  46. }
  47. public function getIndex(): string
  48. {
  49. return $this->index;
  50. }
  51. /**
  52. * @deprecated since Elastica 7 type has no effect
  53. */
  54. public function getType(): string
  55. {
  56. /** @phpstan-ignore-next-line */
  57. return $this->type;
  58. }
  59. /**
  60. * Convert a log message into an Elastica Document
  61. *
  62. * @param mixed[] $record
  63. */
  64. protected function getDocument(array $record): Document
  65. {
  66. $document = new Document();
  67. $document->setData($record);
  68. if (method_exists($document, 'setType')) {
  69. $document->setType($this->type);
  70. }
  71. $document->setIndex($this->index);
  72. return $document;
  73. }
  74. }