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 Exception;
26 use MWDebug;
28 use Psr\Log\AbstractLogger;
29 use Psr\Log\LogLevel;
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 log( $level, $message, array $context = [] ) {
147  if ( is_string( $level ) ) {
148  $level = self::$levelMapping[$level];
149  }
150  if ( $level < $this->minimumLevel ) {
151  return;
152  }
153 
154  if ( $this->channel === 'DBQuery'
155  && $level === self::LEVEL_DEBUG
156  && isset( $context['sql'] )
157  ) {
158  // Also give the query information to the MWDebug tools
159  $enabled = MWDebug::query(
160  $context['sql'],
161  $context['method'],
162  $context['runtime'],
163  $context['db_host']
164  );
165  if ( $enabled ) {
166  // If we the toolbar was enabled, return early so that we don't
167  // also log the query to the main debug output.
168  return;
169  }
170  }
171 
172  // If this is a DB-related error, and the site has $wgDBerrorLog
173  // configured, rewrite the channel as wfLogDBError instead.
174  // Likewise, if the site does not use $wgDBerrorLog, it should
175  // configurable like any other channel via $wgDebugLogGroups
176  // or $wgMWLoggerDefaultSpi.
177  global $wgDBerrorLog;
178  if ( $this->isDB && $level >= self::LEVEL_ERROR && $wgDBerrorLog ) {
179  // Format and write DB errors to the legacy locations
180  $effectiveChannel = 'wfLogDBError';
181  } else {
182  $effectiveChannel = $this->channel;
183  }
184 
185  if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
186  $text = self::format( $effectiveChannel, $message, $context );
187  $destination = self::destination( $effectiveChannel, $message, $context );
188  self::emit( $text, $destination );
189  }
190  if ( !isset( $context['private'] ) || !$context['private'] ) {
191  // Add to debug toolbar if not marked as "private"
192  MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
193  }
194  }
195 
206  public static function shouldEmit( $channel, $message, $level, $context ) {
208 
209  if ( is_string( $level ) ) {
210  $level = self::$levelMapping[$level];
211  }
212 
213  if ( $channel === 'wfLogDBError' ) {
214  // wfLogDBError messages are emitted if a database log location is
215  // specfied.
216  $shouldEmit = (bool)$wgDBerrorLog;
217 
218  } elseif ( $channel === 'wfDebug' ) {
219  // wfDebug messages are emitted if a catch all logging file has
220  // been specified. Checked explicitly so that 'private' flagged
221  // messages are not discarded by unset $wgDebugLogGroups channel
222  // handling below.
223  $shouldEmit = $wgDebugLogFile != '';
224 
225  } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
226  $logConfig = $wgDebugLogGroups[$channel];
227 
228  if ( is_array( $logConfig ) ) {
229  $shouldEmit = true;
230  if ( isset( $logConfig['sample'] ) ) {
231  // Emit randomly with a 1 in 'sample' chance for each message.
232  $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
233  }
234 
235  if ( isset( $logConfig['level'] ) ) {
236  $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
237  }
238  } else {
239  // Emit unless the config value is explictly false.
240  $shouldEmit = $logConfig !== false;
241  }
242 
243  } elseif ( isset( $context['private'] ) && $context['private'] ) {
244  // Don't emit if the message didn't match previous checks based on
245  // the channel and the event is marked as private. This check
246  // discards messages sent via wfDebugLog() with dest == 'private'
247  // and no explicit wgDebugLogGroups configuration.
248  $shouldEmit = false;
249  } else {
250  // Default return value is the same as the historic wfDebug
251  // method: emit if $wgDebugLogFile has been set.
252  $shouldEmit = $wgDebugLogFile != '';
253  }
254 
255  return $shouldEmit;
256  }
257 
270  public static function format( $channel, $message, $context ) {
272 
273  if ( $channel === 'wfDebug' ) {
274  $text = self::formatAsWfDebug( $channel, $message, $context );
275 
276  } elseif ( $channel === 'wfLogDBError' ) {
277  $text = self::formatAsWfLogDBError( $channel, $message, $context );
278 
279  } elseif ( $channel === 'profileoutput' ) {
280  // Legacy wfLogProfilingData formatitng
281  $forward = '';
282  if ( isset( $context['forwarded_for'] ) ) {
283  $forward = " forwarded for {$context['forwarded_for']}";
284  }
285  if ( isset( $context['client_ip'] ) ) {
286  $forward .= " client IP {$context['client_ip']}";
287  }
288  if ( isset( $context['from'] ) ) {
289  $forward .= " from {$context['from']}";
290  }
291  if ( $forward ) {
292  $forward = "\t(proxied via {$context['proxy']}{$forward})";
293  }
294  if ( $context['anon'] ) {
295  $forward .= ' anon';
296  }
297  if ( !isset( $context['url'] ) ) {
298  $context['url'] = 'n/a';
299  }
300 
301  $log = sprintf( "%s\t%04.3f\t%s%s\n",
302  gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
303 
304  $text = self::formatAsWfDebugLog(
305  $channel, $log . $context['output'], $context );
306 
307  } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
308  $text = self::formatAsWfDebug(
309  $channel, "[{$channel}] {$message}", $context );
310 
311  } else {
312  // Default formatting is wfDebugLog's historic style
313  $text = self::formatAsWfDebugLog( $channel, $message, $context );
314  }
315 
316  // Append stacktrace of exception if available
317  if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
318  $e = $context['exception'];
319  $backtrace = false;
320 
321  if ( $e instanceof Throwable || $e instanceof Exception ) {
322  $backtrace = MWExceptionHandler::getRedactedTrace( $e );
323 
324  } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
325  // Exception has already been unpacked as structured data
326  $backtrace = $e['trace'];
327  }
328 
329  if ( $backtrace ) {
330  $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
331  "\n";
332  }
333  }
334 
335  return self::interpolate( $text, $context );
336  }
337 
346  protected static function formatAsWfDebug( $channel, $message, $context ) {
347  $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
348  if ( isset( $context['seconds_elapsed'] ) ) {
349  // Prepend elapsed request time and real memory usage with two
350  // trailing spaces.
351  $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
352  }
353  if ( isset( $context['prefix'] ) ) {
354  $text = "{$context['prefix']}{$text}";
355  }
356  return "{$text}\n";
357  }
358 
367  protected static function formatAsWfLogDBError( $channel, $message, $context ) {
368  global $wgDBerrorLogTZ;
369  static $cachedTimezone = null;
370 
371  if ( !$cachedTimezone ) {
372  $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
373  }
374 
375  $d = date_create( 'now', $cachedTimezone );
376  $date = $d->format( 'D M j G:i:s T Y' );
377 
378  $host = wfHostname();
380 
381  $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
382  return $text;
383  }
384 
393  protected static function formatAsWfDebugLog( $channel, $message, $context ) {
394  $time = wfTimestamp( TS_DB );
396  $host = wfHostname();
397  $text = "{$time} {$host} {$wiki}: {$message}\n";
398  return $text;
399  }
400 
408  public static function interpolate( $message, array $context ) {
409  if ( strpos( $message, '{' ) !== false ) {
410  $replace = [];
411  foreach ( $context as $key => $val ) {
412  $replace['{' . $key . '}'] = self::flatten( $val );
413  }
414  $message = strtr( $message, $replace );
415  }
416  return $message;
417  }
418 
426  protected static function flatten( $item ) {
427  if ( $item === null ) {
428  return '[Null]';
429  }
430 
431  if ( is_bool( $item ) ) {
432  return $item ? 'true' : 'false';
433  }
434 
435  if ( is_float( $item ) ) {
436  if ( is_infinite( $item ) ) {
437  return ( $item > 0 ? '' : '-' ) . 'INF';
438  }
439  if ( is_nan( $item ) ) {
440  return 'NaN';
441  }
442  return (string)$item;
443  }
444 
445  if ( is_scalar( $item ) ) {
446  return (string)$item;
447  }
448 
449  if ( is_array( $item ) ) {
450  return '[Array(' . count( $item ) . ')]';
451  }
452 
453  if ( $item instanceof \DateTime ) {
454  return $item->format( 'c' );
455  }
456 
457  if ( $item instanceof Throwable || $item instanceof Exception ) {
458  $which = $item instanceof Error ? 'Error' : 'Exception';
459  return '[' . $which . ' ' . get_class( $item ) . '( ' .
460  $item->getFile() . ':' . $item->getLine() . ') ' .
461  $item->getMessage() . ']';
462  }
463 
464  if ( is_object( $item ) ) {
465  if ( method_exists( $item, '__toString' ) ) {
466  return (string)$item;
467  }
468 
469  return '[Object ' . get_class( $item ) . ']';
470  }
471 
472  if ( is_resource( $item ) ) {
473  return '[Resource ' . get_resource_type( $item ) . ']';
474  }
475 
476  return '[Unknown ' . gettype( $item ) . ']';
477  }
478 
489  protected static function destination( $channel, $message, $context ) {
491 
492  // Default destination is the debug log file as historically used by
493  // the wfDebug function.
494  $destination = $wgDebugLogFile;
495 
496  if ( isset( $context['destination'] ) ) {
497  // Use destination explicitly provided in context
498  $destination = $context['destination'];
499 
500  } elseif ( $channel === 'wfDebug' ) {
501  $destination = $wgDebugLogFile;
502 
503  } elseif ( $channel === 'wfLogDBError' ) {
504  $destination = $wgDBerrorLog;
505 
506  } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
507  $logConfig = $wgDebugLogGroups[$channel];
508 
509  if ( is_array( $logConfig ) ) {
510  $destination = $logConfig['destination'];
511  } else {
512  $destination = strval( $logConfig );
513  }
514  }
515 
516  return $destination;
517  }
518 
528  public static function emit( $text, $file ) {
529  if ( substr( $file, 0, 4 ) == 'udp:' ) {
530  $transport = UDPTransport::newFromString( $file );
531  $transport->emit( $text );
532  } else {
533  \Wikimedia\suppressWarnings();
534  $exists = file_exists( $file );
535  $size = $exists ? filesize( $file ) : false;
536  if ( !$exists ||
537  ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
538  ) {
539  file_put_contents( $file, $text, FILE_APPEND );
540  }
541  \Wikimedia\restoreWarnings();
542  }
543  }
544 
545 }
MWDebug\query
static query( $sql, $function, $runTime, $dbhost)
Begins profiling on a database query.
Definition: MWDebug.php:378
MediaWiki\Logger\LegacyLogger\interpolate
static interpolate( $message, array $context)
Interpolate placeholders in logging message.
Definition: LegacyLogger.php:408
UDPTransport\newFromString
static newFromString( $info)
Definition: UDPTransport.php:54
MWExceptionHandler\getRedactedTrace
static getRedactedTrace( $e)
Return a copy of an exception's backtrace as an array.
Definition: MWExceptionHandler.php:401
WikiMap\getCurrentWikiDbDomain
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
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:426
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:489
true
return true
Definition: router.php:92
MWExceptionHandler
Handler class for MWExceptions.
Definition: MWExceptionHandler.php:30
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1871
MediaWiki\Logger\LegacyLogger\log
log( $level, $message, array $context=[])
Logs with an arbitrary level.
Definition: LegacyLogger.php:146
$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()
Fetch server name for use in error reporting etc.
Definition: GlobalFunctions.php:1325
MediaWiki\Logger\LegacyLogger\LEVEL_WARNING
const LEVEL_WARNING
Definition: LegacyLogger.php:61
MediaWiki\Logger\LegacyLogger\LEVEL_INFO
const LEVEL_INFO
Definition: LegacyLogger.php:59
MediaWiki\Logger\LegacyLogger\LEVEL_CRITICAL
const LEVEL_CRITICAL
Definition: LegacyLogger.php:63
$wgDBerrorLog
$wgDBerrorLog
File to log database errors to.
Definition: DefaultSettings.php:2133
MediaWiki\Logger\LegacyLogger\formatAsWfDebugLog
static formatAsWfDebugLog( $channel, $message, $context)
Format a message as `wfDebugLog() would have formatted it.
Definition: LegacyLogger.php:393
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:354
MediaWiki\Logger
Definition: ConsoleLogger.php:3
WikiMap\getWikiIdFromDbDomain
static getWikiIdFromDbDomain( $domain)
Get the wiki ID of a database domain.
Definition: WikiMap.php:269
MWDebug\debugMsg
static debugMsg( $str, $context=[])
This is a method to pass messages from wfDebug to the pretty debugger.
Definition: MWDebug.php:347
$wgDebugLogGroups
$wgDebugLogGroups
Map of string log group names to log destinations.
Definition: DefaultSettings.php:6241
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:6319
MediaWiki\Logger\LegacyLogger\LEVEL_ERROR
const LEVEL_ERROR
Definition: LegacyLogger.php:62
$wgDebugLogFile
$wgDebugLogFile
Filename for debug logging.
Definition: DefaultSettings.php:6113
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:346
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:528
MediaWiki\Logger\LegacyLogger\format
static format( $channel, $message, $context)
Format a message.
Definition: LegacyLogger.php:270
MediaWiki\Logger\LegacyLogger\formatAsWfLogDBError
static formatAsWfLogDBError( $channel, $message, $context)
Format a message as wfLogDBError() would have formatted it.
Definition: LegacyLogger.php:367
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:2153
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:6483
MediaWiki\$context
IContextSource $context
Definition: MediaWiki.php:37
MediaWiki\Logger\LegacyLogger\shouldEmit
static shouldEmit( $channel, $message, $level, $context)
Determine if the given message should be emitted or not.
Definition: LegacyLogger.php:206
MediaWiki\Logger\LegacyLogger\$minimumLevel
int $minimumLevel
Minimum level.
Definition: LegacyLogger.php:99