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 DateTimeInterface;
15
16/**
17 * Format a log message into an Elasticsearch record
18 *
19 * @author Avtandil Kikabidze <akalongman@gmail.com>
20 */
21class ElasticsearchFormatter extends NormalizerFormatter
22{
23    /**
24     * @var string Elasticsearch index name
25     */
26    protected $index;
27
28    /**
29     * @var string Elasticsearch record type
30     */
31    protected $type;
32
33    /**
34     * @param string $index Elasticsearch index name
35     * @param string $type  Elasticsearch record type
36     */
37    public function __construct(string $index, string $type)
38    {
39        // Elasticsearch requires an ISO 8601 format date with optional millisecond precision.
40        parent::__construct(DateTimeInterface::ISO8601);
41
42        $this->index = $index;
43        $this->type = $type;
44    }
45
46    /**
47     * {@inheritDoc}
48     */
49    public function format(array $record)
50    {
51        $record = parent::format($record);
52
53        return $this->getDocument($record);
54    }
55
56    /**
57     * Getter index
58     *
59     * @return string
60     */
61    public function getIndex(): string
62    {
63        return $this->index;
64    }
65
66    /**
67     * Getter type
68     *
69     * @return string
70     */
71    public function getType(): string
72    {
73        return $this->type;
74    }
75
76    /**
77     * Convert a log message into an Elasticsearch record
78     *
79     * @param  mixed[] $record Log message
80     * @return mixed[]
81     */
82    protected function getDocument(array $record): array
83    {
84        $record['_index'] = $this->index;
85        $record['_type'] = $this->type;
86
87        return $record;
88    }
89}
90