Movatterモバイル変換


[0]ホーム

URL:


MediaWiki master
LegacyLogger.php
Go to the documentation of this file.
1<?php
7namespaceMediaWiki\Logger;
8
9use DateTimeZone;
10use Error;
11use LogicException;
12useMediaWiki\Debug\MWDebug;
13useMediaWiki\Exception\MWExceptionHandler;
14useMediaWiki\WikiMap\WikiMap;
15use Psr\Log\AbstractLogger;
16use Psr\Log\LogLevel;
17use Throwable;
18useUDPTransport;
19use Wikimedia\AtEase\AtEase;
20
38classLegacyLoggerextends AbstractLogger {
39
43protected$channel;
44
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;
54
61protectedstatic$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
78private $minimumLevel;
79
85private $isDB;
86
90publicfunction__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
105if ( 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
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;
118 }
119 }
120
128publicfunctionsetMinimumForTest( ?int $level ) {
129if ( !defined('MW_PHPUNIT_TEST' ) ) {
130thrownew 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;
135return $original;
136 }
137
145publicfunctionlog( $level, $message, array $context = [] ): void {
146if ( is_string( $level ) ) {
147 $level = self::$levelMapping[$level];
148 }
149if ( $level < $this->minimumLevel ) {
150return;
151 }
152
153 $context +=LoggerFactory::getContext()->get();
154
155if ( $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;
174if ( $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
181if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
182 $text =self::format( $effectiveChannel, $message, $context );
183 $destination =self::destination( $effectiveChannel, $message, $context );
184 $this->maybeLogToStderr( $text );
185self::emit( $text, $destination );
186 }
187if ( !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
203publicstaticfunctionshouldEmit( $channel, $message, $level, $context ) {
205
206if ( is_string( $level ) ) {
207 $level = self::$levelMapping[$level];
208 }
209
210if ( $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
225if ( is_array( $logConfig ) ) {
226 $shouldEmit =true;
227if ( 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
232if ( 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
252return $shouldEmit;
253 }
254
267publicstaticfunctionformat( $channel, $message, $context ) {
269
270if ( $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
286if ($wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
287 $e = $context['exception'];
288 $backtrace =false;
289
290if ( $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
298if ( $backtrace ) {
299 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
300"\n";
301 }
302 }
303
304return self::interpolate( $text, $context );
305 }
306
315protectedstaticfunctionformatAsWfDebug( $channel, $message, $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
319// trailing spaces.
320 $text ="{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
321 }
322if ( isset( $context['prefix'] ) ) {
323 $text ="{$context['prefix']}{$text}";
324 }
325return"{$text}\n";
326 }
327
336protectedstaticfunctionformatAsWfLogDBError( $channel, $message, $context ) {
337 global$wgDBerrorLogTZ;
338static $cachedTimezone =null;
339
340if ( !$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";
351return $text;
352 }
353
362protectedstaticfunctionformatAsWfDebugLog( $channel, $message, $context ) {
363 $time =wfTimestamp( TS_DB );
364 $wiki = WikiMap::getCurrentWikiId();
365 $host =wfHostname();
366 $text ="{$time} {$host} {$wiki}: {$message}\n";
367return $text;
368 }
369
377publicstaticfunctioninterpolate( $message, array $context ) {
378if ( str_contains( $message,'{' ) ) {
379 $replace = [];
380foreach ( $context as $key => $val ) {
381 $replace['{' . $key .'}'] = self::flatten( $val );
382 }
383 $message = strtr( $message, $replace );
384 }
385return $message;
386 }
387
395protectedstaticfunctionflatten( $item ) {
396if ( $item ===null ) {
397return'[Null]';
398 }
399
400if ( is_bool( $item ) ) {
401return $item ?'true' :'false';
402 }
403
404if ( is_float( $item ) ) {
405if ( is_infinite( $item ) ) {
406return ( $item > 0 ?'' :'-' ) .'INF';
407 }
408if ( is_nan( $item ) ) {
409return'NaN';
410 }
411return (string)$item;
412 }
413
414if ( is_scalar( $item ) ) {
415return (string)$item;
416 }
417
418if ( is_array( $item ) ) {
419return'[Array(' . count( $item ) .')]';
420 }
421
422if ( $item instanceof \DateTime ) {
423return $item->format('c' );
424 }
425
426if ( $item instanceof Throwable ) {
427 $which = $item instanceof Error ?'Error' :'Exception';
428return'[' . $which .' ' . get_class( $item ) .'( ' .
429 $item->getFile() .':' . $item->getLine() .') ' .
430 $item->getMessage() .']';
431 }
432
433if ( is_object( $item ) ) {
434if ( method_exists( $item,'__toString' ) ) {
435return (string)$item;
436 }
437
438return'[Object ' . get_class( $item ) .']';
439 }
440
441// phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
442if ( is_resource( $item ) ) {
443return'[Resource ' . get_resource_type( $item ) .']';
444 }
445
446return'[Unknown ' . get_debug_type( $item ) .']';
447 }
448
459protectedstaticfunctiondestination( $channel, $message, $context ) {
461
462// Default destination is the debug log file as historically used by
463// the wfDebug function.
464 $destination =$wgDebugLogFile;
465
466if ( 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
479if ( is_array( $logConfig ) ) {
480 $destination = $logConfig['destination'];
481 }else {
482 $destination = strval( $logConfig );
483 }
484 }
485
486return $destination;
487 }
488
498publicstaticfunctionemit( $text, $file ) {
499if ( 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;
506if ( !$exists ||
507 ( $size !==false && $size + strlen( $text ) < 0x7fffffff )
508 ) {
509 file_put_contents( $file, $text, FILE_APPEND );
510 }
511 AtEase::restoreWarnings();
512 }
513 }
514
522privatefunction maybeLogToStderr(string $text ): void {
523if ( getenv('MW_LOG_STDERR' ) ) {
524 error_log( trim( $text ) );
525 }
526 }
527
528}
wfIsDebugRawPage
wfIsDebugRawPage()
Returns true if debug logging should be suppressed if $wgDebugRawPage = false.
DefinitionGlobalFunctions.php:654
wfHostname
wfHostname()
Get host name of the current machine, for use in error reporting.
DefinitionGlobalFunctions.php:888
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
DefinitionGlobalFunctions.php:1300
if
if(!defined('MW_SETUP_CALLBACK'))
DefinitionWebStart.php:68
MediaWiki\Debug\MWDebug
Debug toolbar.
DefinitionMWDebug.php:35
MediaWiki\Exception\MWExceptionHandler
Handler class for MWExceptions.
DefinitionMWExceptionHandler.php:27
MediaWiki\Logger\LegacyLogger
PSR-3 logger that mimics the historic implementation of MediaWiki's former wfErrorLog logging impleme...
DefinitionLegacyLogger.php:38
MediaWiki\Logger\LegacyLogger\flatten
static flatten( $item)
Convert a logging context element to a string suitable for interpolation.
DefinitionLegacyLogger.php:395
MediaWiki\Logger\LegacyLogger\formatAsWfDebugLog
static formatAsWfDebugLog( $channel, $message, $context)
Format a message as `wfDebugLog() would have formatted it.
DefinitionLegacyLogger.php:362
MediaWiki\Logger\LegacyLogger\shouldEmit
static shouldEmit( $channel, $message, $level, $context)
Determine if the given message should be emitted or not.
DefinitionLegacyLogger.php:203
MediaWiki\Logger\LegacyLogger\log
log( $level, $message, array $context=[])
Logs with an arbitrary level.
DefinitionLegacyLogger.php:145
MediaWiki\Logger\LegacyLogger\formatAsWfLogDBError
static formatAsWfLogDBError( $channel, $message, $context)
Format a message as wfLogDBError() would have formatted it.
DefinitionLegacyLogger.php:336
MediaWiki\Logger\LegacyLogger\interpolate
static interpolate( $message, array $context)
Interpolate placeholders in logging message.
DefinitionLegacyLogger.php:377
MediaWiki\Logger\LegacyLogger\destination
static destination( $channel, $message, $context)
Select the appropriate log output destination for the given log event.
DefinitionLegacyLogger.php:459
MediaWiki\Logger\LegacyLogger\$channel
string $channel
DefinitionLegacyLogger.php:43
MediaWiki\Logger\LegacyLogger\setMinimumForTest
setMinimumForTest(?int $level)
Change an existing Logger singleton to act like NullLogger.
DefinitionLegacyLogger.php:128
MediaWiki\Logger\LegacyLogger\emit
static emit( $text, $file)
Log to a file without getting "file size exceeded" signals.
DefinitionLegacyLogger.php:498
MediaWiki\Logger\LegacyLogger\format
static format( $channel, $message, $context)
Format a message.
DefinitionLegacyLogger.php:267
MediaWiki\Logger\LegacyLogger\__construct
__construct( $channel)
DefinitionLegacyLogger.php:90
MediaWiki\Logger\LegacyLogger\formatAsWfDebug
static formatAsWfDebug( $channel, $message, $context)
Format a message as wfDebug() would have formatted it.
DefinitionLegacyLogger.php:315
MediaWiki\Logger\LegacyLogger\$levelMapping
static array $levelMapping
Convert \Psr\Log\LogLevel constants into int for sensible comparisons These are the same values that ...
DefinitionLegacyLogger.php:61
MediaWiki\Logger\LoggerFactory\getContext
static getContext()
Get a logging context, which can be used to add information to all log events.
DefinitionLoggerFactory.php:89
MediaWiki\WikiMap\WikiMap
Tools for dealing with other locally-hosted wikis.
DefinitionWikiMap.php:19
UDPTransport
A generic class to send a message over UDP.
DefinitionUDPTransport.php:19
$wgLogExceptionBacktrace
$wgLogExceptionBacktrace
Config variable stub for the LogExceptionBacktrace setting, for use by phpdoc and IDEs.
Definitionconfig-vars.php:3312
$wgDBerrorLogTZ
$wgDBerrorLogTZ
Config variable stub for the DBerrorLogTZ setting, for use by phpdoc and IDEs.
Definitionconfig-vars.php:1209
$wgDBerrorLog
$wgDBerrorLog
Config variable stub for the DBerrorLog setting, for use by phpdoc and IDEs.
Definitionconfig-vars.php:1203
$wgDebugRawPage
$wgDebugRawPage
Config variable stub for the DebugRawPage setting, for use by phpdoc and IDEs.
Definitionconfig-vars.php:3258
$wgShowDebug
$wgShowDebug
Config variable stub for the ShowDebug setting, for use by phpdoc and IDEs.
Definitionconfig-vars.php:3294
$wgDebugToolbar
$wgDebugToolbar
Config variable stub for the DebugToolbar setting, for use by phpdoc and IDEs.
Definitionconfig-vars.php:3408
$wgDebugLogGroups
$wgDebugLogGroups
Config variable stub for the DebugLogGroups setting, for use by phpdoc and IDEs.
Definitionconfig-vars.php:3282
$wgDebugLogFile
$wgDebugLogFile
Config variable stub for the DebugLogFile setting, for use by phpdoc and IDEs.
Definitionconfig-vars.php:3240
MediaWiki\Logger
DefinitionConsoleLogger.php:3

[8]ページ先頭

©2009-2025 Movatter.jp