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 MWDebug;
27 use Psr\Log\AbstractLogger;
28 use Psr\Log\LogLevel;
29 use RuntimeException;
30 use Throwable;
31 use UDPTransport;
32 use WikiMap;
33 
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 
88  protected static $dbChannels = [
89  'DBQuery' => true,
90  'DBConnection' => true
91  ];
92 
99  private $minimumLevel;
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();
363  $wiki = WikiMap::getCurrentWikiId();
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 );
379  $wiki = WikiMap::getCurrentWikiId();
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  if ( is_resource( $item ) ) {
457  return '[Resource ' . get_resource_type( $item ) . ']';
458  }
459 
460  return '[Unknown ' . gettype( $item ) . ']';
461  }
462 
473  protected static function destination( $channel, $message, $context ) {
475 
476  // Default destination is the debug log file as historically used by
477  // the wfDebug function.
478  $destination = $wgDebugLogFile;
479 
480  if ( isset( $context['destination'] ) ) {
481  // Use destination explicitly provided in context
482  $destination = $context['destination'];
483 
484  } elseif ( $channel === 'wfDebug' ) {
485  $destination = $wgDebugLogFile;
486 
487  } elseif ( $channel === 'wfLogDBError' ) {
488  $destination = $wgDBerrorLog;
489 
490  } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
491  $logConfig = $wgDebugLogGroups[$channel];
492 
493  if ( is_array( $logConfig ) ) {
494  $destination = $logConfig['destination'];
495  } else {
496  $destination = strval( $logConfig );
497  }
498  }
499 
500  return $destination;
501  }
502 
512  public static function emit( $text, $file ) {
513  if ( substr( $file, 0, 4 ) == 'udp:' ) {
514  $transport = UDPTransport::newFromString( $file );
515  $transport->emit( $text );
516  } else {
517  \Wikimedia\suppressWarnings();
518  $exists = file_exists( $file );
519  $size = $exists ? filesize( $file ) : false;
520  if ( !$exists ||
521  ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
522  ) {
523  file_put_contents( $file, $text, FILE_APPEND );
524  }
525  \Wikimedia\restoreWarnings();
526  }
527  }
528 
529 }
MWDebug\query
static query( $sql, $function, $runTime, $dbhost)
Begins profiling on a database query.
Definition: MWDebug.php:497
MediaWiki\Logger\LegacyLogger\interpolate
static interpolate( $message, array $context)
Interpolate placeholders in logging message.
Definition: LegacyLogger.php:392
MediaWiki\Logger\LegacyLogger\setMinimumForTest
setMinimumForTest(?int $level)
Change an existing Logger singleton to act like NullLogger.
Definition: LegacyLogger.php:146
UDPTransport\newFromString
static newFromString( $info)
Definition: UDPTransport.php:56
MediaWiki\Logger\LegacyLogger\$levelMapping
static $levelMapping
Convert \Psr\Log\LogLevel constants into int for sane comparisons These are the same values that Mono...
Definition: LegacyLogger.php:74
MediaWiki\Logger\LegacyLogger\flatten
static flatten( $item)
Convert a logging context element to a string suitable for interpolation.
Definition: LegacyLogger.php:410
MWDebug
New debugger system that outputs a toolbar on page view.
Definition: MWDebug.php:33
MediaWiki\Logger\LegacyLogger\$dbChannels
static array $dbChannels
Definition: LegacyLogger.php:88
MediaWiki\Logger\LegacyLogger\LEVEL_ALERT
const LEVEL_ALERT
Definition: LegacyLogger.php:64
MediaWiki\Logger\LegacyLogger\destination
static destination( $channel, $message, $context)
Select the appropriate log output destination for the given log event.
Definition: LegacyLogger.php:473
true
return true
Definition: router.php:90
MWExceptionHandler
Handler class for MWExceptions.
Definition: MWExceptionHandler.php:31
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1815
MediaWiki\Logger\LegacyLogger\log
log( $level, $message, array $context=[])
Logs with an arbitrary level.
Definition: LegacyLogger.php:163
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
Definition: GlobalFunctions.php:1283
MediaWiki\Logger\LegacyLogger\LEVEL_WARNING
const LEVEL_WARNING
Definition: LegacyLogger.php:61
MediaWiki\Logger\LegacyLogger\LEVEL_INFO
const LEVEL_INFO
Definition: LegacyLogger.php:59
WikiMap\getCurrentWikiId
static getCurrentWikiId()
Definition: WikiMap.php:303
MediaWiki\Logger\LegacyLogger\LEVEL_CRITICAL
const LEVEL_CRITICAL
Definition: LegacyLogger.php:63
$wgDBerrorLog
$wgDBerrorLog
File to log database errors to.
Definition: DefaultSettings.php:2240
MediaWiki\Logger\LegacyLogger\formatAsWfDebugLog
static formatAsWfDebugLog( $channel, $message, $context)
Format a message as `wfDebugLog() would have formatted it.
Definition: LegacyLogger.php:377
MediaWiki\Logger\LegacyLogger\$channel
string $channel
Definition: LegacyLogger.php:56
MWExceptionHandler\prettyPrintTrace
static prettyPrintTrace(array $trace, $pad='')
Generate a string representation of a stacktrace.
Definition: MWExceptionHandler.php:376
MediaWiki\Logger
Definition: ConsoleLogger.php:3
MWDebug\debugMsg
static debugMsg( $str, $context=[])
This is a method to pass messages from wfDebug to the pretty debugger.
Definition: MWDebug.php:466
$wgDebugLogGroups
$wgDebugLogGroups
Map of string log group names to log destinations.
Definition: DefaultSettings.php:6694
MediaWiki\Logger\LegacyLogger\LEVEL_EMERGENCY
const LEVEL_EMERGENCY
Definition: LegacyLogger.php:65
$wgLogExceptionBacktrace
$wgLogExceptionBacktrace
If true, send the exception backtrace to the error log.
Definition: DefaultSettings.php:6766
MediaWiki\Logger\LegacyLogger\LEVEL_ERROR
const LEVEL_ERROR
Definition: LegacyLogger.php:62
$wgDebugLogFile
$wgDebugLogFile
Filename for debug logging.
Definition: DefaultSettings.php:6566
MediaWiki\Logger\LegacyLogger\$isDB
bool $isDB
Whether the channel is a DB channel.
Definition: LegacyLogger.php:106
UDPTransport
A generic class to send a message over UDP.
Definition: UDPTransport.php:33
MediaWiki\Logger\LegacyLogger\LEVEL_DEBUG
const LEVEL_DEBUG
Definition: LegacyLogger.php:58
MediaWiki\Logger\LegacyLogger\LEVEL_INFINITY
const LEVEL_INFINITY
Definition: LegacyLogger.php:66
MediaWiki\Logger\LegacyLogger\formatAsWfDebug
static formatAsWfDebug( $channel, $message, $context)
Format a message as wfDebug() would have formatted it.
Definition: LegacyLogger.php:330
WikiMap
Helper tools for dealing with other locally-hosted wikis.
Definition: WikiMap.php:29
MediaWiki\Logger\LegacyLogger\emit
static emit( $text, $file)
Log to a file without getting "file size exceeded" signals.
Definition: LegacyLogger.php:512
MediaWiki\Logger\LegacyLogger\format
static format( $channel, $message, $context)
Format a message.
Definition: LegacyLogger.php:282
MediaWiki\Logger\LegacyLogger\formatAsWfLogDBError
static formatAsWfLogDBError( $channel, $message, $context)
Format a message as wfLogDBError() would have formatted it.
Definition: LegacyLogger.php:351
MediaWiki\Logger\LegacyLogger
PSR-3 logger that mimics the historic implementation of MediaWiki's former wfErrorLog logging impleme...
Definition: LegacyLogger.php:51
$wgDBerrorLogTZ
$wgDBerrorLogTZ
Timezone to use in the error log.
Definition: DefaultSettings.php:2260
MediaWiki\Logger\LegacyLogger\__construct
__construct( $channel)
Definition: LegacyLogger.php:111
MediaWiki\Logger\LegacyLogger\LEVEL_NOTICE
const LEVEL_NOTICE
Definition: LegacyLogger.php:60
$wgDebugToolbar
$wgDebugToolbar
Display the new debugging toolbar.
Definition: DefaultSettings.php:6925
MediaWiki\$context
IContextSource $context
Definition: MediaWiki.php:40
MediaWiki\Logger\LegacyLogger\shouldEmit
static shouldEmit( $channel, $message, $level, $context)
Determine if the given message should be emitted or not.
Definition: LegacyLogger.php:218
MediaWiki\Logger\LegacyLogger\$minimumLevel
int $minimumLevel
Minimum level.
Definition: LegacyLogger.php:99
MWExceptionHandler\getRedactedTrace
static getRedactedTrace(Throwable $e)
Return a copy of a throwable's backtrace as an array.
Definition: MWExceptionHandler.php:423