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 && $level === self
::$levelMapping[LogLevel
::DEBUG
]
106 && isset( $context['sql'] )
108 // Also give the query information to the MWDebug tools
109 $enabled = MWDebug
::query(
116 // If we the toolbar was enabled, return early so that we don't
117 // also log the query to the main debug output.
122 // If this is a DB-related error, and the site has $wgDBerrorLog
123 // configured, rewrite the channel as wfLogDBError instead.
124 // Likewise, if the site does not use $wgDBerrorLog, it should
125 // configurable like any other channel via $wgDebugLogGroups
126 // or $wgMWLoggerDefaultSpi.
127 if ( isset( self
::$dbChannels[$this->channel
] )
128 && $level >= self
::$levelMapping[LogLevel
::ERROR
]
131 // Format and write DB errors to the legacy locations
132 $effectiveChannel = 'wfLogDBError';
134 $effectiveChannel = $this->channel
;
137 if ( self
::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
138 $text = self
::format( $effectiveChannel, $message, $context );
139 $destination = self
::destination( $effectiveChannel, $message, $context );
140 self
::emit( $text, $destination );
142 if ( !isset( $context['private'] ) ||
!$context['private'] ) {
143 // Add to debug toolbar if not marked as "private"
144 MWDebug
::debugMsg( $message, [ 'channel' => $this->channel
] +
$context );
149 * Determine if the given message should be emitted or not.
151 * @param string $channel
152 * @param string $message
153 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
154 * @param array $context
155 * @return bool True if message should be sent to disk/network, false
158 public static function shouldEmit( $channel, $message, $level, $context ) {
159 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
161 if ( is_string( $level ) ) {
162 $level = self
::$levelMapping[$level];
165 if ( $channel === 'wfLogDBError' ) {
166 // wfLogDBError messages are emitted if a database log location is
168 $shouldEmit = (bool)$wgDBerrorLog;
170 } elseif ( $channel === 'wfDebug' ) {
171 // wfDebug messages are emitted if a catch all logging file has
172 // been specified. Checked explicitly so that 'private' flagged
173 // messages are not discarded by unset $wgDebugLogGroups channel
175 $shouldEmit = $wgDebugLogFile != '';
177 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
178 $logConfig = $wgDebugLogGroups[$channel];
180 if ( is_array( $logConfig ) ) {
182 if ( isset( $logConfig['sample'] ) ) {
183 // Emit randomly with a 1 in 'sample' chance for each message.
184 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
187 if ( isset( $logConfig['level'] ) ) {
188 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
191 // Emit unless the config value is explictly false.
192 $shouldEmit = $logConfig !== false;
195 } elseif ( isset( $context['private'] ) && $context['private'] ) {
196 // Don't emit if the message didn't match previous checks based on
197 // the channel and the event is marked as private. This check
198 // discards messages sent via wfDebugLog() with dest == 'private'
199 // and no explicit wgDebugLogGroups configuration.
202 // Default return value is the same as the historic wfDebug
203 // method: emit if $wgDebugLogFile has been set.
204 $shouldEmit = $wgDebugLogFile != '';
213 * Messages to the 'wfDebug' and 'wfLogDBError' channels receive special formatting to mimic the
214 * historic output of the functions of the same name. All other channel values are formatted
215 * based on the historic output of the `wfDebugLog()` global function.
217 * @param string $channel
218 * @param string $message
219 * @param array $context
222 public static function format( $channel, $message, $context ) {
223 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
225 if ( $channel === 'wfDebug' ) {
226 $text = self
::formatAsWfDebug( $channel, $message, $context );
228 } elseif ( $channel === 'wfLogDBError' ) {
229 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
231 } elseif ( $channel === 'profileoutput' ) {
232 // Legacy wfLogProfilingData formatitng
234 if ( isset( $context['forwarded_for'] ) ) {
235 $forward = " forwarded for {$context['forwarded_for']}";
237 if ( isset( $context['client_ip'] ) ) {
238 $forward .= " client IP {$context['client_ip']}";
240 if ( isset( $context['from'] ) ) {
241 $forward .= " from {$context['from']}";
244 $forward = "\t(proxied via {$context['proxy']}{$forward})";
246 if ( $context['anon'] ) {
249 if ( !isset( $context['url'] ) ) {
250 $context['url'] = 'n/a';
253 $log = sprintf( "%s\t%04.3f\t%s%s\n",
254 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
256 $text = self
::formatAsWfDebugLog(
257 $channel, $log . $context['output'], $context );
259 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
260 $text = self
::formatAsWfDebug(
261 $channel, "[{$channel}] {$message}", $context );
264 // Default formatting is wfDebugLog's historic style
265 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
268 // Append stacktrace of exception if available
269 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
270 $e = $context['exception'];
273 if ( $e instanceof Throwable ||
$e instanceof Exception
) {
274 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
276 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
277 // Exception has already been unpacked as structured data
278 $backtrace = $e['trace'];
282 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
287 return self
::interpolate( $text, $context );
291 * Format a message as `wfDebug()` would have formatted it.
293 * @param string $channel
294 * @param string $message
295 * @param array $context
298 protected static function formatAsWfDebug( $channel, $message, $context ) {
299 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
300 if ( isset( $context['seconds_elapsed'] ) ) {
301 // Prepend elapsed request time and real memory usage with two
303 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
305 if ( isset( $context['prefix'] ) ) {
306 $text = "{$context['prefix']}{$text}";
312 * Format a message as `wfLogDBError()` would have formatted it.
314 * @param string $channel
315 * @param string $message
316 * @param array $context
319 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
320 global $wgDBerrorLogTZ;
321 static $cachedTimezone = null;
323 if ( !$cachedTimezone ) {
324 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
327 $d = date_create( 'now', $cachedTimezone );
328 $date = $d->format( 'D M j G:i:s T Y' );
330 $host = wfHostname();
331 $wiki = WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() );
333 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
338 * Format a message as `wfDebugLog() would have formatted it.
340 * @param string $channel
341 * @param string $message
342 * @param array $context
345 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
346 $time = wfTimestamp( TS_DB
);
347 $wiki = WikiMap
::getWikiIdFromDbDomain( WikiMap
::getCurrentWikiDbDomain() );
348 $host = wfHostname();
349 $text = "{$time} {$host} {$wiki}: {$message}\n";
354 * Interpolate placeholders in logging message.
356 * @param string $message
357 * @param array $context
358 * @return string Interpolated message
360 public static function interpolate( $message, array $context ) {
361 if ( strpos( $message, '{' ) !== false ) {
363 foreach ( $context as $key => $val ) {
364 $replace['{' . $key . '}'] = self
::flatten( $val );
366 $message = strtr( $message, $replace );
372 * Convert a logging context element to a string suitable for
378 protected static function flatten( $item ) {
379 if ( $item === null ) {
383 if ( is_bool( $item ) ) {
384 return $item ?
'true' : 'false';
387 if ( is_float( $item ) ) {
388 if ( is_infinite( $item ) ) {
389 return ( $item > 0 ?
'' : '-' ) . 'INF';
391 if ( is_nan( $item ) ) {
394 return (string)$item;
397 if ( is_scalar( $item ) ) {
398 return (string)$item;
401 if ( is_array( $item ) ) {
402 return '[Array(' . count( $item ) . ')]';
405 if ( $item instanceof \DateTime
) {
406 return $item->format( 'c' );
409 if ( $item instanceof Throwable ||
$item instanceof Exception
) {
410 $which = $item instanceof Error ?
'Error' : 'Exception';
411 return '[' . $which . ' ' . get_class( $item ) . '( ' .
412 $item->getFile() . ':' . $item->getLine() . ') ' .
413 $item->getMessage() . ']';
416 if ( is_object( $item ) ) {
417 if ( method_exists( $item, '__toString' ) ) {
418 return (string)$item;
421 return '[Object ' . get_class( $item ) . ']';
424 if ( is_resource( $item ) ) {
425 return '[Resource ' . get_resource_type( $item ) . ']';
428 return '[Unknown ' . gettype( $item ) . ']';
432 * Select the appropriate log output destination for the given log event.
434 * If the event context contains 'destination'
436 * @param string $channel
437 * @param string $message
438 * @param array $context
441 protected static function destination( $channel, $message, $context ) {
442 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
444 // Default destination is the debug log file as historically used by
445 // the wfDebug function.
446 $destination = $wgDebugLogFile;
448 if ( isset( $context['destination'] ) ) {
449 // Use destination explicitly provided in context
450 $destination = $context['destination'];
452 } elseif ( $channel === 'wfDebug' ) {
453 $destination = $wgDebugLogFile;
455 } elseif ( $channel === 'wfLogDBError' ) {
456 $destination = $wgDBerrorLog;
458 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
459 $logConfig = $wgDebugLogGroups[$channel];
461 if ( is_array( $logConfig ) ) {
462 $destination = $logConfig['destination'];
464 $destination = strval( $logConfig );
472 * Log to a file without getting "file size exceeded" signals.
474 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
475 * lines to the specified port, prefixed by the specified prefix and a space.
477 * @param string $text
478 * @param string $file Filename
480 public static function emit( $text, $file ) {
481 if ( substr( $file, 0, 4 ) == 'udp:' ) {
482 $transport = UDPTransport
::newFromString( $file );
483 $transport->emit( $text );
485 \Wikimedia\
suppressWarnings();
486 $exists = file_exists( $file );
487 $size = $exists ?
filesize( $file ) : false;
489 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
491 file_put_contents( $file, $text, FILE_APPEND
);
493 \Wikimedia\restoreWarnings
();