Merge "mediawiki.Title: Remove dead code and streamline newFromUserInput()"
[lhc/web/wiklou.git] / includes / debug / logger / LegacyLogger.php
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Logger;
22
23 use DateTimeZone;
24 use Error;
25 use Exception;
26 use WikiMap;
27 use MWDebug;
28 use MWExceptionHandler;
29 use Psr\Log\AbstractLogger;
30 use Psr\Log\LogLevel;
31 use Throwable;
32 use UDPTransport;
33
34 /**
35 * PSR-3 logger that mimics the historic implementation of MediaWiki's former
36 * wfErrorLog logging implementation.
37 *
38 * This logger is configured by the following global configuration variables:
39 * - `$wgDebugLogFile`
40 * - `$wgDebugLogGroups`
41 * - `$wgDBerrorLog`
42 * - `$wgDBerrorLogTZ`
43 *
44 * See documentation in DefaultSettings.php for detailed explanations of each
45 * variable.
46 *
47 * @see \MediaWiki\Logger\LoggerFactory
48 * @since 1.25
49 * @copyright © 2014 Wikimedia Foundation and contributors
50 */
51 class LegacyLogger extends AbstractLogger {
52
53 /**
54 * @var string $channel
55 */
56 protected $channel;
57
58 /**
59 * Convert \Psr\Log\LogLevel constants into int for sane comparisons
60 * These are the same values that Monlog uses
61 *
62 * @var array $levelMapping
63 */
64 protected static $levelMapping = [
65 LogLevel::DEBUG => 100,
66 LogLevel::INFO => 200,
67 LogLevel::NOTICE => 250,
68 LogLevel::WARNING => 300,
69 LogLevel::ERROR => 400,
70 LogLevel::CRITICAL => 500,
71 LogLevel::ALERT => 550,
72 LogLevel::EMERGENCY => 600,
73 ];
74
75 /**
76 * @var array
77 */
78 protected static $dbChannels = [
79 'DBQuery' => true,
80 'DBConnection' => true
81 ];
82
83 /**
84 * @param string $channel
85 */
86 public function __construct( $channel ) {
87 $this->channel = $channel;
88 }
89
90 /**
91 * Logs with an arbitrary level.
92 *
93 * @param string|int $level
94 * @param string $message
95 * @param array $context
96 * @return null
97 */
98 public function log( $level, $message, array $context = [] ) {
99 global $wgDBerrorLog;
100
101 if ( is_string( $level ) ) {
102 $level = self::$levelMapping[$level];
103 }
104 if ( $this->channel === 'DBQuery'
105 && isset( $context['method'] )
106 && isset( $context['master'] )
107 && isset( $context['runtime'] )
108 ) {
109 // Also give the query information to the MWDebug tools
110 $enabled = MWDebug::query(
111 $message,
112 $context['method'],
113 $context['master'],
114 $context['runtime']
115 );
116 if ( $enabled ) {
117 // If we the toolbar was enabled, return early so that we don't
118 // also log the query to the main debug output.
119 return;
120 }
121 }
122
123 // If this is a DB-related error, and the site has $wgDBerrorLog
124 // configured, rewrite the channel as wfLogDBError instead.
125 // Likewise, if the site does not use $wgDBerrorLog, it should
126 // configurable like any other channel via $wgDebugLogGroups
127 // or $wgMWLoggerDefaultSpi.
128 if ( isset( self::$dbChannels[$this->channel] )
129 && $level >= self::$levelMapping[LogLevel::ERROR]
130 && $wgDBerrorLog
131 ) {
132 // Format and write DB errors to the legacy locations
133 $effectiveChannel = 'wfLogDBError';
134 } else {
135 $effectiveChannel = $this->channel;
136 }
137
138 if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
139 $text = self::format( $effectiveChannel, $message, $context );
140 $destination = self::destination( $effectiveChannel, $message, $context );
141 self::emit( $text, $destination );
142 }
143 if ( !isset( $context['private'] ) || !$context['private'] ) {
144 // Add to debug toolbar if not marked as "private"
145 MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
146 }
147 }
148
149 /**
150 * Determine if the given message should be emitted or not.
151 *
152 * @param string $channel
153 * @param string $message
154 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
155 * @param array $context
156 * @return bool True if message should be sent to disk/network, false
157 * otherwise
158 */
159 public static function shouldEmit( $channel, $message, $level, $context ) {
160 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
161
162 if ( is_string( $level ) ) {
163 $level = self::$levelMapping[$level];
164 }
165
166 if ( $channel === 'wfLogDBError' ) {
167 // wfLogDBError messages are emitted if a database log location is
168 // specfied.
169 $shouldEmit = (bool)$wgDBerrorLog;
170
171 } elseif ( $channel === 'wfDebug' ) {
172 // wfDebug messages are emitted if a catch all logging file has
173 // been specified. Checked explicitly so that 'private' flagged
174 // messages are not discarded by unset $wgDebugLogGroups channel
175 // handling below.
176 $shouldEmit = $wgDebugLogFile != '';
177
178 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
179 $logConfig = $wgDebugLogGroups[$channel];
180
181 if ( is_array( $logConfig ) ) {
182 $shouldEmit = true;
183 if ( isset( $logConfig['sample'] ) ) {
184 // Emit randomly with a 1 in 'sample' chance for each message.
185 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
186 }
187
188 if ( isset( $logConfig['level'] ) ) {
189 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
190 }
191 } else {
192 // Emit unless the config value is explictly false.
193 $shouldEmit = $logConfig !== false;
194 }
195
196 } elseif ( isset( $context['private'] ) && $context['private'] ) {
197 // Don't emit if the message didn't match previous checks based on
198 // the channel and the event is marked as private. This check
199 // discards messages sent via wfDebugLog() with dest == 'private'
200 // and no explicit wgDebugLogGroups configuration.
201 $shouldEmit = false;
202 } else {
203 // Default return value is the same as the historic wfDebug
204 // method: emit if $wgDebugLogFile has been set.
205 $shouldEmit = $wgDebugLogFile != '';
206 }
207
208 return $shouldEmit;
209 }
210
211 /**
212 * Format a message.
213 *
214 * Messages to the 'wfDebug' and 'wfLogDBError' channels receive special formatting to mimic the
215 * historic output of the functions of the same name. All other channel values are formatted
216 * based on the historic output of the `wfDebugLog()` global function.
217 *
218 * @param string $channel
219 * @param string $message
220 * @param array $context
221 * @return string
222 */
223 public static function format( $channel, $message, $context ) {
224 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
225
226 if ( $channel === 'wfDebug' ) {
227 $text = self::formatAsWfDebug( $channel, $message, $context );
228
229 } elseif ( $channel === 'wfLogDBError' ) {
230 $text = self::formatAsWfLogDBError( $channel, $message, $context );
231
232 } elseif ( $channel === 'profileoutput' ) {
233 // Legacy wfLogProfilingData formatitng
234 $forward = '';
235 if ( isset( $context['forwarded_for'] ) ) {
236 $forward = " forwarded for {$context['forwarded_for']}";
237 }
238 if ( isset( $context['client_ip'] ) ) {
239 $forward .= " client IP {$context['client_ip']}";
240 }
241 if ( isset( $context['from'] ) ) {
242 $forward .= " from {$context['from']}";
243 }
244 if ( $forward ) {
245 $forward = "\t(proxied via {$context['proxy']}{$forward})";
246 }
247 if ( $context['anon'] ) {
248 $forward .= ' anon';
249 }
250 if ( !isset( $context['url'] ) ) {
251 $context['url'] = 'n/a';
252 }
253
254 $log = sprintf( "%s\t%04.3f\t%s%s\n",
255 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
256
257 $text = self::formatAsWfDebugLog(
258 $channel, $log . $context['output'], $context );
259
260 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
261 $text = self::formatAsWfDebug(
262 $channel, "[{$channel}] {$message}", $context );
263
264 } else {
265 // Default formatting is wfDebugLog's historic style
266 $text = self::formatAsWfDebugLog( $channel, $message, $context );
267 }
268
269 // Append stacktrace of exception if available
270 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
271 $e = $context['exception'];
272 $backtrace = false;
273
274 if ( $e instanceof Throwable || $e instanceof Exception ) {
275 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
276
277 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
278 // Exception has already been unpacked as structured data
279 $backtrace = $e['trace'];
280 }
281
282 if ( $backtrace ) {
283 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
284 "\n";
285 }
286 }
287
288 return self::interpolate( $text, $context );
289 }
290
291 /**
292 * Format a message as `wfDebug()` would have formatted it.
293 *
294 * @param string $channel
295 * @param string $message
296 * @param array $context
297 * @return string
298 */
299 protected static function formatAsWfDebug( $channel, $message, $context ) {
300 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
301 if ( isset( $context['seconds_elapsed'] ) ) {
302 // Prepend elapsed request time and real memory usage with two
303 // trailing spaces.
304 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
305 }
306 if ( isset( $context['prefix'] ) ) {
307 $text = "{$context['prefix']}{$text}";
308 }
309 return "{$text}\n";
310 }
311
312 /**
313 * Format a message as `wfLogDBError()` would have formatted it.
314 *
315 * @param string $channel
316 * @param string $message
317 * @param array $context
318 * @return string
319 */
320 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
321 global $wgDBerrorLogTZ;
322 static $cachedTimezone = null;
323
324 if ( !$cachedTimezone ) {
325 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
326 }
327
328 $d = date_create( 'now', $cachedTimezone );
329 $date = $d->format( 'D M j G:i:s T Y' );
330
331 $host = wfHostname();
332 $wiki = WikiMap::getWikiIdFromDbDomain( WikiMap::getCurrentWikiDbDomain() );
333
334 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
335 return $text;
336 }
337
338 /**
339 * Format a message as `wfDebugLog() would have formatted it.
340 *
341 * @param string $channel
342 * @param string $message
343 * @param array $context
344 * @return string
345 */
346 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
347 $time = wfTimestamp( TS_DB );
348 $wiki = WikiMap::getWikiIdFromDbDomain( WikiMap::getCurrentWikiDbDomain() );
349 $host = wfHostname();
350 $text = "{$time} {$host} {$wiki}: {$message}\n";
351 return $text;
352 }
353
354 /**
355 * Interpolate placeholders in logging message.
356 *
357 * @param string $message
358 * @param array $context
359 * @return string Interpolated message
360 */
361 public static function interpolate( $message, array $context ) {
362 if ( strpos( $message, '{' ) !== false ) {
363 $replace = [];
364 foreach ( $context as $key => $val ) {
365 $replace['{' . $key . '}'] = self::flatten( $val );
366 }
367 $message = strtr( $message, $replace );
368 }
369 return $message;
370 }
371
372 /**
373 * Convert a logging context element to a string suitable for
374 * interpolation.
375 *
376 * @param mixed $item
377 * @return string
378 */
379 protected static function flatten( $item ) {
380 if ( $item === null ) {
381 return '[Null]';
382 }
383
384 if ( is_bool( $item ) ) {
385 return $item ? 'true' : 'false';
386 }
387
388 if ( is_float( $item ) ) {
389 if ( is_infinite( $item ) ) {
390 return ( $item > 0 ? '' : '-' ) . 'INF';
391 }
392 if ( is_nan( $item ) ) {
393 return 'NaN';
394 }
395 return (string)$item;
396 }
397
398 if ( is_scalar( $item ) ) {
399 return (string)$item;
400 }
401
402 if ( is_array( $item ) ) {
403 return '[Array(' . count( $item ) . ')]';
404 }
405
406 if ( $item instanceof \DateTime ) {
407 return $item->format( 'c' );
408 }
409
410 if ( $item instanceof Throwable || $item instanceof Exception ) {
411 $which = $item instanceof Error ? 'Error' : 'Exception';
412 return '[' . $which . ' ' . get_class( $item ) . '( ' .
413 $item->getFile() . ':' . $item->getLine() . ') ' .
414 $item->getMessage() . ']';
415 }
416
417 if ( is_object( $item ) ) {
418 if ( method_exists( $item, '__toString' ) ) {
419 return (string)$item;
420 }
421
422 return '[Object ' . get_class( $item ) . ']';
423 }
424
425 if ( is_resource( $item ) ) {
426 return '[Resource ' . get_resource_type( $item ) . ']';
427 }
428
429 return '[Unknown ' . gettype( $item ) . ']';
430 }
431
432 /**
433 * Select the appropriate log output destination for the given log event.
434 *
435 * If the event context contains 'destination'
436 *
437 * @param string $channel
438 * @param string $message
439 * @param array $context
440 * @return string
441 */
442 protected static function destination( $channel, $message, $context ) {
443 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
444
445 // Default destination is the debug log file as historically used by
446 // the wfDebug function.
447 $destination = $wgDebugLogFile;
448
449 if ( isset( $context['destination'] ) ) {
450 // Use destination explicitly provided in context
451 $destination = $context['destination'];
452
453 } elseif ( $channel === 'wfDebug' ) {
454 $destination = $wgDebugLogFile;
455
456 } elseif ( $channel === 'wfLogDBError' ) {
457 $destination = $wgDBerrorLog;
458
459 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
460 $logConfig = $wgDebugLogGroups[$channel];
461
462 if ( is_array( $logConfig ) ) {
463 $destination = $logConfig['destination'];
464 } else {
465 $destination = strval( $logConfig );
466 }
467 }
468
469 return $destination;
470 }
471
472 /**
473 * Log to a file without getting "file size exceeded" signals.
474 *
475 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
476 * lines to the specified port, prefixed by the specified prefix and a space.
477 *
478 * @param string $text
479 * @param string $file Filename
480 */
481 public static function emit( $text, $file ) {
482 if ( substr( $file, 0, 4 ) == 'udp:' ) {
483 $transport = UDPTransport::newFromString( $file );
484 $transport->emit( $text );
485 } else {
486 \Wikimedia\suppressWarnings();
487 $exists = file_exists( $file );
488 $size = $exists ? filesize( $file ) : false;
489 if ( !$exists ||
490 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
491 ) {
492 file_put_contents( $file, $text, FILE_APPEND );
493 }
494 \Wikimedia\restoreWarnings();
495 }
496 }
497
498 }