MediaWiki REL1_35
LegacyLogger.php
Go to the documentation of this file.
1<?php
21namespace MediaWiki\Logger;
22
23use DateTimeZone;
24use Error;
25use MWDebug;
27use Psr\Log\AbstractLogger;
28use Psr\Log\LogLevel;
29use RuntimeException;
30use Throwable;
31use UDPTransport;
32use WikiMap;
33
51class LegacyLogger extends AbstractLogger {
52
56 protected $channel;
57
58 private const LEVEL_DEBUG = 100;
59 private const LEVEL_INFO = 200;
60 private const LEVEL_NOTICE = 250;
61 private const LEVEL_WARNING = 300;
62 private const LEVEL_ERROR = 400;
63 private const LEVEL_CRITICAL = 500;
64 private const LEVEL_ALERT = 550;
65 private const LEVEL_EMERGENCY = 600;
66 private const LEVEL_INFINITY = 999;
67
74 protected static $levelMapping = [
75 LogLevel::DEBUG => self::LEVEL_DEBUG,
76 LogLevel::INFO => self::LEVEL_INFO,
77 LogLevel::NOTICE => self::LEVEL_NOTICE,
78 LogLevel::WARNING => self::LEVEL_WARNING,
79 LogLevel::ERROR => self::LEVEL_ERROR,
80 LogLevel::CRITICAL => self::LEVEL_CRITICAL,
81 LogLevel::ALERT => self::LEVEL_ALERT,
82 LogLevel::EMERGENCY => self::LEVEL_EMERGENCY,
83 ];
84
88 protected static $dbChannels = [
89 'DBQuery' => true,
90 'DBConnection' => true
91 ];
92
100
106 private $isDB;
107
111 public function __construct( $channel ) {
113
114 $this->channel = $channel;
115 $this->isDB = isset( self::$dbChannels[$channel] );
116
117 // Calculate minimum level, duplicating some of the logic from log() and shouldEmit()
118 if ( $wgDebugLogFile != '' || $wgDebugToolbar ) {
119 // Log all messages if there is a debug log file or debug toolbar
120 $this->minimumLevel = self::LEVEL_DEBUG;
121 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
122 $logConfig = $wgDebugLogGroups[$channel];
123 // Log messages if the config is set, according to the configured level
124 if ( is_array( $logConfig ) && isset( $logConfig['level'] ) ) {
125 $this->minimumLevel = self::$levelMapping[$logConfig['level']];
126 } else {
127 $this->minimumLevel = self::LEVEL_DEBUG;
128 }
129 } else {
130 // No other case hit: discard all messages
131 $this->minimumLevel = self::LEVEL_INFINITY;
132 }
133 if ( $this->isDB && $wgDBerrorLog && $this->minimumLevel > self::LEVEL_ERROR ) {
134 // Log DB errors if there is a DB error log
135 $this->minimumLevel = self::LEVEL_ERROR;
136 }
137 }
138
146 public function setMinimumForTest( ?int $level ) {
147 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
148 throw new RuntimeException( 'Not allowed outside tests' );
149 }
150 // Set LEVEL_INFINITY if given null, or restore the original level.
151 $original = $this->minimumLevel;
152 $this->minimumLevel = $level ?? self::LEVEL_INFINITY;
153 return $original;
154 }
155
163 public function log( $level, $message, array $context = [] ) {
164 if ( is_string( $level ) ) {
165 $level = self::$levelMapping[$level];
166 }
167 if ( $level < $this->minimumLevel ) {
168 return;
169 }
170
171 if ( $this->channel === 'DBQuery'
172 && $level === self::LEVEL_DEBUG
173 && isset( $context['sql'] )
174 ) {
175 // Also give the query information to the MWDebug tools
177 $context['sql'],
178 $context['method'],
179 $context['runtime'],
180 $context['db_host']
181 );
182 }
183
184 // If this is a DB-related error, and the site has $wgDBerrorLog
185 // configured, rewrite the channel as wfLogDBError instead.
186 // Likewise, if the site does not use $wgDBerrorLog, it should
187 // configurable like any other channel via $wgDebugLogGroups
188 // or $wgMWLoggerDefaultSpi.
189 global $wgDBerrorLog;
190 if ( $this->isDB && $level >= self::LEVEL_ERROR && $wgDBerrorLog ) {
191 // Format and write DB errors to the legacy locations
192 $effectiveChannel = 'wfLogDBError';
193 } else {
194 $effectiveChannel = $this->channel;
195 }
196
197 if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
198 $text = self::format( $effectiveChannel, $message, $context );
199 $destination = self::destination( $effectiveChannel, $message, $context );
200 self::emit( $text, $destination );
201 }
202 if ( !isset( $context['private'] ) || !$context['private'] ) {
203 // Add to debug toolbar if not marked as "private"
204 MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
205 }
206 }
207
218 public static function shouldEmit( $channel, $message, $level, $context ) {
220
221 if ( is_string( $level ) ) {
222 $level = self::$levelMapping[$level];
223 }
224
225 if ( $channel === 'wfLogDBError' ) {
226 // wfLogDBError messages are emitted if a database log location is
227 // specfied.
228 $shouldEmit = (bool)$wgDBerrorLog;
229
230 } elseif ( $channel === 'wfDebug' ) {
231 // wfDebug messages are emitted if a catch all logging file has
232 // been specified. Checked explicitly so that 'private' flagged
233 // messages are not discarded by unset $wgDebugLogGroups channel
234 // handling below.
235 $shouldEmit = $wgDebugLogFile != '';
236
237 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
238 $logConfig = $wgDebugLogGroups[$channel];
239
240 if ( is_array( $logConfig ) ) {
241 $shouldEmit = true;
242 if ( isset( $logConfig['sample'] ) ) {
243 // Emit randomly with a 1 in 'sample' chance for each message.
244 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
245 }
246
247 if ( isset( $logConfig['level'] ) ) {
248 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
249 }
250 } else {
251 // Emit unless the config value is explictly false.
252 $shouldEmit = $logConfig !== false;
253 }
254
255 } elseif ( isset( $context['private'] ) && $context['private'] ) {
256 // Don't emit if the message didn't match previous checks based on
257 // the channel and the event is marked as private. This check
258 // discards messages sent via wfDebugLog() with dest == 'private'
259 // and no explicit wgDebugLogGroups configuration.
260 $shouldEmit = false;
261 } else {
262 // Default return value is the same as the historic wfDebug
263 // method: emit if $wgDebugLogFile has been set.
264 $shouldEmit = $wgDebugLogFile != '';
265 }
266
267 return $shouldEmit;
268 }
269
282 public static function format( $channel, $message, $context ) {
284
285 if ( $channel === 'wfDebug' ) {
286 $text = self::formatAsWfDebug( $channel, $message, $context );
287
288 } elseif ( $channel === 'wfLogDBError' ) {
289 $text = self::formatAsWfLogDBError( $channel, $message, $context );
290
291 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
292 $text = self::formatAsWfDebug(
293 $channel, "[{$channel}] {$message}", $context );
294
295 } else {
296 // Default formatting is wfDebugLog's historic style
297 $text = self::formatAsWfDebugLog( $channel, $message, $context );
298 }
299
300 // Append stacktrace of throwable if available
301 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
302 $e = $context['exception'];
303 $backtrace = false;
304
305 if ( $e instanceof Throwable ) {
306 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
307
308 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
309 // Throwable has already been unpacked as structured data
310 $backtrace = $e['trace'];
311 }
312
313 if ( $backtrace ) {
314 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
315 "\n";
316 }
317 }
318
319 return self::interpolate( $text, $context );
320 }
321
330 protected static function formatAsWfDebug( $channel, $message, $context ) {
331 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
332 if ( isset( $context['seconds_elapsed'] ) ) {
333 // Prepend elapsed request time and real memory usage with two
334 // trailing spaces.
335 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
336 }
337 if ( isset( $context['prefix'] ) ) {
338 $text = "{$context['prefix']}{$text}";
339 }
340 return "{$text}\n";
341 }
342
351 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
352 global $wgDBerrorLogTZ;
353 static $cachedTimezone = null;
354
355 if ( !$cachedTimezone ) {
356 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
357 }
358
359 $d = date_create( 'now', $cachedTimezone );
360 $date = $d->format( 'D M j G:i:s T Y' );
361
362 $host = wfHostname();
364
365 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
366 return $text;
367 }
368
377 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
378 $time = wfTimestamp( TS_DB );
380 $host = wfHostname();
381 $text = "{$time} {$host} {$wiki}: {$message}\n";
382 return $text;
383 }
384
392 public static function interpolate( $message, array $context ) {
393 if ( strpos( $message, '{' ) !== false ) {
394 $replace = [];
395 foreach ( $context as $key => $val ) {
396 $replace['{' . $key . '}'] = self::flatten( $val );
397 }
398 $message = strtr( $message, $replace );
399 }
400 return $message;
401 }
402
410 protected static function flatten( $item ) {
411 if ( $item === null ) {
412 return '[Null]';
413 }
414
415 if ( is_bool( $item ) ) {
416 return $item ? 'true' : 'false';
417 }
418
419 if ( is_float( $item ) ) {
420 if ( is_infinite( $item ) ) {
421 return ( $item > 0 ? '' : '-' ) . 'INF';
422 }
423 if ( is_nan( $item ) ) {
424 return 'NaN';
425 }
426 return (string)$item;
427 }
428
429 if ( is_scalar( $item ) ) {
430 return (string)$item;
431 }
432
433 if ( is_array( $item ) ) {
434 return '[Array(' . count( $item ) . ')]';
435 }
436
437 if ( $item instanceof \DateTime ) {
438 return $item->format( 'c' );
439 }
440
441 if ( $item instanceof Throwable ) {
442 $which = $item instanceof Error ? 'Error' : 'Exception';
443 return '[' . $which . ' ' . get_class( $item ) . '( ' .
444 $item->getFile() . ':' . $item->getLine() . ') ' .
445 $item->getMessage() . ']';
446 }
447
448 if ( is_object( $item ) ) {
449 if ( method_exists( $item, '__toString' ) ) {
450 return (string)$item;
451 }
452
453 return '[Object ' . get_class( $item ) . ']';
454 }
455
456 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
457 if ( is_resource( $item ) ) {
458 return '[Resource ' . get_resource_type( $item ) . ']';
459 }
460
461 return '[Unknown ' . gettype( $item ) . ']';
462 }
463
474 protected static function destination( $channel, $message, $context ) {
476
477 // Default destination is the debug log file as historically used by
478 // the wfDebug function.
479 $destination = $wgDebugLogFile;
480
481 if ( isset( $context['destination'] ) ) {
482 // Use destination explicitly provided in context
483 $destination = $context['destination'];
484
485 } elseif ( $channel === 'wfDebug' ) {
486 $destination = $wgDebugLogFile;
487
488 } elseif ( $channel === 'wfLogDBError' ) {
489 $destination = $wgDBerrorLog;
490
491 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
492 $logConfig = $wgDebugLogGroups[$channel];
493
494 if ( is_array( $logConfig ) ) {
495 $destination = $logConfig['destination'];
496 } else {
497 $destination = strval( $logConfig );
498 }
499 }
500
501 return $destination;
502 }
503
513 public static function emit( $text, $file ) {
514 if ( substr( $file, 0, 4 ) == 'udp:' ) {
515 $transport = UDPTransport::newFromString( $file );
516 $transport->emit( $text );
517 } else {
518 \Wikimedia\suppressWarnings();
519 $exists = file_exists( $file );
520 $size = $exists ? filesize( $file ) : false;
521 if ( !$exists ||
522 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
523 ) {
524 file_put_contents( $file, $text, FILE_APPEND );
525 }
526 \Wikimedia\restoreWarnings();
527 }
528 }
529
530}
$wgLogExceptionBacktrace
If true, send the exception backtrace to the error log.
$wgDBerrorLogTZ
Timezone to use in the error log.
$wgDBerrorLog
File to log database errors to.
$wgDebugToolbar
Display the new debugging toolbar.
$wgDebugLogGroups
Map of string log group names to log destinations.
$wgDebugLogFile
Filename for debug logging.
wfHostname()
Get host name of the current machine, for use in error reporting.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
New debugger system that outputs a toolbar on page view.
Definition MWDebug.php:33
static query( $sql, $function, $runTime, $dbhost)
Begins profiling on a database query.
Definition MWDebug.php:475
static debugMsg( $str, $context=[])
This is a method to pass messages from wfDebug to the pretty debugger.
Definition MWDebug.php:444
Handler class for MWExceptions.
static getRedactedTrace(Throwable $e)
Return a copy of a throwable's backtrace as an array.
static prettyPrintTrace(array $trace, $pad='')
Generate a string representation of a stacktrace.
PSR-3 logger that mimics the historic implementation of MediaWiki's former wfErrorLog logging impleme...
static flatten( $item)
Convert a logging context element to a string suitable for interpolation.
static formatAsWfDebugLog( $channel, $message, $context)
Format a message as `wfDebugLog() would have formatted it.
bool $isDB
Whether the channel is a DB channel.
int $minimumLevel
Minimum level.
static shouldEmit( $channel, $message, $level, $context)
Determine if the given message should be emitted or not.
log( $level, $message, array $context=[])
Logs with an arbitrary level.
static formatAsWfLogDBError( $channel, $message, $context)
Format a message as wfLogDBError() would have formatted it.
static interpolate( $message, array $context)
Interpolate placeholders in logging message.
static destination( $channel, $message, $context)
Select the appropriate log output destination for the given log event.
setMinimumForTest(?int $level)
Change an existing Logger singleton to act like NullLogger.
static emit( $text, $file)
Log to a file without getting "file size exceeded" signals.
static format( $channel, $message, $context)
Format a message.
static formatAsWfDebug( $channel, $message, $context)
Format a message as wfDebug() would have formatted it.
static $levelMapping
Convert \Psr\Log\LogLevel constants into int for sane comparisons These are the same values that Mono...
A generic class to send a message over UDP.
static newFromString( $info)
Helper tools for dealing with other locally-hosted wikis.
Definition WikiMap.php:29
static getCurrentWikiId()
Definition WikiMap.php:303
return true
Definition router.php:92
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42