MediaWiki REL1_39
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;
33use Wikimedia\AtEase\AtEase;
34
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
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 ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
119 $this->minimumLevel = self::LEVEL_WARNING;
120 } elseif ( $wgDebugLogFile != '' || $wgDebugToolbar ) {
121 // Log all messages if there is a debug log file or debug toolbar
122 $this->minimumLevel = self::LEVEL_DEBUG;
123 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
124 $logConfig = $wgDebugLogGroups[$channel];
125 // Log messages if the config is set, according to the configured level
126 if ( is_array( $logConfig ) && isset( $logConfig['level'] ) ) {
127 $this->minimumLevel = self::$levelMapping[$logConfig['level']];
128 } else {
129 $this->minimumLevel = self::LEVEL_DEBUG;
130 }
131 } else {
132 // No other case hit: discard all messages
133 $this->minimumLevel = self::LEVEL_INFINITY;
134 }
135
136 if ( $this->isDB && $wgDBerrorLog && $this->minimumLevel > self::LEVEL_ERROR ) {
137 // Log DB errors if there is a DB error log
138 $this->minimumLevel = self::LEVEL_ERROR;
139 }
140 }
141
149 public function setMinimumForTest( ?int $level ) {
150 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
151 throw new RuntimeException( 'Not allowed outside tests' );
152 }
153 // Set LEVEL_INFINITY if given null, or restore the original level.
154 $original = $this->minimumLevel;
155 $this->minimumLevel = $level ?? self::LEVEL_INFINITY;
156 return $original;
157 }
158
166 public function log( $level, $message, array $context = [] ) {
167 if ( is_string( $level ) ) {
168 $level = self::$levelMapping[$level];
169 }
170 if ( $level < $this->minimumLevel ) {
171 return;
172 }
173
174 if ( $this->channel === 'DBQuery'
175 && $level === self::LEVEL_DEBUG
176 && isset( $context['sql'] )
177 ) {
178 // Also give the query information to the MWDebug tools
180 $context['sql'],
181 $context['method'],
182 $context['runtime'],
183 $context['db_server']
184 );
185 }
186
187 // If this is a DB-related error, and the site has $wgDBerrorLog
188 // configured, rewrite the channel as wfLogDBError instead.
189 // Likewise, if the site does not use $wgDBerrorLog, it should
190 // configurable like any other channel via $wgDebugLogGroups
191 // or $wgMWLoggerDefaultSpi.
192 global $wgDBerrorLog;
193 if ( $this->isDB && $level >= self::LEVEL_ERROR && $wgDBerrorLog ) {
194 // Format and write DB errors to the legacy locations
195 $effectiveChannel = 'wfLogDBError';
196 } else {
197 $effectiveChannel = $this->channel;
198 }
199
200 if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
201 $text = self::format( $effectiveChannel, $message, $context );
202 $destination = self::destination( $effectiveChannel, $message, $context );
203 self::emit( $text, $destination );
204 }
205 if ( !isset( $context['private'] ) || !$context['private'] ) {
206 // Add to debug toolbar if not marked as "private"
207 MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
208 }
209 }
210
221 public static function shouldEmit( $channel, $message, $level, $context ) {
223
224 if ( is_string( $level ) ) {
225 $level = self::$levelMapping[$level];
226 }
227
228 if ( $channel === 'wfLogDBError' ) {
229 // wfLogDBError messages are emitted if a database log location is
230 // specified.
231 $shouldEmit = (bool)$wgDBerrorLog;
232
233 } elseif ( $channel === 'wfDebug' ) {
234 // wfDebug messages are emitted if a catch all logging file has
235 // been specified. Checked explicitly so that 'private' flagged
236 // messages are not discarded by unset $wgDebugLogGroups channel
237 // handling below.
238 $shouldEmit = $wgDebugLogFile != '';
239
240 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
241 $logConfig = $wgDebugLogGroups[$channel];
242
243 if ( is_array( $logConfig ) ) {
244 $shouldEmit = true;
245 if ( isset( $logConfig['sample'] ) ) {
246 // Emit randomly with a 1 in 'sample' chance for each message.
247 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
248 }
249
250 if ( isset( $logConfig['level'] ) ) {
251 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
252 }
253 } else {
254 // Emit unless the config value is explicitly false.
255 $shouldEmit = $logConfig !== false;
256 }
257
258 } elseif ( isset( $context['private'] ) && $context['private'] ) {
259 // Don't emit if the message didn't match previous checks based on
260 // the channel and the event is marked as private. This check
261 // discards messages sent via wfDebugLog() with dest == 'private'
262 // and no explicit wgDebugLogGroups configuration.
263 $shouldEmit = false;
264 } else {
265 // Default return value is the same as the historic wfDebug
266 // method: emit if $wgDebugLogFile has been set.
267 $shouldEmit = $wgDebugLogFile != '';
268 }
269
270 return $shouldEmit;
271 }
272
285 public static function format( $channel, $message, $context ) {
287
288 if ( $channel === 'wfDebug' ) {
289 $text = self::formatAsWfDebug( $channel, $message, $context );
290
291 } elseif ( $channel === 'wfLogDBError' ) {
292 $text = self::formatAsWfLogDBError( $channel, $message, $context );
293
294 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
295 $text = self::formatAsWfDebug(
296 $channel, "[{$channel}] {$message}", $context );
297
298 } else {
299 // Default formatting is wfDebugLog's historic style
300 $text = self::formatAsWfDebugLog( $channel, $message, $context );
301 }
302
303 // Append stacktrace of throwable if available
304 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
305 $e = $context['exception'];
306 $backtrace = false;
307
308 if ( $e instanceof Throwable ) {
309 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
310
311 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
312 // Throwable has already been unpacked as structured data
313 $backtrace = $e['trace'];
314 }
315
316 if ( $backtrace ) {
317 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
318 "\n";
319 }
320 }
321
322 return self::interpolate( $text, $context );
323 }
324
333 protected static function formatAsWfDebug( $channel, $message, $context ) {
334 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
335 if ( isset( $context['seconds_elapsed'] ) ) {
336 // Prepend elapsed request time and real memory usage with two
337 // trailing spaces.
338 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
339 }
340 if ( isset( $context['prefix'] ) ) {
341 $text = "{$context['prefix']}{$text}";
342 }
343 return "{$text}\n";
344 }
345
354 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
355 global $wgDBerrorLogTZ;
356 static $cachedTimezone = null;
357
358 if ( !$cachedTimezone ) {
359 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
360 }
361
362 $d = date_create( 'now', $cachedTimezone );
363 $date = $d->format( 'D M j G:i:s T Y' );
364
365 $host = wfHostname();
367
368 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
369 return $text;
370 }
371
380 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
381 $time = wfTimestamp( TS_DB );
383 $host = wfHostname();
384 $text = "{$time} {$host} {$wiki}: {$message}\n";
385 return $text;
386 }
387
395 public static function interpolate( $message, array $context ) {
396 if ( strpos( $message, '{' ) !== false ) {
397 $replace = [];
398 foreach ( $context as $key => $val ) {
399 $replace['{' . $key . '}'] = self::flatten( $val );
400 }
401 $message = strtr( $message, $replace );
402 }
403 return $message;
404 }
405
413 protected static function flatten( $item ) {
414 if ( $item === null ) {
415 return '[Null]';
416 }
417
418 if ( is_bool( $item ) ) {
419 return $item ? 'true' : 'false';
420 }
421
422 if ( is_float( $item ) ) {
423 if ( is_infinite( $item ) ) {
424 return ( $item > 0 ? '' : '-' ) . 'INF';
425 }
426 if ( is_nan( $item ) ) {
427 return 'NaN';
428 }
429 return (string)$item;
430 }
431
432 if ( is_scalar( $item ) ) {
433 return (string)$item;
434 }
435
436 if ( is_array( $item ) ) {
437 return '[Array(' . count( $item ) . ')]';
438 }
439
440 if ( $item instanceof \DateTime ) {
441 return $item->format( 'c' );
442 }
443
444 if ( $item instanceof Throwable ) {
445 $which = $item instanceof Error ? 'Error' : 'Exception';
446 return '[' . $which . ' ' . get_class( $item ) . '( ' .
447 $item->getFile() . ':' . $item->getLine() . ') ' .
448 $item->getMessage() . ']';
449 }
450
451 if ( is_object( $item ) ) {
452 if ( method_exists( $item, '__toString' ) ) {
453 return (string)$item;
454 }
455
456 return '[Object ' . get_class( $item ) . ']';
457 }
458
459 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
460 if ( is_resource( $item ) ) {
461 return '[Resource ' . get_resource_type( $item ) . ']';
462 }
463
464 return '[Unknown ' . gettype( $item ) . ']';
465 }
466
477 protected static function destination( $channel, $message, $context ) {
479
480 // Default destination is the debug log file as historically used by
481 // the wfDebug function.
482 $destination = $wgDebugLogFile;
483
484 if ( isset( $context['destination'] ) ) {
485 // Use destination explicitly provided in context
486 $destination = $context['destination'];
487
488 } elseif ( $channel === 'wfDebug' ) {
489 $destination = $wgDebugLogFile;
490
491 } elseif ( $channel === 'wfLogDBError' ) {
492 $destination = $wgDBerrorLog;
493
494 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
495 $logConfig = $wgDebugLogGroups[$channel];
496
497 if ( is_array( $logConfig ) ) {
498 $destination = $logConfig['destination'];
499 } else {
500 $destination = strval( $logConfig );
501 }
502 }
503
504 return $destination;
505 }
506
516 public static function emit( $text, $file ) {
517 if ( substr( $file, 0, 4 ) == 'udp:' ) {
518 $transport = UDPTransport::newFromString( $file );
519 $transport->emit( $text );
520 } else {
521 AtEase::suppressWarnings();
522 $exists = file_exists( $file );
523 $size = $exists ? filesize( $file ) : false;
524 if ( !$exists ||
525 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
526 ) {
527 file_put_contents( $file, $text, FILE_APPEND );
528 }
529 AtEase::restoreWarnings();
530 }
531 }
532
533}
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:36
static query( $sql, $function, $runTime, $dbhost)
Begins profiling on a database query.
Definition MWDebug.php:552
static debugMsg( $str, $context=[])
This is a method to pass messages from wfDebug to the pretty debugger.
Definition MWDebug.php:521
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 ...
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
$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.
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