1<?php declare(strict_types=1); 2 3/* 4 * This file is part of the Monolog package. 5 * 6 * (c) Jordi Boggiano <j.boggiano@seld.be> 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Monolog\Formatter; 13 14use Elastica\Document; 15 16/** 17 * Format a log message into an Elastica Document 18 * 19 * @author Jelle Vink <jelle.vink@gmail.com> 20 * 21 * @phpstan-import-type Record from \Monolog\Logger 22 */ 23class ElasticaFormatter extends NormalizerFormatter 24{ 25 /** 26 * @var string Elastic search index name 27 */ 28 protected $index; 29 30 /** 31 * @var ?string Elastic search document type 32 */ 33 protected $type; 34 35 /** 36 * @param string $index Elastic Search index name 37 * @param ?string $type Elastic Search document type, deprecated as of Elastica 7 38 */ 39 public function __construct(string $index, ?string $type) 40 { 41 // elasticsearch requires a ISO 8601 format date with optional millisecond precision. 42 parent::__construct('Y-m-d\TH:i:s.uP'); 43 44 $this->index = $index; 45 $this->type = $type; 46 } 47 48 /** 49 * {@inheritDoc} 50 */ 51 public function format(array $record) 52 { 53 $record = parent::format($record); 54 55 return $this->getDocument($record); 56 } 57 58 public function getIndex(): string 59 { 60 return $this->index; 61 } 62 63 /** 64 * @deprecated since Elastica 7 type has no effect 65 */ 66 public function getType(): string 67 { 68 /** @phpstan-ignore-next-line */ 69 return $this->type; 70 } 71 72 /** 73 * Convert a log message into an Elastica Document 74 * 75 * @phpstan-param Record $record 76 */ 77 protected function getDocument(array $record): Document 78 { 79 $document = new Document(); 80 $document->setData($record); 81 if (method_exists($document, 'setType')) { 82 /** @phpstan-ignore-next-line */ 83 $document->setType($this->type); 84 } 85 $document->setIndex($this->index); 86 87 return $document; 88 } 89} 90