Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.74% covered (success)
96.74%
89 / 92
62.50% covered (warning)
62.50%
5 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
LogstashFormatter
96.74% covered (success)
96.74%
89 / 92
62.50% covered (warning)
62.50%
5 / 8
40
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 format
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 formatV0
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 formatMonologV0
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
12
 formatV1
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 formatMonologV1
96.00% covered (success)
96.00%
24 / 25
0.00% covered (danger)
0.00%
0 / 1
11
 fixKeyConflicts
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 normalizeException
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3namespace MediaWiki\Logger\Monolog;
4
5use MediaWiki\Exception\MWExceptionHandler;
6use Monolog\LogRecord;
7
8/**
9 * Modified version of Monolog\Formatter\LogstashFormatter
10 *
11 * - Squash the base message array, the context and extra subarrays into one.
12 *   This can result in unfortunately named context fields overwriting other data (T145133).
13 * - Improve exception JSON-ification, which is done poorly by the standard class.
14 *
15 * @since 1.29
16 * @ingroup Debug
17 */
18class LogstashFormatter extends \Monolog\Formatter\LogstashFormatter {
19
20    public const V0 = 0;
21    public const V1 = 1;
22
23    /** @var array Keys which should not be used in log context */
24    protected $reservedKeys = [
25        // from LogstashFormatter
26        'message', 'channel', 'level', 'type',
27        // from WebProcessor
28        'url', 'ip', 'http_method', 'server', 'referrer',
29        // from WikiProcessor
30        'host', 'wiki', 'reqId', 'mwversion',
31        // from config magic
32        'normalized_message',
33    ];
34
35    /**
36     * @var int Logstash format version to use
37     */
38    protected $version;
39
40    /**
41     * TODO: See T247675 for removing this override.
42     *
43     * @param string $applicationName The application that sends the data, used as the "type"
44     * field of logstash
45     * @param string|null $systemName The system/machine name, used as the "source" field of
46     * logstash, defaults to the hostname of the machine
47     * @param string $extraKey The key for extra keys inside logstash "fields", defaults to ''
48     * @param string $contextKey The key for context keys inside logstash "fields", defaults
49     * @param int $version The logstash format version to use, defaults to V0
50     * to ''
51     */
52    public function __construct( string $applicationName, ?string $systemName = null,
53        string $extraKey = '', string $contextKey = 'ctxt_', $version = self::V0
54    ) {
55        $this->version = $version;
56        parent::__construct( $applicationName, $systemName, $extraKey, $contextKey );
57    }
58
59    public function format( LogRecord $record ): string {
60        $record = \Monolog\Formatter\NormalizerFormatter::format( $record );
61        if ( $this->version === self::V1 ) {
62            $message = $this->formatV1( $record );
63        } elseif ( $this->version === self::V0 ) {
64            $message = $this->formatV0( $record );
65        } else {
66            $message = __METHOD__ . ' unknown version ' . $this->version;
67        }
68
69        return $this->toJson( $message ) . "\n";
70    }
71
72    /**
73     * Prevent key conflicts
74     * @param array $record
75     * @return array
76     */
77    protected function formatV0( array $record ) {
78        if ( $this->contextKey !== '' ) {
79            return $this->formatMonologV0( $record );
80        }
81
82        $context = !empty( $record['context'] ) ? $record['context'] : [];
83        $record['context'] = [];
84        $formatted = $this->formatMonologV0( $record );
85
86        $formatted['@fields'] = $this->fixKeyConflicts( $formatted['@fields'], $context );
87
88        return $formatted;
89    }
90
91    /**
92     * Borrowed from monolog/monolog 1.25.3
93     * https://github.com/Seldaek/monolog/blob/1.x/src/Monolog/Formatter/LogstashFormatter.php#L87-L128
94     *
95     * @param array $record
96     * @return array
97     */
98    protected function formatMonologV0( array $record ) {
99        if ( empty( $record['datetime'] ) ) {
100            $record['datetime'] = gmdate( 'c' );
101        }
102        $message = [
103            '@timestamp' => $record['datetime'],
104            '@source' => $this->systemName,
105            '@fields' => [],
106        ];
107        if ( isset( $record['message'] ) ) {
108            $message['@message'] = $record['message'];
109        }
110        if ( isset( $record['channel'] ) ) {
111            $message['@tags'] = [ $record['channel'] ];
112            $message['@fields']['channel'] = $record['channel'];
113        }
114        if ( isset( $record['level'] ) ) {
115            $message['@fields']['level'] = $record['level'];
116        }
117        if ( $this->applicationName ) {
118            $message['@type'] = $this->applicationName;
119        }
120        if ( isset( $record['extra']['server'] ) ) {
121            $message['@source_host'] = $record['extra']['server'];
122        }
123        if ( isset( $record['extra']['url'] ) ) {
124            $message['@source_path'] = $record['extra']['url'];
125        }
126        if ( !empty( $record['extra'] ) ) {
127            foreach ( $record['extra'] as $key => $val ) {
128                $message['@fields'][$this->extraKey . $key] = $val;
129            }
130        }
131        if ( !empty( $record['context'] ) ) {
132            foreach ( $record['context'] as $key => $val ) {
133                $message['@fields'][$this->contextKey . $key] = $val;
134            }
135        }
136
137        return $message;
138    }
139
140    /**
141     * Prevent key conflicts
142     * @param array $record
143     * @return array
144     */
145    protected function formatV1( array $record ) {
146        if ( $this->contextKey ) {
147            return $this->formatMonologV1( $record );
148        }
149
150        $context = !empty( $record['context'] ) ? $record['context'] : [];
151        $record['context'] = [];
152        $formatted = $this->formatMonologV1( $record );
153
154        return $this->fixKeyConflicts( $formatted, $context );
155    }
156
157    /**
158     * Borrowed mostly from monolog/monolog 1.25.3
159     * https://github.com/Seldaek/monolog/blob/1.25.3/src/Monolog/Formatter/LogstashFormatter.php#L130-165
160     *
161     * @param array $record
162     * @return array
163     */
164    protected function formatMonologV1( array $record ) {
165        if ( empty( $record['datetime'] ) ) {
166            $record['datetime'] = gmdate( 'c' );
167        }
168        $message = [
169            '@timestamp' => $record['datetime'],
170            '@version' => 1,
171            'host' => $this->systemName,
172        ];
173        if ( isset( $record['message'] ) ) {
174            $message['message'] = $record['message'];
175        }
176        if ( isset( $record['channel'] ) ) {
177            $message['type'] = $record['channel'];
178            $message['channel'] = $record['channel'];
179        }
180        if ( isset( $record['level_name'] ) ) {
181            $message['level'] = $record['level_name'];
182        }
183        // level -> monolog_level is new in 2.0
184        // https://github.com/Seldaek/monolog/blob/2.0.2/src/Monolog/Formatter/LogstashFormatter.php#L86-L88
185        if ( isset( $record['level'] ) ) {
186            $message['monolog_level'] = $record['level'];
187        }
188        if ( $this->applicationName ) {
189            $message['type'] = $this->applicationName;
190        }
191        if ( !empty( $record['extra'] ) ) {
192            foreach ( $record['extra'] as $key => $val ) {
193                $message[$this->extraKey . $key] = $val;
194            }
195        }
196        if ( !empty( $record['context'] ) ) {
197            foreach ( $record['context'] as $key => $val ) {
198                $message[$this->contextKey . $key] = $val;
199            }
200        }
201
202        return $message;
203    }
204
205    /**
206     * Rename any context field that would otherwise overwrite a message key.
207     *
208     * @param array $fields Fields to be sent to logstash
209     * @param array $context Copy of the original $record['context']
210     * @return array Updated version of $fields
211     */
212    protected function fixKeyConflicts( array $fields, array $context ) {
213        foreach ( $context as $key => $val ) {
214            if (
215                in_array( $key, $this->reservedKeys, true ) &&
216                isset( $fields[$key] ) && $fields[$key] !== $val
217            ) {
218                $fields['logstash_formatter_key_conflict'][] = $key;
219                $key = 'c_' . $key;
220            }
221            $fields[$key] = $val;
222        }
223        return $fields;
224    }
225
226    /**
227     * Use a more user-friendly trace format than Monolog\Formatter\NormalizerFormatter.
228     *
229     * @param \Throwable $e
230     * @param int $depth
231     * @return array
232     */
233    protected function normalizeException( \Throwable $e, int $depth = 0 ) {
234        $data = [
235            'class' => get_class( $e ),
236            'message' => $e->getMessage(),
237            'code' => $e->getCode(),
238            'file' => $e->getFile() . ':' . $e->getLine(),
239            'trace' => MWExceptionHandler::getRedactedTraceAsString( $e ),
240        ];
241
242        $previous = $e->getPrevious();
243        if ( $previous ) {
244            $data['previous'] = $this->normalizeException( $previous );
245        }
246
247        return $data;
248    }
249}