MediaWiki master
LegacyLogger.php
Go to the documentation of this file.
1<?php
21namespace MediaWiki\Logger;
22
23use DateTimeZone;
24use Error;
25use LogicException;
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 != '' || $wgShowDebug || $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 = [] ): void {
160 if ( is_string( $level ) ) {
161 $level = self::$levelMapping[$level];
162 }
163 if ( $level < $this->minimumLevel ) {
164 return;
165 }
166
167 $context += LoggerFactory::getContext()->get();
168
169 if ( $this->isDB
170 && $level === self::LEVEL_DEBUG
171 && isset( $context['sql'] )
172 ) {
173 // Also give the query information to the MWDebug tools
174 MWDebug::query(
175 $context['sql'],
176 $context['method'],
177 $context['runtime_ms'] / 1000,
178 $context['db_server']
179 );
180 }
181
182 // If this is a DB-related error, and the site has $wgDBerrorLog
183 // configured, rewrite the channel as wfLogDBError instead.
184 // Likewise, if the site does not use $wgDBerrorLog, it should
185 // configurable like any other channel via $wgDebugLogGroups
186 // or $wgMWLoggerDefaultSpi.
187 global $wgDBerrorLog;
188 if ( $this->isDB && $level >= self::LEVEL_ERROR && $wgDBerrorLog ) {
189 // Format and write DB errors to the legacy locations
190 $effectiveChannel = 'wfLogDBError';
191 } else {
192 $effectiveChannel = $this->channel;
193 }
194
195 if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
196 $text = self::format( $effectiveChannel, $message, $context );
197 $destination = self::destination( $effectiveChannel, $message, $context );
198 $this->maybeLogToStderr( $text );
199 self::emit( $text, $destination );
200 }
201 if ( !isset( $context['private'] ) || !$context['private'] ) {
202 // Add to debug toolbar if not marked as "private"
203 MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
204 }
205 }
206
217 public static function shouldEmit( $channel, $message, $level, $context ) {
219
220 if ( is_string( $level ) ) {
221 $level = self::$levelMapping[$level];
222 }
223
224 if ( $channel === 'wfLogDBError' ) {
225 // wfLogDBError messages are emitted if a database log location is
226 // specified.
227 $shouldEmit = (bool)$wgDBerrorLog;
228
229 } elseif ( $channel === 'wfDebug' ) {
230 // wfDebug messages are emitted if a catch all logging file has
231 // been specified. Checked explicitly so that 'private' flagged
232 // messages are not discarded by unset $wgDebugLogGroups channel
233 // handling below.
234 $shouldEmit = $wgDebugLogFile != '';
235
236 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
237 $logConfig = $wgDebugLogGroups[$channel];
238
239 if ( is_array( $logConfig ) ) {
240 $shouldEmit = true;
241 if ( isset( $logConfig['sample'] ) ) {
242 // Emit randomly with a 1 in 'sample' chance for each message.
243 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
244 }
245
246 if ( isset( $logConfig['level'] ) ) {
247 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
248 }
249 } else {
250 // Emit unless the config value is explicitly false.
251 $shouldEmit = $logConfig !== false;
252 }
253
254 } elseif ( isset( $context['private'] ) && $context['private'] ) {
255 // Don't emit if the message didn't match previous checks based on
256 // the channel and the event is marked as private. This check
257 // discards messages sent via wfDebugLog() with dest == 'private'
258 // and no explicit wgDebugLogGroups configuration.
259 $shouldEmit = false;
260 } else {
261 // Default return value is the same as the historic wfDebug
262 // method: emit if $wgDebugLogFile has been set.
263 $shouldEmit = $wgDebugLogFile != '';
264 }
265
266 return $shouldEmit;
267 }
268
281 public static function format( $channel, $message, $context ) {
283
284 if ( $channel === 'wfDebug' ) {
285 $text = self::formatAsWfDebug( $channel, $message, $context );
286
287 } elseif ( $channel === 'wfLogDBError' ) {
288 $text = self::formatAsWfLogDBError( $channel, $message, $context );
289
290 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
291 $text = self::formatAsWfDebug(
292 $channel, "[{$channel}] {$message}", $context );
293
294 } else {
295 // Default formatting is wfDebugLog's historic style
296 $text = self::formatAsWfDebugLog( $channel, $message, $context );
297 }
298
299 // Append stacktrace of throwable if available
300 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
301 $e = $context['exception'];
302 $backtrace = false;
303
304 if ( $e instanceof Throwable ) {
305 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
306
307 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
308 // Throwable has already been unpacked as structured data
309 $backtrace = $e['trace'];
310 }
311
312 if ( $backtrace ) {
313 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
314 "\n";
315 }
316 }
317
318 return self::interpolate( $text, $context );
319 }
320
329 protected static function formatAsWfDebug( $channel, $message, $context ) {
330 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
331 if ( isset( $context['seconds_elapsed'] ) ) {
332 // Prepend elapsed request time and real memory usage with two
333 // trailing spaces.
334 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
335 }
336 if ( isset( $context['prefix'] ) ) {
337 $text = "{$context['prefix']}{$text}";
338 }
339 return "{$text}\n";
340 }
341
350 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
351 global $wgDBerrorLogTZ;
352 static $cachedTimezone = null;
353
354 if ( !$cachedTimezone ) {
355 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
356 }
357
358 $d = date_create( 'now', $cachedTimezone );
359 $date = $d->format( 'D M j G:i:s T Y' );
360
361 $host = wfHostname();
362 $wiki = WikiMap::getCurrentWikiId();
363
364 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
365 return $text;
366 }
367
376 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
377 $time = wfTimestamp( TS_DB );
378 $wiki = WikiMap::getCurrentWikiId();
379 $host = wfHostname();
380 $text = "{$time} {$host} {$wiki}: {$message}\n";
381 return $text;
382 }
383
391 public static function interpolate( $message, array $context ) {
392 if ( str_contains( $message, '{' ) ) {
393 $replace = [];
394 foreach ( $context as $key => $val ) {
395 $replace['{' . $key . '}'] = self::flatten( $val );
396 }
397 $message = strtr( $message, $replace );
398 }
399 return $message;
400 }
401
409 protected static function flatten( $item ) {
410 if ( $item === null ) {
411 return '[Null]';
412 }
413
414 if ( is_bool( $item ) ) {
415 return $item ? 'true' : 'false';
416 }
417
418 if ( is_float( $item ) ) {
419 if ( is_infinite( $item ) ) {
420 return ( $item > 0 ? '' : '-' ) . 'INF';
421 }
422 if ( is_nan( $item ) ) {
423 return 'NaN';
424 }
425 return (string)$item;
426 }
427
428 if ( is_scalar( $item ) ) {
429 return (string)$item;
430 }
431
432 if ( is_array( $item ) ) {
433 return '[Array(' . count( $item ) . ')]';
434 }
435
436 if ( $item instanceof \DateTime ) {
437 return $item->format( 'c' );
438 }
439
440 if ( $item instanceof Throwable ) {
441 $which = $item instanceof Error ? 'Error' : 'Exception';
442 return '[' . $which . ' ' . get_class( $item ) . '( ' .
443 $item->getFile() . ':' . $item->getLine() . ') ' .
444 $item->getMessage() . ']';
445 }
446
447 if ( is_object( $item ) ) {
448 if ( method_exists( $item, '__toString' ) ) {
449 return (string)$item;
450 }
451
452 return '[Object ' . get_class( $item ) . ']';
453 }
454
455 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
456 if ( is_resource( $item ) ) {
457 return '[Resource ' . get_resource_type( $item ) . ']';
458 }
459
460 return '[Unknown ' . get_debug_type( $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 ( str_starts_with( $file, 'udp:' ) ) {
514 $transport = UDPTransport::newFromString( $file );
515 $transport->emit( $text );
516 } else {
517 AtEase::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 AtEase::restoreWarnings();
526 }
527 }
528
536 private function maybeLogToStderr( string $text ): void {
537 if ( getenv( 'MW_LOG_STDERR' ) ) {
538 error_log( trim( $text ) );
539 }
540 }
541
542}
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.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:82
Debug toolbar.
Definition MWDebug.php:49
Handler class for MWExceptions.
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 ...
static getContext()
Get a logging context, which can be used to add information to all log events.
Tools for dealing with other locally-hosted wikis.
Definition WikiMap.php:33
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.
$wgShowDebug
Config variable stub for the ShowDebug 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.