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 former
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 === 'wfDebug' ) {
169 // wfDebug messages are emitted if a catch all logging file has
170 // been specified. Checked explicitly so that 'private' flagged
171 // messages are not discarded by unset $wgDebugLogGroups channel
173 $shouldEmit = $wgDebugLogFile != '';
175 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
176 $logConfig = $wgDebugLogGroups[$channel];
178 if ( is_array( $logConfig ) ) {
180 if ( isset( $logConfig['sample'] ) ) {
181 // Emit randomly with a 1 in 'sample' chance for each message.
182 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
185 if ( isset( $logConfig['level'] ) ) {
186 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
189 // Emit unless the config value is explictly false.
190 $shouldEmit = $logConfig !== false;
193 } elseif ( isset( $context['private'] ) && $context['private'] ) {
194 // Don't emit if the message didn't match previous checks based on
195 // the channel and the event is marked as private. This check
196 // discards messages sent via wfDebugLog() with dest == 'private'
197 // and no explicit wgDebugLogGroups configuration.
200 // Default return value is the same as the historic wfDebug
201 // method: emit if $wgDebugLogFile has been set.
202 $shouldEmit = $wgDebugLogFile != '';
211 * Messages to the 'wfDebug' and 'wfLogDBError' channels receive special formatting to mimic the
212 * historic output of the functions of the same name. All other channel values are formatted
213 * based on the historic output of the `wfDebugLog()` global function.
215 * @param string $channel
216 * @param string $message
217 * @param array $context
220 public static function format( $channel, $message, $context ) {
221 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
223 if ( $channel === 'wfDebug' ) {
224 $text = self
::formatAsWfDebug( $channel, $message, $context );
226 } elseif ( $channel === 'wfLogDBError' ) {
227 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
229 } elseif ( $channel === 'profileoutput' ) {
230 // Legacy wfLogProfilingData formatitng
232 if ( isset( $context['forwarded_for'] ) ) {
233 $forward = " forwarded for {$context['forwarded_for']}";
235 if ( isset( $context['client_ip'] ) ) {
236 $forward .= " client IP {$context['client_ip']}";
238 if ( isset( $context['from'] ) ) {
239 $forward .= " from {$context['from']}";
242 $forward = "\t(proxied via {$context['proxy']}{$forward})";
244 if ( $context['anon'] ) {
247 if ( !isset( $context['url'] ) ) {
248 $context['url'] = 'n/a';
251 $log = sprintf( "%s\t%04.3f\t%s%s\n",
252 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
254 $text = self
::formatAsWfDebugLog(
255 $channel, $log . $context['output'], $context );
257 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
258 $text = self
::formatAsWfDebug(
259 $channel, "[{$channel}] {$message}", $context );
262 // Default formatting is wfDebugLog's historic style
263 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
266 // Append stacktrace of exception if available
267 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
268 $e = $context['exception'];
271 if ( $e instanceof Exception
) {
272 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
274 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
275 // Exception has already been unpacked as structured data
276 $backtrace = $e['trace'];
280 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
285 return self
::interpolate( $text, $context );
289 * Format a message as `wfDebug()` would have formatted it.
291 * @param string $channel
292 * @param string $message
293 * @param array $context
296 protected static function formatAsWfDebug( $channel, $message, $context ) {
297 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
298 if ( isset( $context['seconds_elapsed'] ) ) {
299 // Prepend elapsed request time and real memory usage with two
301 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
303 if ( isset( $context['prefix'] ) ) {
304 $text = "{$context['prefix']}{$text}";
310 * Format a message as `wfLogDBError()` would have formatted it.
312 * @param string $channel
313 * @param string $message
314 * @param array $context
317 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
318 global $wgDBerrorLogTZ;
319 static $cachedTimezone = null;
321 if ( !$cachedTimezone ) {
322 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
325 $d = date_create( 'now', $cachedTimezone );
326 $date = $d->format( 'D M j G:i:s T Y' );
328 $host = wfHostname();
331 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
336 * Format a message as `wfDebugLog() would have formatted it.
338 * @param string $channel
339 * @param string $message
340 * @param array $context
343 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
344 $time = wfTimestamp( TS_DB
);
346 $host = wfHostname();
347 $text = "{$time} {$host} {$wiki}: {$message}\n";
352 * Interpolate placeholders in logging message.
354 * @param string $message
355 * @param array $context
356 * @return string Interpolated message
358 public static function interpolate( $message, array $context ) {
359 if ( strpos( $message, '{' ) !== false ) {
361 foreach ( $context as $key => $val ) {
362 $replace['{' . $key . '}'] = self
::flatten( $val );
364 $message = strtr( $message, $replace );
370 * Convert a logging context element to a string suitable for
376 protected static function flatten( $item ) {
377 if ( null === $item ) {
381 if ( is_bool( $item ) ) {
382 return $item ?
'true' : 'false';
385 if ( is_float( $item ) ) {
386 if ( is_infinite( $item ) ) {
387 return ( $item > 0 ?
'' : '-' ) . 'INF';
389 if ( is_nan( $item ) ) {
392 return (string)$item;
395 if ( is_scalar( $item ) ) {
396 return (string)$item;
399 if ( is_array( $item ) ) {
400 return '[Array(' . count( $item ) . ')]';
403 if ( $item instanceof \DateTime
) {
404 return $item->format( 'c' );
407 if ( $item instanceof Exception
) {
408 return '[Exception ' . get_class( $item ) . '( ' .
409 $item->getFile() . ':' . $item->getLine() . ') ' .
410 $item->getMessage() . ']';
413 if ( is_object( $item ) ) {
414 if ( method_exists( $item, '__toString' ) ) {
415 return (string)$item;
418 return '[Object ' . get_class( $item ) . ']';
421 if ( is_resource( $item ) ) {
422 return '[Resource ' . get_resource_type( $item ) . ']';
425 return '[Unknown ' . gettype( $item ) . ']';
429 * Select the appropriate log output destination for the given log event.
431 * If the event context contains 'destination'
433 * @param string $channel
434 * @param string $message
435 * @param array $context
438 protected static function destination( $channel, $message, $context ) {
439 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
441 // Default destination is the debug log file as historically used by
442 // the wfDebug function.
443 $destination = $wgDebugLogFile;
445 if ( isset( $context['destination'] ) ) {
446 // Use destination explicitly provided in context
447 $destination = $context['destination'];
449 } elseif ( $channel === 'wfDebug' ) {
450 $destination = $wgDebugLogFile;
452 } elseif ( $channel === 'wfLogDBError' ) {
453 $destination = $wgDBerrorLog;
455 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
456 $logConfig = $wgDebugLogGroups[$channel];
458 if ( is_array( $logConfig ) ) {
459 $destination = $logConfig['destination'];
461 $destination = strval( $logConfig );
469 * Log to a file without getting "file size exceeded" signals.
471 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
472 * lines to the specified port, prefixed by the specified prefix and a space.
474 * @param string $text
475 * @param string $file Filename
477 public static function emit( $text, $file ) {
478 if ( substr( $file, 0, 4 ) == 'udp:' ) {
479 $transport = UDPTransport
::newFromString( $file );
480 $transport->emit( $text );
482 \Wikimedia\
suppressWarnings();
483 $exists = file_exists( $file );
484 $size = $exists ?
filesize( $file ) : false;
486 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
488 file_put_contents( $file, $text, FILE_APPEND
);
490 \Wikimedia\restoreWarnings
();