MediaWiki master
LegacyLogger.php
Go to the documentation of this file.
1<?php
7namespace MediaWiki\Logger;
8
9use DateTimeZone;
10use Error;
11use LogicException;
15use Psr\Log\AbstractLogger;
16use Psr\Log\LogLevel;
17use Throwable;
18use UDPTransport;
19use Wikimedia\Timestamp\ConvertibleTimestamp;
20use Wikimedia\Timestamp\TimestampFormat as TS;
21
39class LegacyLogger extends AbstractLogger {
40
44 protected $channel;
45
46 private const LEVEL_DEBUG = 100;
47 private const LEVEL_INFO = 200;
48 private const LEVEL_NOTICE = 250;
49 private const LEVEL_WARNING = 300;
50 private const LEVEL_ERROR = 400;
51 private const LEVEL_CRITICAL = 500;
52 private const LEVEL_ALERT = 550;
53 private const LEVEL_EMERGENCY = 600;
54 private const LEVEL_INFINITY = 999;
55
62 protected static $levelMapping = [
63 LogLevel::DEBUG => self::LEVEL_DEBUG,
64 LogLevel::INFO => self::LEVEL_INFO,
65 LogLevel::NOTICE => self::LEVEL_NOTICE,
66 LogLevel::WARNING => self::LEVEL_WARNING,
67 LogLevel::ERROR => self::LEVEL_ERROR,
68 LogLevel::CRITICAL => self::LEVEL_CRITICAL,
69 LogLevel::ALERT => self::LEVEL_ALERT,
70 LogLevel::EMERGENCY => self::LEVEL_EMERGENCY,
71 ];
72
79 private $minimumLevel;
80
86 private $isDB;
87
91 public function __construct( $channel ) {
93
94 $this->channel = $channel;
95 $this->isDB = ( $channel === 'rdbms' );
96
97 // Calculate minimum level, duplicating some of the logic from log() and shouldEmit()
99 $this->minimumLevel = self::LEVEL_WARNING;
100 } elseif ( $wgDebugLogFile != '' || $wgShowDebug || $wgDebugToolbar ) {
101 // Log all messages if there is a debug log file or debug toolbar
102 $this->minimumLevel = self::LEVEL_DEBUG;
103 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
104 $logConfig = $wgDebugLogGroups[$channel];
105 // Log messages if the config is set, according to the configured level
106 if ( is_array( $logConfig ) && isset( $logConfig['level'] ) ) {
107 $this->minimumLevel = self::$levelMapping[$logConfig['level']];
108 } else {
109 $this->minimumLevel = self::LEVEL_DEBUG;
110 }
111 } else {
112 // No other case hit: discard all messages
113 $this->minimumLevel = self::LEVEL_INFINITY;
114 }
115
116 if ( $this->isDB && $wgDBerrorLog && $this->minimumLevel > self::LEVEL_ERROR ) {
117 // Log DB errors if there is a DB error log
118 $this->minimumLevel = self::LEVEL_ERROR;
119 }
120 }
121
129 public function setMinimumForTest( ?int $level ) {
130 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
131 throw new LogicException( 'Not allowed outside tests' );
132 }
133 // Set LEVEL_INFINITY if given null, or restore the original level.
134 $original = $this->minimumLevel;
135 $this->minimumLevel = $level ?? self::LEVEL_INFINITY;
136 return $original;
137 }
138
146 public function log( $level, $message, array $context = [] ): void {
147 if ( is_string( $level ) ) {
148 $level = self::$levelMapping[$level];
149 }
150 if ( $level < $this->minimumLevel ) {
151 return;
152 }
153
154 $context += LoggerFactory::getContext()->get();
155
156 if ( $this->isDB
157 && $level === self::LEVEL_DEBUG
158 && isset( $context['sql'] )
159 ) {
160 // Also give the query information to the MWDebug tools
161 MWDebug::query(
162 $context['sql'],
163 $context['method'],
164 $context['runtime_ms'] / 1000,
165 $context['db_server'],
166 $context['rows'],
167 );
168 }
169
170 // If this is a DB-related error, and the site has $wgDBerrorLog
171 // configured, rewrite the channel as wfLogDBError instead.
172 // Likewise, if the site does not use $wgDBerrorLog, it should
173 // configurable like any other channel via $wgDebugLogGroups
174 // or $wgMWLoggerDefaultSpi.
175 global $wgDBerrorLog;
176 if ( $this->isDB && $level >= self::LEVEL_ERROR && $wgDBerrorLog ) {
177 // Format and write DB errors to the legacy locations
178 $effectiveChannel = 'wfLogDBError';
179 } else {
180 $effectiveChannel = $this->channel;
181 }
182
183 if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
184 $text = self::format( $effectiveChannel, $message, $context );
185 $destination = self::destination( $effectiveChannel, $message, $context );
186 $this->maybeLogToStderr( $text );
187 self::emit( $text, $destination );
188 }
189 if ( !isset( $context['private'] ) || !$context['private'] ) {
190 // Add to debug toolbar if not marked as "private"
191 MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
192 }
193 }
194
205 public static function shouldEmit( $channel, $message, $level, $context ) {
207
208 if ( is_string( $level ) ) {
209 $level = self::$levelMapping[$level];
210 }
211
212 if ( $channel === 'wfLogDBError' ) {
213 // wfLogDBError messages are emitted if a database log location is
214 // specified.
215 $shouldEmit = (bool)$wgDBerrorLog;
216
217 } elseif ( $channel === 'wfDebug' ) {
218 // wfDebug messages are emitted if a catch all logging file has
219 // been specified. Checked explicitly so that 'private' flagged
220 // messages are not discarded by unset $wgDebugLogGroups channel
221 // handling below.
222 $shouldEmit = $wgDebugLogFile != '';
223
224 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
225 $logConfig = $wgDebugLogGroups[$channel];
226
227 if ( is_array( $logConfig ) ) {
228 $shouldEmit = true;
229 if ( isset( $logConfig['sample'] ) ) {
230 // Emit randomly with a 1 in 'sample' chance for each message.
231 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
232 }
233
234 if ( isset( $logConfig['level'] ) ) {
235 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
236 }
237 } else {
238 // Emit unless the config value is explicitly false.
239 $shouldEmit = $logConfig !== false;
240 }
241
242 } elseif ( isset( $context['private'] ) && $context['private'] ) {
243 // Don't emit if the message didn't match previous checks based on
244 // the channel and the event is marked as private. This check
245 // discards messages sent via wfDebugLog() with dest == 'private'
246 // and no explicit wgDebugLogGroups configuration.
247 $shouldEmit = false;
248 } else {
249 // Default return value is the same as the historic wfDebug
250 // method: emit if $wgDebugLogFile has been set.
251 $shouldEmit = $wgDebugLogFile != '';
252 }
253
254 return $shouldEmit;
255 }
256
269 public static function format( $channel, $message, $context ) {
271
272 if ( $channel === 'wfDebug' ) {
273 $text = self::formatAsWfDebug( $channel, $message, $context );
274
275 } elseif ( $channel === 'wfLogDBError' ) {
276 $text = self::formatAsWfLogDBError( $channel, $message, $context );
277
278 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
279 $text = self::formatAsWfDebug(
280 $channel, "[{$channel}] {$message}", $context );
281
282 } else {
283 // Default formatting is wfDebugLog's historic style
284 $text = self::formatAsWfDebugLog( $channel, $message, $context );
285 }
286
287 // Append stacktrace of throwable if available
288 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
289 $e = $context['exception'];
290 $backtrace = false;
291
292 if ( $e instanceof Throwable ) {
293 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
294
295 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
296 // Throwable has already been unpacked as structured data
297 $backtrace = $e['trace'];
298 }
299
300 if ( $backtrace ) {
301 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
302 "\n";
303 }
304 }
305
306 return self::interpolate( $text, $context );
307 }
308
317 protected static function formatAsWfDebug( $channel, $message, $context ) {
318 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
319 if ( isset( $context['seconds_elapsed'] ) ) {
320 // Prepend elapsed request time and real memory usage with two
321 // trailing spaces.
322 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
323 }
324 if ( isset( $context['prefix'] ) ) {
325 $text = "{$context['prefix']}{$text}";
326 }
327 return "{$text}\n";
328 }
329
338 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
339 global $wgDBerrorLogTZ;
340 static $cachedTimezone = null;
341
342 if ( !$cachedTimezone ) {
343 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
344 }
345
346 $d = date_create( 'now', $cachedTimezone );
347 $date = $d->format( 'D M j G:i:s T Y' );
348
349 $host = wfHostname();
350 $wiki = WikiMap::getCurrentWikiId();
351
352 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
353 return $text;
354 }
355
364 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
365 $time = ConvertibleTimestamp::now( TS::DB );
366 $wiki = WikiMap::getCurrentWikiId();
367 $host = wfHostname();
368 $text = "{$time} {$host} {$wiki}: {$message}\n";
369 return $text;
370 }
371
379 public static function interpolate( $message, array $context ) {
380 if ( str_contains( $message, '{' ) ) {
381 $replace = [];
382 foreach ( $context as $key => $val ) {
383 $replace['{' . $key . '}'] = self::flatten( $val );
384 }
385 $message = strtr( $message, $replace );
386 }
387 return $message;
388 }
389
397 protected static function flatten( $item ) {
398 if ( $item === null ) {
399 return '[Null]';
400 }
401
402 if ( is_bool( $item ) ) {
403 return $item ? 'true' : 'false';
404 }
405
406 if ( is_float( $item ) ) {
407 if ( is_infinite( $item ) ) {
408 return ( $item > 0 ? '' : '-' ) . 'INF';
409 }
410 if ( is_nan( $item ) ) {
411 return 'NaN';
412 }
413 return (string)$item;
414 }
415
416 if ( is_scalar( $item ) ) {
417 return (string)$item;
418 }
419
420 if ( is_array( $item ) ) {
421 return '[Array(' . count( $item ) . ')]';
422 }
423
424 if ( $item instanceof \DateTime ) {
425 return $item->format( 'c' );
426 }
427
428 if ( $item instanceof Throwable ) {
429 $which = $item instanceof Error ? 'Error' : 'Exception';
430 return '[' . $which . ' ' . get_class( $item ) . '( ' .
431 $item->getFile() . ':' . $item->getLine() . ') ' .
432 $item->getMessage() . ']';
433 }
434
435 if ( is_object( $item ) ) {
436 if ( method_exists( $item, '__toString' ) ) {
437 return (string)$item;
438 }
439
440 return '[Object ' . get_class( $item ) . ']';
441 }
442
443 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
444 if ( is_resource( $item ) ) {
445 return '[Resource ' . get_resource_type( $item ) . ']';
446 }
447
448 return '[Unknown ' . get_debug_type( $item ) . ']';
449 }
450
461 protected static function destination( $channel, $message, $context ) {
463
464 // Default destination is the debug log file as historically used by
465 // the wfDebug function.
466 $destination = $wgDebugLogFile;
467
468 if ( isset( $context['destination'] ) ) {
469 // Use destination explicitly provided in context
470 $destination = $context['destination'];
471
472 } elseif ( $channel === 'wfDebug' ) {
473 $destination = $wgDebugLogFile;
474
475 } elseif ( $channel === 'wfLogDBError' ) {
476 $destination = $wgDBerrorLog;
477
478 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
479 $logConfig = $wgDebugLogGroups[$channel];
480
481 if ( is_array( $logConfig ) ) {
482 $destination = $logConfig['destination'];
483 } else {
484 $destination = strval( $logConfig );
485 }
486 }
487
488 return $destination;
489 }
490
500 public static function emit( $text, $file ) {
501 if ( str_starts_with( $file, 'udp:' ) ) {
502 $transport = UDPTransport::newFromString( $file );
503 $transport->emit( $text );
504 } else {
505 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
506 $exists = @file_exists( $file );
507 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
508 $size = $exists ? @filesize( $file ) : false;
509 if ( !$exists ||
510 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
511 ) {
512 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
513 @file_put_contents( $file, $text, FILE_APPEND );
514 }
515 }
516 }
517
525 private function maybeLogToStderr( string $text ): void {
526 if ( getenv( 'MW_LOG_STDERR' ) ) {
527 error_log( trim( $text ) );
528 }
529 }
530
531}
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.
if(!defined('MW_SETUP_CALLBACK'))
Definition WebStart.php:69
Debug toolbar.
Definition MWDebug.php:35
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:19
A generic class to send a message over UDP.
$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.