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