MediaWiki 1.41.2
LegacyLogger.php
Go to the documentation of this file.
1<?php
21namespace MediaWiki\Logger;
22
23use DateTimeZone;
24use Error;
25use LogicException;
27use MWDebug;
29use Psr\Log\AbstractLogger;
30use Psr\Log\LogLevel;
31use Throwable;
32use UDPTransport;
33use Wikimedia\AtEase\AtEase;
34
52class LegacyLogger extends AbstractLogger {
53
57 protected $channel;
58
59 private const LEVEL_DEBUG = 100;
60 private const LEVEL_INFO = 200;
61 private const LEVEL_NOTICE = 250;
62 private const LEVEL_WARNING = 300;
63 private const LEVEL_ERROR = 400;
64 private const LEVEL_CRITICAL = 500;
65 private const LEVEL_ALERT = 550;
66 private const LEVEL_EMERGENCY = 600;
67 private const LEVEL_INFINITY = 999;
68
75 protected static $levelMapping = [
76 LogLevel::DEBUG => self::LEVEL_DEBUG,
77 LogLevel::INFO => self::LEVEL_INFO,
78 LogLevel::NOTICE => self::LEVEL_NOTICE,
79 LogLevel::WARNING => self::LEVEL_WARNING,
80 LogLevel::ERROR => self::LEVEL_ERROR,
81 LogLevel::CRITICAL => self::LEVEL_CRITICAL,
82 LogLevel::ALERT => self::LEVEL_ALERT,
83 LogLevel::EMERGENCY => self::LEVEL_EMERGENCY,
84 ];
85
92 private $minimumLevel;
93
99 private $isDB;
100
104 public function __construct( $channel ) {
106
107 $this->channel = $channel;
108 $this->isDB = ( $channel === 'rdbms' );
109
110 // Calculate minimum level, duplicating some of the logic from log() and shouldEmit()
111 if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
112 $this->minimumLevel = self::LEVEL_WARNING;
113 } elseif ( $wgDebugLogFile != '' || $wgDebugToolbar ) {
114 // Log all messages if there is a debug log file or debug toolbar
115 $this->minimumLevel = self::LEVEL_DEBUG;
116 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
117 $logConfig = $wgDebugLogGroups[$channel];
118 // Log messages if the config is set, according to the configured level
119 if ( is_array( $logConfig ) && isset( $logConfig['level'] ) ) {
120 $this->minimumLevel = self::$levelMapping[$logConfig['level']];
121 } else {
122 $this->minimumLevel = self::LEVEL_DEBUG;
123 }
124 } else {
125 // No other case hit: discard all messages
126 $this->minimumLevel = self::LEVEL_INFINITY;
127 }
128
129 if ( $this->isDB && $wgDBerrorLog && $this->minimumLevel > self::LEVEL_ERROR ) {
130 // Log DB errors if there is a DB error log
131 $this->minimumLevel = self::LEVEL_ERROR;
132 }
133 }
134
142 public function setMinimumForTest( ?int $level ) {
143 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
144 throw new LogicException( 'Not allowed outside tests' );
145 }
146 // Set LEVEL_INFINITY if given null, or restore the original level.
147 $original = $this->minimumLevel;
148 $this->minimumLevel = $level ?? self::LEVEL_INFINITY;
149 return $original;
150 }
151
159 public function log( $level, $message, array $context = [] ) {
160 if ( is_string( $level ) ) {
161 $level = self::$levelMapping[$level];
162 }
163 if ( $level < $this->minimumLevel ) {
164 return;
165 }
166
167 if ( $this->isDB
168 && $level === self::LEVEL_DEBUG
169 && isset( $context['sql'] )
170 ) {
171 // Also give the query information to the MWDebug tools
173 $context['sql'],
174 $context['method'],
175 $context['runtime'],
176 $context['db_server']
177 );
178 }
179
180 // If this is a DB-related error, and the site has $wgDBerrorLog
181 // configured, rewrite the channel as wfLogDBError instead.
182 // Likewise, if the site does not use $wgDBerrorLog, it should
183 // configurable like any other channel via $wgDebugLogGroups
184 // or $wgMWLoggerDefaultSpi.
185 global $wgDBerrorLog;
186 if ( $this->isDB && $level >= self::LEVEL_ERROR && $wgDBerrorLog ) {
187 // Format and write DB errors to the legacy locations
188 $effectiveChannel = 'wfLogDBError';
189 } else {
190 $effectiveChannel = $this->channel;
191 }
192
193 if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
194 $text = self::format( $effectiveChannel, $message, $context );
195 $destination = self::destination( $effectiveChannel, $message, $context );
196 self::emit( $text, $destination );
197 }
198 if ( !isset( $context['private'] ) || !$context['private'] ) {
199 // Add to debug toolbar if not marked as "private"
200 MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
201 }
202 }
203
214 public static function shouldEmit( $channel, $message, $level, $context ) {
216
217 if ( is_string( $level ) ) {
218 $level = self::$levelMapping[$level];
219 }
220
221 if ( $channel === 'wfLogDBError' ) {
222 // wfLogDBError messages are emitted if a database log location is
223 // specified.
224 $shouldEmit = (bool)$wgDBerrorLog;
225
226 } elseif ( $channel === 'wfDebug' ) {
227 // wfDebug messages are emitted if a catch all logging file has
228 // been specified. Checked explicitly so that 'private' flagged
229 // messages are not discarded by unset $wgDebugLogGroups channel
230 // handling below.
231 $shouldEmit = $wgDebugLogFile != '';
232
233 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
234 $logConfig = $wgDebugLogGroups[$channel];
235
236 if ( is_array( $logConfig ) ) {
237 $shouldEmit = true;
238 if ( isset( $logConfig['sample'] ) ) {
239 // Emit randomly with a 1 in 'sample' chance for each message.
240 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
241 }
242
243 if ( isset( $logConfig['level'] ) ) {
244 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
245 }
246 } else {
247 // Emit unless the config value is explicitly false.
248 $shouldEmit = $logConfig !== false;
249 }
250
251 } elseif ( isset( $context['private'] ) && $context['private'] ) {
252 // Don't emit if the message didn't match previous checks based on
253 // the channel and the event is marked as private. This check
254 // discards messages sent via wfDebugLog() with dest == 'private'
255 // and no explicit wgDebugLogGroups configuration.
256 $shouldEmit = false;
257 } else {
258 // Default return value is the same as the historic wfDebug
259 // method: emit if $wgDebugLogFile has been set.
260 $shouldEmit = $wgDebugLogFile != '';
261 }
262
263 return $shouldEmit;
264 }
265
278 public static function format( $channel, $message, $context ) {
280
281 if ( $channel === 'wfDebug' ) {
282 $text = self::formatAsWfDebug( $channel, $message, $context );
283
284 } elseif ( $channel === 'wfLogDBError' ) {
285 $text = self::formatAsWfLogDBError( $channel, $message, $context );
286
287 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
288 $text = self::formatAsWfDebug(
289 $channel, "[{$channel}] {$message}", $context );
290
291 } else {
292 // Default formatting is wfDebugLog's historic style
293 $text = self::formatAsWfDebugLog( $channel, $message, $context );
294 }
295
296 // Append stacktrace of throwable if available
297 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
298 $e = $context['exception'];
299 $backtrace = false;
300
301 if ( $e instanceof Throwable ) {
302 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
303
304 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
305 // Throwable has already been unpacked as structured data
306 $backtrace = $e['trace'];
307 }
308
309 if ( $backtrace ) {
310 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
311 "\n";
312 }
313 }
314
315 return self::interpolate( $text, $context );
316 }
317
326 protected static function formatAsWfDebug( $channel, $message, $context ) {
327 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
328 if ( isset( $context['seconds_elapsed'] ) ) {
329 // Prepend elapsed request time and real memory usage with two
330 // trailing spaces.
331 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
332 }
333 if ( isset( $context['prefix'] ) ) {
334 $text = "{$context['prefix']}{$text}";
335 }
336 return "{$text}\n";
337 }
338
347 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
348 global $wgDBerrorLogTZ;
349 static $cachedTimezone = null;
350
351 if ( !$cachedTimezone ) {
352 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
353 }
354
355 $d = date_create( 'now', $cachedTimezone );
356 $date = $d->format( 'D M j G:i:s T Y' );
357
358 $host = wfHostname();
359 $wiki = WikiMap::getCurrentWikiId();
360
361 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
362 return $text;
363 }
364
373 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
374 $time = wfTimestamp( TS_DB );
375 $wiki = WikiMap::getCurrentWikiId();
376 $host = wfHostname();
377 $text = "{$time} {$host} {$wiki}: {$message}\n";
378 return $text;
379 }
380
388 public static function interpolate( $message, array $context ) {
389 if ( str_contains( $message, '{' ) ) {
390 $replace = [];
391 foreach ( $context as $key => $val ) {
392 $replace['{' . $key . '}'] = self::flatten( $val );
393 }
394 $message = strtr( $message, $replace );
395 }
396 return $message;
397 }
398
406 protected static function flatten( $item ) {
407 if ( $item === null ) {
408 return '[Null]';
409 }
410
411 if ( is_bool( $item ) ) {
412 return $item ? 'true' : 'false';
413 }
414
415 if ( is_float( $item ) ) {
416 if ( is_infinite( $item ) ) {
417 return ( $item > 0 ? '' : '-' ) . 'INF';
418 }
419 if ( is_nan( $item ) ) {
420 return 'NaN';
421 }
422 return (string)$item;
423 }
424
425 if ( is_scalar( $item ) ) {
426 return (string)$item;
427 }
428
429 if ( is_array( $item ) ) {
430 return '[Array(' . count( $item ) . ')]';
431 }
432
433 if ( $item instanceof \DateTime ) {
434 return $item->format( 'c' );
435 }
436
437 if ( $item instanceof Throwable ) {
438 $which = $item instanceof Error ? 'Error' : 'Exception';
439 return '[' . $which . ' ' . get_class( $item ) . '( ' .
440 $item->getFile() . ':' . $item->getLine() . ') ' .
441 $item->getMessage() . ']';
442 }
443
444 if ( is_object( $item ) ) {
445 if ( method_exists( $item, '__toString' ) ) {
446 return (string)$item;
447 }
448
449 return '[Object ' . get_class( $item ) . ']';
450 }
451
452 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
453 if ( is_resource( $item ) ) {
454 return '[Resource ' . get_resource_type( $item ) . ']';
455 }
456
457 return '[Unknown ' . gettype( $item ) . ']';
458 }
459
470 protected static function destination( $channel, $message, $context ) {
472
473 // Default destination is the debug log file as historically used by
474 // the wfDebug function.
475 $destination = $wgDebugLogFile;
476
477 if ( isset( $context['destination'] ) ) {
478 // Use destination explicitly provided in context
479 $destination = $context['destination'];
480
481 } elseif ( $channel === 'wfDebug' ) {
482 $destination = $wgDebugLogFile;
483
484 } elseif ( $channel === 'wfLogDBError' ) {
485 $destination = $wgDBerrorLog;
486
487 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
488 $logConfig = $wgDebugLogGroups[$channel];
489
490 if ( is_array( $logConfig ) ) {
491 $destination = $logConfig['destination'];
492 } else {
493 $destination = strval( $logConfig );
494 }
495 }
496
497 return $destination;
498 }
499
509 public static function emit( $text, $file ) {
510 if ( str_starts_with( $file, 'udp:' ) ) {
511 $transport = UDPTransport::newFromString( $file );
512 $transport->emit( $text );
513 } else {
514 AtEase::suppressWarnings();
515 $exists = file_exists( $file );
516 $size = $exists ? filesize( $file ) : false;
517 if ( !$exists ||
518 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
519 ) {
520 file_put_contents( $file, $text, FILE_APPEND );
521 }
522 AtEase::restoreWarnings();
523 }
524 }
525
526}
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
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.
Debug toolbar.
Definition MWDebug.php:41
static query( $sql, $function, $runTime, $dbhost)
Begins profiling on a database query.
Definition MWDebug.php:557
static debugMsg( $str, $context=[])
This is a method to pass messages from wfDebug to the pretty debugger.
Definition MWDebug.php:526
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.
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 array $levelMapping
Convert \Psr\Log\LogLevel constants into int for sensible comparisons These are the same values that ...
Tools for dealing with other locally-hosted wikis.
Definition WikiMap.php:31
A generic class to send a message over UDP.
static newFromString( $info)
$wgLogExceptionBacktrace
Config variable stub for the LogExceptionBacktrace setting, for use by phpdoc and IDEs.
$wgDBerrorLogTZ
Config variable stub for the DBerrorLogTZ setting, for use by phpdoc and IDEs.
$wgDBerrorLog
Config variable stub for the DBerrorLog setting, for use by phpdoc and IDEs.
$wgDebugRawPage
Config variable stub for the DebugRawPage setting, for use by phpdoc and IDEs.
$wgDebugToolbar
Config variable stub for the DebugToolbar setting, for use by phpdoc and IDEs.
$wgDebugLogGroups
Config variable stub for the DebugLogGroups setting, for use by phpdoc and IDEs.
$wgDebugLogFile
Config variable stub for the DebugLogFile setting, for use by phpdoc and IDEs.
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition router.php:42