MediaWiki REL1_27
LegacyLogger.php
Go to the documentation of this file.
1<?php
22
23use DateTimeZone;
24use Exception;
27use Psr\Log\AbstractLogger;
28use Psr\Log\LogLevel;
30
49class LegacyLogger extends AbstractLogger {
50
54 protected $channel;
55
62 protected static $levelMapping = [
63 LogLevel::DEBUG => 100,
64 LogLevel::INFO => 200,
65 LogLevel::NOTICE => 250,
66 LogLevel::WARNING => 300,
67 LogLevel::ERROR => 400,
68 LogLevel::CRITICAL => 500,
69 LogLevel::ALERT => 550,
70 LogLevel::EMERGENCY => 600,
71 ];
72
76 public function __construct( $channel ) {
77 $this->channel = $channel;
78 }
79
87 public function log( $level, $message, array $context = [] ) {
88 if ( self::shouldEmit( $this->channel, $message, $level, $context ) ) {
89 $text = self::format( $this->channel, $message, $context );
90 $destination = self::destination( $this->channel, $message, $context );
91 self::emit( $text, $destination );
92 }
93 if ( !isset( $context['private'] ) || !$context['private'] ) {
94 // Add to debug toolbar if not marked as "private"
95 MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
96 }
97 }
98
109 public static function shouldEmit( $channel, $message, $level, $context ) {
111
112 if ( $channel === 'wfLogDBError' ) {
113 // wfLogDBError messages are emitted if a database log location is
114 // specfied.
115 $shouldEmit = (bool)$wgDBerrorLog;
116
117 } elseif ( $channel === 'wfErrorLog' ) {
118 // All messages on the wfErrorLog channel should be emitted.
119 $shouldEmit = true;
120
121 } elseif ( $channel === 'wfDebug' ) {
122 // wfDebug messages are emitted if a catch all logging file has
123 // been specified. Checked explicitly so that 'private' flagged
124 // messages are not discarded by unset $wgDebugLogGroups channel
125 // handling below.
126 $shouldEmit = $wgDebugLogFile != '';
127
128 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
129 $logConfig = $wgDebugLogGroups[$channel];
130
131 if ( is_array( $logConfig ) ) {
132 $shouldEmit = true;
133 if ( isset( $logConfig['sample'] ) ) {
134 // Emit randomly with a 1 in 'sample' chance for each message.
135 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
136 }
137
138 if ( isset( $logConfig['level'] ) ) {
139 if ( is_string( $level ) ) {
140 $level = self::$levelMapping[$level];
141 }
142 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
143 }
144 } else {
145 // Emit unless the config value is explictly false.
146 $shouldEmit = $logConfig !== false;
147 }
148
149 } elseif ( isset( $context['private'] ) && $context['private'] ) {
150 // Don't emit if the message didn't match previous checks based on
151 // the channel and the event is marked as private. This check
152 // discards messages sent via wfDebugLog() with dest == 'private'
153 // and no explicit wgDebugLogGroups configuration.
154 $shouldEmit = false;
155 } else {
156 // Default return value is the same as the historic wfDebug
157 // method: emit if $wgDebugLogFile has been set.
158 $shouldEmit = $wgDebugLogFile != '';
159 }
160
161 return $shouldEmit;
162 }
163
177 public static function format( $channel, $message, $context ) {
179
180 if ( $channel === 'wfDebug' ) {
181 $text = self::formatAsWfDebug( $channel, $message, $context );
182
183 } elseif ( $channel === 'wfLogDBError' ) {
184 $text = self::formatAsWfLogDBError( $channel, $message, $context );
185
186 } elseif ( $channel === 'wfErrorLog' ) {
187 $text = "{$message}\n";
188
189 } elseif ( $channel === 'profileoutput' ) {
190 // Legacy wfLogProfilingData formatitng
191 $forward = '';
192 if ( isset( $context['forwarded_for'] ) ) {
193 $forward = " forwarded for {$context['forwarded_for']}";
194 }
195 if ( isset( $context['client_ip'] ) ) {
196 $forward .= " client IP {$context['client_ip']}";
197 }
198 if ( isset( $context['from'] ) ) {
199 $forward .= " from {$context['from']}";
200 }
201 if ( $forward ) {
202 $forward = "\t(proxied via {$context['proxy']}{$forward})";
203 }
204 if ( $context['anon'] ) {
205 $forward .= ' anon';
206 }
207 if ( !isset( $context['url'] ) ) {
208 $context['url'] = 'n/a';
209 }
210
211 $log = sprintf( "%s\t%04.3f\t%s%s\n",
212 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
213
215 $channel, $log . $context['output'], $context );
216
217 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
218 $text = self::formatAsWfDebug(
219 $channel, "[{$channel}] {$message}", $context );
220
221 } else {
222 // Default formatting is wfDebugLog's historic style
223 $text = self::formatAsWfDebugLog( $channel, $message, $context );
224 }
225
226 // Append stacktrace of exception if available
227 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
228 $e = $context['exception'];
229 $backtrace = false;
230
231 if ( $e instanceof Exception ) {
233
234 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
235 // Exception has already been unpacked as structured data
236 $backtrace = $e['trace'];
237 }
238
239 if ( $backtrace ) {
240 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
241 "\n";
242 }
243 }
244
245 return self::interpolate( $text, $context );
246 }
247
256 protected static function formatAsWfDebug( $channel, $message, $context ) {
257 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
258 if ( isset( $context['seconds_elapsed'] ) ) {
259 // Prepend elapsed request time and real memory usage with two
260 // trailing spaces.
261 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
262 }
263 if ( isset( $context['prefix'] ) ) {
264 $text = "{$context['prefix']}{$text}";
265 }
266 return "{$text}\n";
267 }
268
277 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
279 static $cachedTimezone = null;
280
281 if ( !$cachedTimezone ) {
282 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
283 }
284
285 $d = date_create( 'now', $cachedTimezone );
286 $date = $d->format( 'D M j G:i:s T Y' );
287
288 $host = wfHostname();
289 $wiki = wfWikiID();
290
291 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
292 return $text;
293 }
294
302 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
304 $wiki = wfWikiID();
305 $host = wfHostname();
306 $text = "{$time} {$host} {$wiki}: {$message}\n";
307 return $text;
308 }
309
317 public static function interpolate( $message, array $context ) {
318 if ( strpos( $message, '{' ) !== false ) {
319 $replace = [];
320 foreach ( $context as $key => $val ) {
321 $replace['{' . $key . '}'] = self::flatten( $val );
322 }
323 $message = strtr( $message, $replace );
324 }
325 return $message;
326 }
327
335 protected static function flatten( $item ) {
336 if ( null === $item ) {
337 return '[Null]';
338 }
339
340 if ( is_bool( $item ) ) {
341 return $item ? 'true' : 'false';
342 }
343
344 if ( is_float( $item ) ) {
345 if ( is_infinite( $item ) ) {
346 return ( $item > 0 ? '' : '-' ) . 'INF';
347 }
348 if ( is_nan( $item ) ) {
349 return 'NaN';
350 }
351 return $item;
352 }
353
354 if ( is_scalar( $item ) ) {
355 return (string)$item;
356 }
357
358 if ( is_array( $item ) ) {
359 return '[Array(' . count( $item ) . ')]';
360 }
361
362 if ( $item instanceof \DateTime ) {
363 return $item->format( 'c' );
364 }
365
366 if ( $item instanceof Exception ) {
367 return '[Exception ' . get_class( $item ) . '( ' .
368 $item->getFile() . ':' . $item->getLine() . ') ' .
369 $item->getMessage() . ']';
370 }
371
372 if ( is_object( $item ) ) {
373 if ( method_exists( $item, '__toString' ) ) {
374 return (string)$item;
375 }
376
377 return '[Object ' . get_class( $item ) . ']';
378 }
379
380 if ( is_resource( $item ) ) {
381 return '[Resource ' . get_resource_type( $item ) . ']';
382 }
383
384 return '[Unknown ' . gettype( $item ) . ']';
385 }
386
397 protected static function destination( $channel, $message, $context ) {
399
400 // Default destination is the debug log file as historically used by
401 // the wfDebug function.
402 $destination = $wgDebugLogFile;
403
404 if ( isset( $context['destination'] ) ) {
405 // Use destination explicitly provided in context
406 $destination = $context['destination'];
407
408 } elseif ( $channel === 'wfDebug' ) {
409 $destination = $wgDebugLogFile;
410
411 } elseif ( $channel === 'wfLogDBError' ) {
412 $destination = $wgDBerrorLog;
413
414 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
415 $logConfig = $wgDebugLogGroups[$channel];
416
417 if ( is_array( $logConfig ) ) {
418 $destination = $logConfig['destination'];
419 } else {
420 $destination = strval( $logConfig );
421 }
422 }
423
424 return $destination;
425 }
426
437 public static function emit( $text, $file ) {
438 if ( substr( $file, 0, 4 ) == 'udp:' ) {
439 $transport = UDPTransport::newFromString( $file );
440 $transport->emit( $text );
441 } else {
442 \MediaWiki\suppressWarnings();
443 $exists = file_exists( $file );
444 $size = $exists ? filesize( $file ) : false;
445 if ( !$exists ||
446 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
447 ) {
448 file_put_contents( $file, $text, FILE_APPEND );
449 }
450 \MediaWiki\restoreWarnings();
451 }
452 }
453
454}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgLogExceptionBacktrace
If true, send the exception backtrace to the error log.
$wgDBerrorLogTZ
Timezone to use in the error log.
$wgDBerrorLog
File to log database errors to.
$wgDebugLogGroups
Map of string log group names to log destinations.
$wgDebugLogFile
Filename for debug logging.
wfHostname()
Fetch server name for use in error reporting etc.
const TS_DB
MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
New debugger system that outputs a toolbar on page view.
Definition MWDebug.php:31
static debugMsg( $str, $context=[])
This is a method to pass messages from wfDebug to the pretty debugger.
Definition MWDebug.php:314
Handler class for MWExceptions.
static prettyPrintTrace(array $trace, $pad='')
Generate a string representation of a stacktrace.
static getRedactedTrace( $e)
Return a copy of an exception's backtrace as an array.
PSR-3 logger that mimics the historic implementation of MediaWiki's wfErrorLog logging implementation...
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.
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 $levelMapping
Convert \Psr\Log\LogLevel constants into int for sane comparisons These are the same values that Monl...
A generic class to send a message over UDP.
static newFromString( $info)
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
the array() calling protocol came about after MediaWiki 1.4rc1.
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1615
returning false will NOT prevent logging $e
Definition hooks.txt:1940
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
$context
Definition load.php:44