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
;
28 use MWExceptionHandler
;
29 use Psr\Log\AbstractLogger
;
35 * PSR-3 logger that mimics the historic implementation of MediaWiki's former
36 * wfErrorLog logging implementation.
38 * This logger is configured by the following global configuration variables:
40 * - `$wgDebugLogGroups`
44 * See documentation in DefaultSettings.php for detailed explanations of each
47 * @see \MediaWiki\Logger\LoggerFactory
49 * @copyright © 2014 Wikimedia Foundation and contributors
51 class LegacyLogger
extends AbstractLogger
{
54 * @var string $channel
59 * Convert \Psr\Log\LogLevel constants into int for sane comparisons
60 * These are the same values that Monlog uses
62 * @var array $levelMapping
64 protected static $levelMapping = [
65 LogLevel
::DEBUG
=> 100,
66 LogLevel
::INFO
=> 200,
67 LogLevel
::NOTICE
=> 250,
68 LogLevel
::WARNING
=> 300,
69 LogLevel
::ERROR
=> 400,
70 LogLevel
::CRITICAL
=> 500,
71 LogLevel
::ALERT
=> 550,
72 LogLevel
::EMERGENCY
=> 600,
78 protected static $dbChannels = [
80 'DBConnection' => true
84 * @param string $channel
86 public function __construct( $channel ) {
87 $this->channel
= $channel;
91 * Logs with an arbitrary level.
93 * @param string|int $level
94 * @param string $message
95 * @param array $context
98 public function log( $level, $message, array $context = [] ) {
101 if ( is_string( $level ) ) {
102 $level = self
::$levelMapping[$level];
104 if ( $this->channel
=== 'DBQuery'
105 && isset( $context['method'] )
106 && isset( $context['master'] )
107 && isset( $context['runtime'] )
109 // Also give the query information to the MWDebug tools
110 $enabled = MWDebug
::query(
117 // If we the toolbar was enabled, return early so that we don't
118 // also log the query to the main debug output.
123 // If this is a DB-related error, and the site has $wgDBerrorLog
124 // configured, rewrite the channel as wfLogDBError instead.
125 // Likewise, if the site does not use $wgDBerrorLog, it should
126 // configurable like any other channel via $wgDebugLogGroups
127 // or $wgMWLoggerDefaultSpi.
128 if ( isset( self
::$dbChannels[$this->channel
] )
129 && $level >= self
::$levelMapping[LogLevel
::ERROR
]
132 // Format and write DB errors to the legacy locations
133 $effectiveChannel = 'wfLogDBError';
135 $effectiveChannel = $this->channel
;
138 if ( self
::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
139 $text = self
::format( $effectiveChannel, $message, $context );
140 $destination = self
::destination( $effectiveChannel, $message, $context );
141 self
::emit( $text, $destination );
143 if ( !isset( $context['private'] ) ||
!$context['private'] ) {
144 // Add to debug toolbar if not marked as "private"
145 MWDebug
::debugMsg( $message, [ 'channel' => $this->channel
] +
$context );
150 * Determine if the given message should be emitted or not.
152 * @param string $channel
153 * @param string $message
154 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
155 * @param array $context
156 * @return bool True if message should be sent to disk/network, false
159 public static function shouldEmit( $channel, $message, $level, $context ) {
160 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
162 if ( is_string( $level ) ) {
163 $level = self
::$levelMapping[$level];
166 if ( $channel === 'wfLogDBError' ) {
167 // wfLogDBError messages are emitted if a database log location is
169 $shouldEmit = (bool)$wgDBerrorLog;
171 } elseif ( $channel === 'wfDebug' ) {
172 // wfDebug messages are emitted if a catch all logging file has
173 // been specified. Checked explicitly so that 'private' flagged
174 // messages are not discarded by unset $wgDebugLogGroups channel
176 $shouldEmit = $wgDebugLogFile != '';
178 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
179 $logConfig = $wgDebugLogGroups[$channel];
181 if ( is_array( $logConfig ) ) {
183 if ( isset( $logConfig['sample'] ) ) {
184 // Emit randomly with a 1 in 'sample' chance for each message.
185 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
188 if ( isset( $logConfig['level'] ) ) {
189 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
192 // Emit unless the config value is explictly false.
193 $shouldEmit = $logConfig !== false;
196 } elseif ( isset( $context['private'] ) && $context['private'] ) {
197 // Don't emit if the message didn't match previous checks based on
198 // the channel and the event is marked as private. This check
199 // discards messages sent via wfDebugLog() with dest == 'private'
200 // and no explicit wgDebugLogGroups configuration.
203 // Default return value is the same as the historic wfDebug
204 // method: emit if $wgDebugLogFile has been set.
205 $shouldEmit = $wgDebugLogFile != '';
214 * Messages to the 'wfDebug' and 'wfLogDBError' channels receive special formatting to mimic the
215 * historic output of the functions of the same name. All other channel values are formatted
216 * based on the historic output of the `wfDebugLog()` global function.
218 * @param string $channel
219 * @param string $message
220 * @param array $context
223 public static function format( $channel, $message, $context ) {
224 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
226 if ( $channel === 'wfDebug' ) {
227 $text = self
::formatAsWfDebug( $channel, $message, $context );
229 } elseif ( $channel === 'wfLogDBError' ) {
230 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
232 } elseif ( $channel === 'profileoutput' ) {
233 // Legacy wfLogProfilingData formatitng
235 if ( isset( $context['forwarded_for'] ) ) {
236 $forward = " forwarded for {$context['forwarded_for']}";
238 if ( isset( $context['client_ip'] ) ) {
239 $forward .= " client IP {$context['client_ip']}";
241 if ( isset( $context['from'] ) ) {
242 $forward .= " from {$context['from']}";
245 $forward = "\t(proxied via {$context['proxy']}{$forward})";
247 if ( $context['anon'] ) {
250 if ( !isset( $context['url'] ) ) {
251 $context['url'] = 'n/a';
254 $log = sprintf( "%s\t%04.3f\t%s%s\n",
255 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
257 $text = self
::formatAsWfDebugLog(
258 $channel, $log . $context['output'], $context );
260 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
261 $text = self
::formatAsWfDebug(
262 $channel, "[{$channel}] {$message}", $context );
265 // Default formatting is wfDebugLog's historic style
266 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
269 // Append stacktrace of exception if available
270 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
271 $e = $context['exception'];
274 if ( $e instanceof Throwable ||
$e instanceof Exception
) {
275 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
277 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
278 // Exception has already been unpacked as structured data
279 $backtrace = $e['trace'];
283 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
288 return self
::interpolate( $text, $context );
292 * Format a message as `wfDebug()` would have formatted it.
294 * @param string $channel
295 * @param string $message
296 * @param array $context
299 protected static function formatAsWfDebug( $channel, $message, $context ) {
300 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
301 if ( isset( $context['seconds_elapsed'] ) ) {
302 // Prepend elapsed request time and real memory usage with two
304 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
306 if ( isset( $context['prefix'] ) ) {
307 $text = "{$context['prefix']}{$text}";
313 * Format a message as `wfLogDBError()` would have formatted it.
315 * @param string $channel
316 * @param string $message
317 * @param array $context
320 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
321 global $wgDBerrorLogTZ;
322 static $cachedTimezone = null;
324 if ( !$cachedTimezone ) {
325 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
328 $d = date_create( 'now', $cachedTimezone );
329 $date = $d->format( 'D M j G:i:s T Y' );
331 $host = wfHostname();
332 $wiki = WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() );
334 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
339 * Format a message as `wfDebugLog() would have formatted it.
341 * @param string $channel
342 * @param string $message
343 * @param array $context
346 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
347 $time = wfTimestamp( TS_DB
);
348 $wiki = WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() );
349 $host = wfHostname();
350 $text = "{$time} {$host} {$wiki}: {$message}\n";
355 * Interpolate placeholders in logging message.
357 * @param string $message
358 * @param array $context
359 * @return string Interpolated message
361 public static function interpolate( $message, array $context ) {
362 if ( strpos( $message, '{' ) !== false ) {
364 foreach ( $context as $key => $val ) {
365 $replace['{' . $key . '}'] = self
::flatten( $val );
367 $message = strtr( $message, $replace );
373 * Convert a logging context element to a string suitable for
379 protected static function flatten( $item ) {
380 if ( $item === null ) {
384 if ( is_bool( $item ) ) {
385 return $item ?
'true' : 'false';
388 if ( is_float( $item ) ) {
389 if ( is_infinite( $item ) ) {
390 return ( $item > 0 ?
'' : '-' ) . 'INF';
392 if ( is_nan( $item ) ) {
395 return (string)$item;
398 if ( is_scalar( $item ) ) {
399 return (string)$item;
402 if ( is_array( $item ) ) {
403 return '[Array(' . count( $item ) . ')]';
406 if ( $item instanceof \DateTime
) {
407 return $item->format( 'c' );
410 if ( $item instanceof Throwable ||
$item instanceof Exception
) {
411 $which = $item instanceof Error ?
'Error' : 'Exception';
412 return '[' . $which . ' ' . get_class( $item ) . '( ' .
413 $item->getFile() . ':' . $item->getLine() . ') ' .
414 $item->getMessage() . ']';
417 if ( is_object( $item ) ) {
418 if ( method_exists( $item, '__toString' ) ) {
419 return (string)$item;
422 return '[Object ' . get_class( $item ) . ']';
425 if ( is_resource( $item ) ) {
426 return '[Resource ' . get_resource_type( $item ) . ']';
429 return '[Unknown ' . gettype( $item ) . ']';
433 * Select the appropriate log output destination for the given log event.
435 * If the event context contains 'destination'
437 * @param string $channel
438 * @param string $message
439 * @param array $context
442 protected static function destination( $channel, $message, $context ) {
443 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
445 // Default destination is the debug log file as historically used by
446 // the wfDebug function.
447 $destination = $wgDebugLogFile;
449 if ( isset( $context['destination'] ) ) {
450 // Use destination explicitly provided in context
451 $destination = $context['destination'];
453 } elseif ( $channel === 'wfDebug' ) {
454 $destination = $wgDebugLogFile;
456 } elseif ( $channel === 'wfLogDBError' ) {
457 $destination = $wgDBerrorLog;
459 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
460 $logConfig = $wgDebugLogGroups[$channel];
462 if ( is_array( $logConfig ) ) {
463 $destination = $logConfig['destination'];
465 $destination = strval( $logConfig );
473 * Log to a file without getting "file size exceeded" signals.
475 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
476 * lines to the specified port, prefixed by the specified prefix and a space.
478 * @param string $text
479 * @param string $file Filename
481 public static function emit( $text, $file ) {
482 if ( substr( $file, 0, 4 ) == 'udp:' ) {
483 $transport = UDPTransport
::newFromString( $file );
484 $transport->emit( $text );
486 \Wikimedia\
suppressWarnings();
487 $exists = file_exists( $file );
488 $size = $exists ?
filesize( $file ) : false;
490 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
492 file_put_contents( $file, $text, FILE_APPEND
);
494 \Wikimedia\restoreWarnings
();