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