Merge "Convert Special:DeletedContributions to use OOUI."
[lhc/web/wiklou.git] / includes / debug / logger / monolog / LogstashFormatter.php
1 <?php
2
3 namespace MediaWiki\Logger\Monolog;
4
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.
9 *
10 * Compatible with Monolog 1.x only.
11 *
12 * @since 1.29
13 */
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',
25 ];
26
27 /**
28 * Prevent key conflicts
29 * @param array $record
30 * @return array
31 */
32 protected function formatV0( array $record ) {
33 if ( $this->contextPrefix ) {
34 return parent::formatV0( $record );
35 }
36
37 $context = !empty( $record['context'] ) ? $record['context'] : [];
38 $record['context'] = [];
39 $formatted = parent::formatV0( $record );
40
41 $formatted['@fields'] = $this->fixKeyConflicts( $formatted['@fields'], $context );
42 return $formatted;
43 }
44
45 /**
46 * Prevent key conflicts
47 * @param array $record
48 * @return array
49 */
50 protected function formatV1( array $record ) {
51 if ( $this->contextPrefix ) {
52 return parent::formatV1( $record );
53 }
54
55 $context = !empty( $record['context'] ) ? $record['context'] : [];
56 $record['context'] = [];
57 $formatted = parent::formatV1( $record );
58
59 $formatted = $this->fixKeyConflicts( $formatted, $context );
60 return $formatted;
61 }
62
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
69 */
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;
78 }
79 $fields[$key] = $val;
80 }
81 return $fields;
82 }
83 }