15use Psr\Log\AbstractLogger;
19use Wikimedia\AtEase\AtEase;
45privateconst LEVEL_DEBUG = 100;
46privateconst LEVEL_INFO = 200;
47privateconst LEVEL_NOTICE = 250;
48privateconst LEVEL_WARNING = 300;
49privateconst LEVEL_ERROR = 400;
50privateconst LEVEL_CRITICAL = 500;
51privateconst LEVEL_ALERT = 550;
52privateconst LEVEL_EMERGENCY = 600;
53privateconst LEVEL_INFINITY = 999;
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,
94 $this->isDB = (
$channel ===
'rdbms' );
96// Calculate minimum level, duplicating some of the logic from log() and shouldEmit() 98 $this->minimumLevel = self::LEVEL_WARNING;
100// Log all messages if there is a debug log file or debug toolbar 101 $this->minimumLevel = self::LEVEL_DEBUG;
104// Log messages if the config is set, according to the configured level 105if ( is_array( $logConfig ) && isset( $logConfig[
'level'] ) ) {
106 $this->minimumLevel = self::$levelMapping[$logConfig[
'level']];
108 $this->minimumLevel = self::LEVEL_DEBUG;
111// No other case hit: discard all messages 112 $this->minimumLevel = self::LEVEL_INFINITY;
115if ( $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;
129if ( !defined(
'MW_PHPUNIT_TEST' ) ) {
130thrownew LogicException(
'Not allowed outside tests' );
132// Set LEVEL_INFINITY if given null, or restore the original level. 133 $original = $this->minimumLevel;
134 $this->minimumLevel = $level ?? self::LEVEL_INFINITY;
145publicfunctionlog( $level, $message, array $context = [] ): void {
146if ( is_string( $level ) ) {
147 $level = self::$levelMapping[$level];
149if ( $level < $this->minimumLevel ) {
156 && $level === self::LEVEL_DEBUG
157 && isset( $context[
'sql'] )
159// Also give the query information to the MWDebug tools 163 $context[
'runtime_ms'] / 1000,
164 $context[
'db_server']
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. 174if ( $this->isDB && $level >= self::LEVEL_ERROR &&
$wgDBerrorLog ) {
175// Format and write DB errors to the legacy locations 176 $effectiveChannel =
'wfLogDBError';
181if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
182 $text =
self::format( $effectiveChannel, $message, $context );
184 $this->maybeLogToStderr( $text );
187if ( !isset( $context[
'private'] ) || !$context[
'private'] ) {
188// Add to debug toolbar if not marked as "private" 189 MWDebug::debugMsg( $message, [
'channel' => $this->channel ] + $context );
203publicstaticfunctionshouldEmit( $channel, $message, $level, $context ) {
206if ( is_string( $level ) ) {
207 $level = self::$levelMapping[$level];
210if ( $channel ===
'wfLogDBError' ) {
211// wfLogDBError messages are emitted if a database log location is 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 225if ( is_array( $logConfig ) ) {
227if ( isset( $logConfig[
'sample'] ) ) {
228// Emit randomly with a 1 in 'sample' chance for each message. 229 $shouldEmit = mt_rand( 1, $logConfig[
'sample'] ) === 1;
232if ( isset( $logConfig[
'level'] ) ) {
233 $shouldEmit = $level >= self::$levelMapping[$logConfig[
'level']];
236// Emit unless the config value is explicitly false. 237 $shouldEmit = $logConfig !==
false;
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. 247// Default return value is the same as the historic wfDebug 248// method: emit if $wgDebugLogFile has been set. 267publicstaticfunctionformat( $channel, $message, $context ) {
270if ( $channel ===
'wfDebug' ) {
271 $text = self::formatAsWfDebug( $channel, $message, $context );
273 } elseif ( $channel ===
'wfLogDBError' ) {
274 $text = self::formatAsWfLogDBError( $channel, $message, $context );
277 $text = self::formatAsWfDebug(
278 $channel,
"[{$channel}] {$message}", $context );
281// Default formatting is wfDebugLog's historic style 282 $text = self::formatAsWfDebugLog( $channel, $message, $context );
285// Append stacktrace of throwable if available 287 $e = $context[
'exception'];
290if ( $e instanceof Throwable ) {
291 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
293 } elseif ( is_array( $e ) && isset( $e[
'trace'] ) ) {
294// Throwable has already been unpacked as structured data 295 $backtrace = $e[
'trace'];
299 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
304return self::interpolate( $text, $context );
316 $text = preg_replace(
'![\x00-\x08\x0b\x0c\x0e-\x1f]!',
' ', $message );
317if ( isset( $context[
'seconds_elapsed'] ) ) {
318// Prepend elapsed request time and real memory usage with two 320 $text =
"{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
322if ( isset( $context[
'prefix'] ) ) {
323 $text =
"{$context['prefix']}{$text}";
338static $cachedTimezone =
null;
340if ( !$cachedTimezone ) {
344 $d = date_create(
'now', $cachedTimezone );
345 $date = $d->format(
'D M j G:i:s T Y' );
348 $wiki = WikiMap::getCurrentWikiId();
350 $text =
"{$date}\t{$host}\t{$wiki}\t{$message}\n";
364 $wiki = WikiMap::getCurrentWikiId();
366 $text =
"{$time} {$host} {$wiki}: {$message}\n";
378if ( str_contains( $message,
'{' ) ) {
380foreach ( $context as $key => $val ) {
381 $replace[
'{' . $key .
'}'] = self::flatten( $val );
383 $message = strtr( $message, $replace );
396if ( $item ===
null ) {
400if ( is_bool( $item ) ) {
401return $item ?
'true' :
'false';
404if ( is_float( $item ) ) {
405if ( is_infinite( $item ) ) {
406return ( $item > 0 ?
'' :
'-' ) .
'INF';
408if ( is_nan( $item ) ) {
414if ( is_scalar( $item ) ) {
418if ( is_array( $item ) ) {
419return'[Array(' . count( $item ) .
')]';
422if ( $item instanceof \DateTime ) {
423return $item->format(
'c' );
426if ( $item instanceof Throwable ) {
427 $which = $item instanceof Error ?
'Error' :
'Exception';
428return'[' . $which .
' ' . get_class( $item ) .
'( ' .
429 $item->getFile() .
':' . $item->getLine() .
') ' .
430 $item->getMessage() .
']';
433if ( is_object( $item ) ) {
434if ( method_exists( $item,
'__toString' ) ) {
438return'[Object ' . get_class( $item ) .
']';
441// phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource 442if ( is_resource( $item ) ) {
443return'[Resource ' . get_resource_type( $item ) .
']';
446return'[Unknown ' . get_debug_type( $item ) .
']';
459protectedstaticfunctiondestination( $channel, $message, $context ) {
462// Default destination is the debug log file as historically used by 463// the wfDebug function. 466if ( isset( $context[
'destination'] ) ) {
467// Use destination explicitly provided in context 468 $destination = $context[
'destination'];
470 } elseif ( $channel ===
'wfDebug' ) {
473 } elseif ( $channel ===
'wfLogDBError' ) {
479if ( is_array( $logConfig ) ) {
480 $destination = $logConfig[
'destination'];
482 $destination = strval( $logConfig );
498publicstaticfunctionemit( $text, $file ) {
499if ( str_starts_with( $file,
'udp:' ) ) {
500 $transport = UDPTransport::newFromString( $file );
501 $transport->emit( $text );
503 AtEase::suppressWarnings();
504 $exists = file_exists( $file );
505 $size = $exists ? filesize( $file ) :
false;
507 ( $size !==
false && $size + strlen( $text ) < 0x7fffffff )
509 file_put_contents( $file, $text, FILE_APPEND );
511 AtEase::restoreWarnings();
522privatefunction maybeLogToStderr(
string $text ): void {
523if ( getenv(
'MW_LOG_STDERR' ) ) {
524 error_log( trim( $text ) );
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'))
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.
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.