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 = [] ) {
96 if ( is_string( $level ) ) {
97 $level = self
::$levelMapping[$level];
99 if ( $this->channel
=== 'DBQuery' && isset( $context['method'] )
100 && isset( $context['master'] ) && isset( $context['runtime'] )
102 MWDebug
::query( $message, $context['method'], $context['master'], $context['runtime'] );
103 return; // only send profiling data to MWDebug profiling
106 if ( isset( self
::$dbChannels[$this->channel
] )
107 && $level >= self
::$levelMapping[LogLevel
::ERROR
]
109 // Format and write DB errors to the legacy locations
110 $effectiveChannel = 'wfLogDBError';
112 $effectiveChannel = $this->channel
;
115 if ( self
::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
116 $text = self
::format( $effectiveChannel, $message, $context );
117 $destination = self
::destination( $effectiveChannel, $message, $context );
118 self
::emit( $text, $destination );
120 if ( !isset( $context['private'] ) ||
!$context['private'] ) {
121 // Add to debug toolbar if not marked as "private"
122 MWDebug
::debugMsg( $message, [ 'channel' => $this->channel
] +
$context );
127 * Determine if the given message should be emitted or not.
129 * @param string $channel
130 * @param string $message
131 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
132 * @param array $context
133 * @return bool True if message should be sent to disk/network, false
136 public static function shouldEmit( $channel, $message, $level, $context ) {
137 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
139 if ( is_string( $level ) ) {
140 $level = self
::$levelMapping[$level];
143 if ( $channel === 'wfLogDBError' ) {
144 // wfLogDBError messages are emitted if a database log location is
146 $shouldEmit = (bool)$wgDBerrorLog;
148 } elseif ( $channel === 'wfErrorLog' ) {
149 // All messages on the wfErrorLog channel should be emitted.
152 } elseif ( $channel === 'wfDebug' ) {
153 // wfDebug messages are emitted if a catch all logging file has
154 // been specified. Checked explicitly so that 'private' flagged
155 // messages are not discarded by unset $wgDebugLogGroups channel
157 $shouldEmit = $wgDebugLogFile != '';
159 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
160 $logConfig = $wgDebugLogGroups[$channel];
162 if ( is_array( $logConfig ) ) {
164 if ( isset( $logConfig['sample'] ) ) {
165 // Emit randomly with a 1 in 'sample' chance for each message.
166 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
169 if ( isset( $logConfig['level'] ) ) {
170 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
173 // Emit unless the config value is explictly false.
174 $shouldEmit = $logConfig !== false;
177 } elseif ( isset( $context['private'] ) && $context['private'] ) {
178 // Don't emit if the message didn't match previous checks based on
179 // the channel and the event is marked as private. This check
180 // discards messages sent via wfDebugLog() with dest == 'private'
181 // and no explicit wgDebugLogGroups configuration.
184 // Default return value is the same as the historic wfDebug
185 // method: emit if $wgDebugLogFile has been set.
186 $shouldEmit = $wgDebugLogFile != '';
195 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
196 * receive special formatting to mimic the historic output of the functions
197 * of the same name. All other channel values are formatted based on the
198 * historic output of the `wfDebugLog()` global function.
200 * @param string $channel
201 * @param string $message
202 * @param array $context
205 public static function format( $channel, $message, $context ) {
206 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
208 if ( $channel === 'wfDebug' ) {
209 $text = self
::formatAsWfDebug( $channel, $message, $context );
211 } elseif ( $channel === 'wfLogDBError' ) {
212 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
214 } elseif ( $channel === 'wfErrorLog' ) {
215 $text = "{$message}\n";
217 } elseif ( $channel === 'profileoutput' ) {
218 // Legacy wfLogProfilingData formatitng
220 if ( isset( $context['forwarded_for'] ) ) {
221 $forward = " forwarded for {$context['forwarded_for']}";
223 if ( isset( $context['client_ip'] ) ) {
224 $forward .= " client IP {$context['client_ip']}";
226 if ( isset( $context['from'] ) ) {
227 $forward .= " from {$context['from']}";
230 $forward = "\t(proxied via {$context['proxy']}{$forward})";
232 if ( $context['anon'] ) {
235 if ( !isset( $context['url'] ) ) {
236 $context['url'] = 'n/a';
239 $log = sprintf( "%s\t%04.3f\t%s%s\n",
240 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
242 $text = self
::formatAsWfDebugLog(
243 $channel, $log . $context['output'], $context );
245 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
246 $text = self
::formatAsWfDebug(
247 $channel, "[{$channel}] {$message}", $context );
250 // Default formatting is wfDebugLog's historic style
251 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
254 // Append stacktrace of exception if available
255 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
256 $e = $context['exception'];
259 if ( $e instanceof Exception
) {
260 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
262 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
263 // Exception has already been unpacked as structured data
264 $backtrace = $e['trace'];
268 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
273 return self
::interpolate( $text, $context );
277 * Format a message as `wfDebug()` would have formatted it.
279 * @param string $channel
280 * @param string $message
281 * @param array $context
284 protected static function formatAsWfDebug( $channel, $message, $context ) {
285 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
286 if ( isset( $context['seconds_elapsed'] ) ) {
287 // Prepend elapsed request time and real memory usage with two
289 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
291 if ( isset( $context['prefix'] ) ) {
292 $text = "{$context['prefix']}{$text}";
298 * Format a message as `wfLogDBError()` would have formatted it.
300 * @param string $channel
301 * @param string $message
302 * @param array $context
305 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
306 global $wgDBerrorLogTZ;
307 static $cachedTimezone = null;
309 if ( !$cachedTimezone ) {
310 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
313 $d = date_create( 'now', $cachedTimezone );
314 $date = $d->format( 'D M j G:i:s T Y' );
316 $host = wfHostname();
319 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
324 * Format a message as `wfDebugLog() would have formatted it.
326 * @param string $channel
327 * @param string $message
328 * @param array $context
331 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
332 $time = wfTimestamp( TS_DB
);
334 $host = wfHostname();
335 $text = "{$time} {$host} {$wiki}: {$message}\n";
340 * Interpolate placeholders in logging message.
342 * @param string $message
343 * @param array $context
344 * @return string Interpolated message
346 public static function interpolate( $message, array $context ) {
347 if ( strpos( $message, '{' ) !== false ) {
349 foreach ( $context as $key => $val ) {
350 $replace['{' . $key . '}'] = self
::flatten( $val );
352 $message = strtr( $message, $replace );
358 * Convert a logging context element to a string suitable for
364 protected static function flatten( $item ) {
365 if ( null === $item ) {
369 if ( is_bool( $item ) ) {
370 return $item ?
'true' : 'false';
373 if ( is_float( $item ) ) {
374 if ( is_infinite( $item ) ) {
375 return ( $item > 0 ?
'' : '-' ) . 'INF';
377 if ( is_nan( $item ) ) {
380 return (string)$item;
383 if ( is_scalar( $item ) ) {
384 return (string)$item;
387 if ( is_array( $item ) ) {
388 return '[Array(' . count( $item ) . ')]';
391 if ( $item instanceof \DateTime
) {
392 return $item->format( 'c' );
395 if ( $item instanceof Exception
) {
396 return '[Exception ' . get_class( $item ) . '( ' .
397 $item->getFile() . ':' . $item->getLine() . ') ' .
398 $item->getMessage() . ']';
401 if ( is_object( $item ) ) {
402 if ( method_exists( $item, '__toString' ) ) {
403 return (string)$item;
406 return '[Object ' . get_class( $item ) . ']';
409 if ( is_resource( $item ) ) {
410 return '[Resource ' . get_resource_type( $item ) . ']';
413 return '[Unknown ' . gettype( $item ) . ']';
417 * Select the appropriate log output destination for the given log event.
419 * If the event context contains 'destination'
421 * @param string $channel
422 * @param string $message
423 * @param array $context
426 protected static function destination( $channel, $message, $context ) {
427 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
429 // Default destination is the debug log file as historically used by
430 // the wfDebug function.
431 $destination = $wgDebugLogFile;
433 if ( isset( $context['destination'] ) ) {
434 // Use destination explicitly provided in context
435 $destination = $context['destination'];
437 } elseif ( $channel === 'wfDebug' ) {
438 $destination = $wgDebugLogFile;
440 } elseif ( $channel === 'wfLogDBError' ) {
441 $destination = $wgDBerrorLog;
443 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
444 $logConfig = $wgDebugLogGroups[$channel];
446 if ( is_array( $logConfig ) ) {
447 $destination = $logConfig['destination'];
449 $destination = strval( $logConfig );
457 * Log to a file without getting "file size exceeded" signals.
459 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
460 * lines to the specified port, prefixed by the specified prefix and a space.
462 * @param string $text
463 * @param string $file Filename
465 public static function emit( $text, $file ) {
466 if ( substr( $file, 0, 4 ) == 'udp:' ) {
467 $transport = UDPTransport
::newFromString( $file );
468 $transport->emit( $text );
470 \Wikimedia\
suppressWarnings();
471 $exists = file_exists( $file );
472 $size = $exists ?
filesize( $file ) : false;
474 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
476 file_put_contents( $file, $text, FILE_APPEND
);
478 \Wikimedia\restoreWarnings
();