Added release notes for 'ContentHandler::runLegacyHooks' removal
[mediawiki.git] / includes / debug / logger / monolog / LogstashFormatter.php
blob553cbf61c4add2235a49f872e4847f24df127436
1 <?php
3 namespace MediaWiki\Logger\Monolog;
5 /**
6 * LogstashFormatter squashes the base message array and the context and extras subarrays into one.
7 * This can result in unfortunately named context fields overwriting other data (T145133).
8 * This class modifies the standard LogstashFormatter to rename such fields and flag the message.
10 * Compatible with Monolog 1.x only.
12 * @since 1.29
14 class LogstashFormatter extends \Monolog\Formatter\LogstashFormatter {
15 /** @var array Keys which should not be used in log context */
16 protected $reservedKeys = [
17 // from LogstashFormatter
18 'message', 'channel', 'level', 'type',
19 // from WebProcessor
20 'url', 'ip', 'http_method', 'server', 'referrer',
21 // from WikiProcessor
22 'host', 'wiki', 'reqId', 'mwversion',
23 // from config magic
24 'normalized_message',
27 /**
28 * Prevent key conflicts
29 * @param array $record
30 * @return array
32 protected function formatV0( array $record ) {
33 if ( $this->contextPrefix ) {
34 return parent::formatV0( $record );
37 $context = !empty( $record['context'] ) ? $record['context'] : [];
38 $record['context'] = [];
39 $formatted = parent::formatV0( $record );
41 $formatted['@fields'] = $this->fixKeyConflicts( $formatted['@fields'], $context );
42 return $formatted;
45 /**
46 * Prevent key conflicts
47 * @param array $record
48 * @return array
50 protected function formatV1( array $record ) {
51 if ( $this->contextPrefix ) {
52 return parent::formatV1( $record );
55 $context = !empty( $record['context'] ) ? $record['context'] : [];
56 $record['context'] = [];
57 $formatted = parent::formatV1( $record );
59 $formatted = $this->fixKeyConflicts( $formatted, $context );
60 return $formatted;
63 /**
64 * Check whether some context field would overwrite another message key. If so, rename
65 * and flag.
66 * @param array $fields Fields to be sent to logstash
67 * @param array $context Copy of the original $record['context']
68 * @return array Updated version of $fields
70 protected function fixKeyConflicts( array $fields, array $context ) {
71 foreach ( $context as $key => $val ) {
72 if (
73 in_array( $key, $this->reservedKeys, true ) &&
74 isset( $fields[$key] ) && $fields[$key] !== $val
75 ) {
76 $fields['logstash_formatter_key_conflict'][] = $key;
77 $key = 'c_' . $key;
79 $fields[$key] = $val;
81 return $fields;