3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Logger
;
26 use MWExceptionHandler
;
27 use Psr\Log\AbstractLogger
;
32 * PSR-3 logger that mimics the historic implementation of MediaWiki's
33 * wfErrorLog logging implementation.
35 * This logger is configured by the following global configuration variables:
37 * - `$wgDebugLogGroups`
41 * See documentation in DefaultSettings.php for detailed explanations of each
44 * @see \MediaWiki\Logger\LoggerFactory
46 * @copyright © 2014 Wikimedia Foundation and contributors
48 class LegacyLogger
extends AbstractLogger
{
51 * @var string $channel
56 * Convert \Psr\Log\LogLevel constants into int for sane comparisons
57 * These are the same values that Monlog uses
59 * @var array $levelMapping
61 protected static $levelMapping = [
62 LogLevel
::DEBUG
=> 100,
63 LogLevel
::INFO
=> 200,
64 LogLevel
::NOTICE
=> 250,
65 LogLevel
::WARNING
=> 300,
66 LogLevel
::ERROR
=> 400,
67 LogLevel
::CRITICAL
=> 500,
68 LogLevel
::ALERT
=> 550,
69 LogLevel
::EMERGENCY
=> 600,
75 protected static $dbChannels = [
77 'DBConnection' => true
81 * @param string $channel
83 public function __construct( $channel ) {
84 $this->channel
= $channel;
88 * Logs with an arbitrary level.
90 * @param string|int $level
91 * @param string $message
92 * @param array $context
95 public function log( $level, $message, array $context = [] ) {
98 if ( is_string( $level ) ) {
99 $level = self
::$levelMapping[$level];
101 if ( $this->channel
=== 'DBQuery'
102 && isset( $context['method'] )
103 && isset( $context['master'] )
104 && isset( $context['runtime'] )
106 // Also give the query information to the MWDebug tools
107 $enabled = MWDebug
::query(
114 // If we the toolbar was enabled, return early so that we don't
115 // also log the query to the main debug output.
120 // If this is a DB-related error, and the site has $wgDBerrorLog
121 // configured, rewrite the channel as wfLogDBError instead.
122 // Likewise, if the site does not use $wgDBerrorLog, it should
123 // configurable like any other channel via $wgDebugLogGroups
124 // or $wgMWLoggerDefaultSpi.
125 if ( isset( self
::$dbChannels[$this->channel
] )
126 && $level >= self
::$levelMapping[LogLevel
::ERROR
]
129 // Format and write DB errors to the legacy locations
130 $effectiveChannel = 'wfLogDBError';
132 $effectiveChannel = $this->channel
;
135 if ( self
::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
136 $text = self
::format( $effectiveChannel, $message, $context );
137 $destination = self
::destination( $effectiveChannel, $message, $context );
138 self
::emit( $text, $destination );
140 if ( !isset( $context['private'] ) ||
!$context['private'] ) {
141 // Add to debug toolbar if not marked as "private"
142 MWDebug
::debugMsg( $message, [ 'channel' => $this->channel
] +
$context );
147 * Determine if the given message should be emitted or not.
149 * @param string $channel
150 * @param string $message
151 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
152 * @param array $context
153 * @return bool True if message should be sent to disk/network, false
156 public static function shouldEmit( $channel, $message, $level, $context ) {
157 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
159 if ( is_string( $level ) ) {
160 $level = self
::$levelMapping[$level];
163 if ( $channel === 'wfLogDBError' ) {
164 // wfLogDBError messages are emitted if a database log location is
166 $shouldEmit = (bool)$wgDBerrorLog;
168 } elseif ( $channel === 'wfErrorLog' ) {
169 // All messages on the wfErrorLog channel should be emitted.
172 } elseif ( $channel === 'wfDebug' ) {
173 // wfDebug messages are emitted if a catch all logging file has
174 // been specified. Checked explicitly so that 'private' flagged
175 // messages are not discarded by unset $wgDebugLogGroups channel
177 $shouldEmit = $wgDebugLogFile != '';
179 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
180 $logConfig = $wgDebugLogGroups[$channel];
182 if ( is_array( $logConfig ) ) {
184 if ( isset( $logConfig['sample'] ) ) {
185 // Emit randomly with a 1 in 'sample' chance for each message.
186 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
189 if ( isset( $logConfig['level'] ) ) {
190 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
193 // Emit unless the config value is explictly false.
194 $shouldEmit = $logConfig !== false;
197 } elseif ( isset( $context['private'] ) && $context['private'] ) {
198 // Don't emit if the message didn't match previous checks based on
199 // the channel and the event is marked as private. This check
200 // discards messages sent via wfDebugLog() with dest == 'private'
201 // and no explicit wgDebugLogGroups configuration.
204 // Default return value is the same as the historic wfDebug
205 // method: emit if $wgDebugLogFile has been set.
206 $shouldEmit = $wgDebugLogFile != '';
215 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
216 * receive special formatting to mimic the historic output of the functions
217 * of the same name. All other channel values are formatted based on the
218 * historic output of the `wfDebugLog()` global function.
220 * @param string $channel
221 * @param string $message
222 * @param array $context
225 public static function format( $channel, $message, $context ) {
226 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
228 if ( $channel === 'wfDebug' ) {
229 $text = self
::formatAsWfDebug( $channel, $message, $context );
231 } elseif ( $channel === 'wfLogDBError' ) {
232 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
234 } elseif ( $channel === 'wfErrorLog' ) {
235 $text = "{$message}\n";
237 } elseif ( $channel === 'profileoutput' ) {
238 // Legacy wfLogProfilingData formatitng
240 if ( isset( $context['forwarded_for'] ) ) {
241 $forward = " forwarded for {$context['forwarded_for']}";
243 if ( isset( $context['client_ip'] ) ) {
244 $forward .= " client IP {$context['client_ip']}";
246 if ( isset( $context['from'] ) ) {
247 $forward .= " from {$context['from']}";
250 $forward = "\t(proxied via {$context['proxy']}{$forward})";
252 if ( $context['anon'] ) {
255 if ( !isset( $context['url'] ) ) {
256 $context['url'] = 'n/a';
259 $log = sprintf( "%s\t%04.3f\t%s%s\n",
260 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
262 $text = self
::formatAsWfDebugLog(
263 $channel, $log . $context['output'], $context );
265 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
266 $text = self
::formatAsWfDebug(
267 $channel, "[{$channel}] {$message}", $context );
270 // Default formatting is wfDebugLog's historic style
271 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
274 // Append stacktrace of exception if available
275 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
276 $e = $context['exception'];
279 if ( $e instanceof Exception
) {
280 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
282 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
283 // Exception has already been unpacked as structured data
284 $backtrace = $e['trace'];
288 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
293 return self
::interpolate( $text, $context );
297 * Format a message as `wfDebug()` would have formatted it.
299 * @param string $channel
300 * @param string $message
301 * @param array $context
304 protected static function formatAsWfDebug( $channel, $message, $context ) {
305 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
306 if ( isset( $context['seconds_elapsed'] ) ) {
307 // Prepend elapsed request time and real memory usage with two
309 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
311 if ( isset( $context['prefix'] ) ) {
312 $text = "{$context['prefix']}{$text}";
318 * Format a message as `wfLogDBError()` would have formatted it.
320 * @param string $channel
321 * @param string $message
322 * @param array $context
325 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
326 global $wgDBerrorLogTZ;
327 static $cachedTimezone = null;
329 if ( !$cachedTimezone ) {
330 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
333 $d = date_create( 'now', $cachedTimezone );
334 $date = $d->format( 'D M j G:i:s T Y' );
336 $host = wfHostname();
339 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
344 * Format a message as `wfDebugLog() would have formatted it.
346 * @param string $channel
347 * @param string $message
348 * @param array $context
351 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
352 $time = wfTimestamp( TS_DB
);
354 $host = wfHostname();
355 $text = "{$time} {$host} {$wiki}: {$message}\n";
360 * Interpolate placeholders in logging message.
362 * @param string $message
363 * @param array $context
364 * @return string Interpolated message
366 public static function interpolate( $message, array $context ) {
367 if ( strpos( $message, '{' ) !== false ) {
369 foreach ( $context as $key => $val ) {
370 $replace['{' . $key . '}'] = self
::flatten( $val );
372 $message = strtr( $message, $replace );
378 * Convert a logging context element to a string suitable for
384 protected static function flatten( $item ) {
385 if ( null === $item ) {
389 if ( is_bool( $item ) ) {
390 return $item ?
'true' : 'false';
393 if ( is_float( $item ) ) {
394 if ( is_infinite( $item ) ) {
395 return ( $item > 0 ?
'' : '-' ) . 'INF';
397 if ( is_nan( $item ) ) {
400 return (string)$item;
403 if ( is_scalar( $item ) ) {
404 return (string)$item;
407 if ( is_array( $item ) ) {
408 return '[Array(' . count( $item ) . ')]';
411 if ( $item instanceof \DateTime
) {
412 return $item->format( 'c' );
415 if ( $item instanceof Exception
) {
416 return '[Exception ' . get_class( $item ) . '( ' .
417 $item->getFile() . ':' . $item->getLine() . ') ' .
418 $item->getMessage() . ']';
421 if ( is_object( $item ) ) {
422 if ( method_exists( $item, '__toString' ) ) {
423 return (string)$item;
426 return '[Object ' . get_class( $item ) . ']';
429 if ( is_resource( $item ) ) {
430 return '[Resource ' . get_resource_type( $item ) . ']';
433 return '[Unknown ' . gettype( $item ) . ']';
437 * Select the appropriate log output destination for the given log event.
439 * If the event context contains 'destination'
441 * @param string $channel
442 * @param string $message
443 * @param array $context
446 protected static function destination( $channel, $message, $context ) {
447 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
449 // Default destination is the debug log file as historically used by
450 // the wfDebug function.
451 $destination = $wgDebugLogFile;
453 if ( isset( $context['destination'] ) ) {
454 // Use destination explicitly provided in context
455 $destination = $context['destination'];
457 } elseif ( $channel === 'wfDebug' ) {
458 $destination = $wgDebugLogFile;
460 } elseif ( $channel === 'wfLogDBError' ) {
461 $destination = $wgDBerrorLog;
463 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
464 $logConfig = $wgDebugLogGroups[$channel];
466 if ( is_array( $logConfig ) ) {
467 $destination = $logConfig['destination'];
469 $destination = strval( $logConfig );
477 * Log to a file without getting "file size exceeded" signals.
479 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
480 * lines to the specified port, prefixed by the specified prefix and a space.
482 * @param string $text
483 * @param string $file Filename
485 public static function emit( $text, $file ) {
486 if ( substr( $file, 0, 4 ) == 'udp:' ) {
487 $transport = UDPTransport
::newFromString( $file );
488 $transport->emit( $text );
490 \Wikimedia\
suppressWarnings();
491 $exists = file_exists( $file );
492 $size = $exists ?
filesize( $file ) : false;
494 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
496 file_put_contents( $file, $text, FILE_APPEND
);
498 \Wikimedia\restoreWarnings
();