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
;
27 use MWExceptionHandler
;
28 use Psr\Log\AbstractLogger
;
33 * PSR-3 logger that mimics the historic implementation of MediaWiki's former
34 * wfErrorLog logging implementation.
36 * This logger is configured by the following global configuration variables:
38 * - `$wgDebugLogGroups`
42 * See documentation in DefaultSettings.php for detailed explanations of each
45 * @see \MediaWiki\Logger\LoggerFactory
47 * @copyright © 2014 Wikimedia Foundation and contributors
49 class LegacyLogger
extends AbstractLogger
{
52 * @var string $channel
57 * Convert \Psr\Log\LogLevel constants into int for sane comparisons
58 * These are the same values that Monlog uses
60 * @var array $levelMapping
62 protected static $levelMapping = [
63 LogLevel
::DEBUG
=> 100,
64 LogLevel
::INFO
=> 200,
65 LogLevel
::NOTICE
=> 250,
66 LogLevel
::WARNING
=> 300,
67 LogLevel
::ERROR
=> 400,
68 LogLevel
::CRITICAL
=> 500,
69 LogLevel
::ALERT
=> 550,
70 LogLevel
::EMERGENCY
=> 600,
76 protected static $dbChannels = [
78 'DBConnection' => true
82 * @param string $channel
84 public function __construct( $channel ) {
85 $this->channel
= $channel;
89 * Logs with an arbitrary level.
91 * @param string|int $level
92 * @param string $message
93 * @param array $context
96 public function log( $level, $message, array $context = [] ) {
99 if ( is_string( $level ) ) {
100 $level = self
::$levelMapping[$level];
102 if ( $this->channel
=== 'DBQuery'
103 && isset( $context['method'] )
104 && isset( $context['master'] )
105 && isset( $context['runtime'] )
107 // Also give the query information to the MWDebug tools
108 $enabled = MWDebug
::query(
115 // If we the toolbar was enabled, return early so that we don't
116 // also log the query to the main debug output.
121 // If this is a DB-related error, and the site has $wgDBerrorLog
122 // configured, rewrite the channel as wfLogDBError instead.
123 // Likewise, if the site does not use $wgDBerrorLog, it should
124 // configurable like any other channel via $wgDebugLogGroups
125 // or $wgMWLoggerDefaultSpi.
126 if ( isset( self
::$dbChannels[$this->channel
] )
127 && $level >= self
::$levelMapping[LogLevel
::ERROR
]
130 // Format and write DB errors to the legacy locations
131 $effectiveChannel = 'wfLogDBError';
133 $effectiveChannel = $this->channel
;
136 if ( self
::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
137 $text = self
::format( $effectiveChannel, $message, $context );
138 $destination = self
::destination( $effectiveChannel, $message, $context );
139 self
::emit( $text, $destination );
141 if ( !isset( $context['private'] ) ||
!$context['private'] ) {
142 // Add to debug toolbar if not marked as "private"
143 MWDebug
::debugMsg( $message, [ 'channel' => $this->channel
] +
$context );
148 * Determine if the given message should be emitted or not.
150 * @param string $channel
151 * @param string $message
152 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
153 * @param array $context
154 * @return bool True if message should be sent to disk/network, false
157 public static function shouldEmit( $channel, $message, $level, $context ) {
158 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
160 if ( is_string( $level ) ) {
161 $level = self
::$levelMapping[$level];
164 if ( $channel === 'wfLogDBError' ) {
165 // wfLogDBError messages are emitted if a database log location is
167 $shouldEmit = (bool)$wgDBerrorLog;
169 } elseif ( $channel === 'wfDebug' ) {
170 // wfDebug messages are emitted if a catch all logging file has
171 // been specified. Checked explicitly so that 'private' flagged
172 // messages are not discarded by unset $wgDebugLogGroups channel
174 $shouldEmit = $wgDebugLogFile != '';
176 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
177 $logConfig = $wgDebugLogGroups[$channel];
179 if ( is_array( $logConfig ) ) {
181 if ( isset( $logConfig['sample'] ) ) {
182 // Emit randomly with a 1 in 'sample' chance for each message.
183 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
186 if ( isset( $logConfig['level'] ) ) {
187 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
190 // Emit unless the config value is explictly false.
191 $shouldEmit = $logConfig !== false;
194 } elseif ( isset( $context['private'] ) && $context['private'] ) {
195 // Don't emit if the message didn't match previous checks based on
196 // the channel and the event is marked as private. This check
197 // discards messages sent via wfDebugLog() with dest == 'private'
198 // and no explicit wgDebugLogGroups configuration.
201 // Default return value is the same as the historic wfDebug
202 // method: emit if $wgDebugLogFile has been set.
203 $shouldEmit = $wgDebugLogFile != '';
212 * Messages to the 'wfDebug' and 'wfLogDBError' channels receive special formatting to mimic the
213 * historic output of the functions of the same name. All other channel values are formatted
214 * based on the historic output of the `wfDebugLog()` global function.
216 * @param string $channel
217 * @param string $message
218 * @param array $context
221 public static function format( $channel, $message, $context ) {
222 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
224 if ( $channel === 'wfDebug' ) {
225 $text = self
::formatAsWfDebug( $channel, $message, $context );
227 } elseif ( $channel === 'wfLogDBError' ) {
228 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
230 } elseif ( $channel === 'profileoutput' ) {
231 // Legacy wfLogProfilingData formatitng
233 if ( isset( $context['forwarded_for'] ) ) {
234 $forward = " forwarded for {$context['forwarded_for']}";
236 if ( isset( $context['client_ip'] ) ) {
237 $forward .= " client IP {$context['client_ip']}";
239 if ( isset( $context['from'] ) ) {
240 $forward .= " from {$context['from']}";
243 $forward = "\t(proxied via {$context['proxy']}{$forward})";
245 if ( $context['anon'] ) {
248 if ( !isset( $context['url'] ) ) {
249 $context['url'] = 'n/a';
252 $log = sprintf( "%s\t%04.3f\t%s%s\n",
253 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
255 $text = self
::formatAsWfDebugLog(
256 $channel, $log . $context['output'], $context );
258 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
259 $text = self
::formatAsWfDebug(
260 $channel, "[{$channel}] {$message}", $context );
263 // Default formatting is wfDebugLog's historic style
264 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
267 // Append stacktrace of exception if available
268 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
269 $e = $context['exception'];
272 if ( $e instanceof Exception
) {
273 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
275 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
276 // Exception has already been unpacked as structured data
277 $backtrace = $e['trace'];
281 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
286 return self
::interpolate( $text, $context );
290 * Format a message as `wfDebug()` would have formatted it.
292 * @param string $channel
293 * @param string $message
294 * @param array $context
297 protected static function formatAsWfDebug( $channel, $message, $context ) {
298 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
299 if ( isset( $context['seconds_elapsed'] ) ) {
300 // Prepend elapsed request time and real memory usage with two
302 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
304 if ( isset( $context['prefix'] ) ) {
305 $text = "{$context['prefix']}{$text}";
311 * Format a message as `wfLogDBError()` would have formatted it.
313 * @param string $channel
314 * @param string $message
315 * @param array $context
318 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
319 global $wgDBerrorLogTZ;
320 static $cachedTimezone = null;
322 if ( !$cachedTimezone ) {
323 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
326 $d = date_create( 'now', $cachedTimezone );
327 $date = $d->format( 'D M j G:i:s T Y' );
329 $host = wfHostname();
330 $wiki = WikiMap
::getWikiIdFromDomain( WikiMap
::getCurrentWikiDomain() );
332 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
337 * Format a message as `wfDebugLog() would have formatted it.
339 * @param string $channel
340 * @param string $message
341 * @param array $context
344 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
345 $time = wfTimestamp( TS_DB
);
346 $wiki = WikiMap
::getWikiIdFromDomain( WikiMap
::getCurrentWikiDomain() );
347 $host = wfHostname();
348 $text = "{$time} {$host} {$wiki}: {$message}\n";
353 * Interpolate placeholders in logging message.
355 * @param string $message
356 * @param array $context
357 * @return string Interpolated message
359 public static function interpolate( $message, array $context ) {
360 if ( strpos( $message, '{' ) !== false ) {
362 foreach ( $context as $key => $val ) {
363 $replace['{' . $key . '}'] = self
::flatten( $val );
365 $message = strtr( $message, $replace );
371 * Convert a logging context element to a string suitable for
377 protected static function flatten( $item ) {
378 if ( $item === null ) {
382 if ( is_bool( $item ) ) {
383 return $item ?
'true' : 'false';
386 if ( is_float( $item ) ) {
387 if ( is_infinite( $item ) ) {
388 return ( $item > 0 ?
'' : '-' ) . 'INF';
390 if ( is_nan( $item ) ) {
393 return (string)$item;
396 if ( is_scalar( $item ) ) {
397 return (string)$item;
400 if ( is_array( $item ) ) {
401 return '[Array(' . count( $item ) . ')]';
404 if ( $item instanceof \DateTime
) {
405 return $item->format( 'c' );
408 if ( $item instanceof Exception
) {
409 return '[Exception ' . get_class( $item ) . '( ' .
410 $item->getFile() . ':' . $item->getLine() . ') ' .
411 $item->getMessage() . ']';
414 if ( is_object( $item ) ) {
415 if ( method_exists( $item, '__toString' ) ) {
416 return (string)$item;
419 return '[Object ' . get_class( $item ) . ']';
422 if ( is_resource( $item ) ) {
423 return '[Resource ' . get_resource_type( $item ) . ']';
426 return '[Unknown ' . gettype( $item ) . ']';
430 * Select the appropriate log output destination for the given log event.
432 * If the event context contains 'destination'
434 * @param string $channel
435 * @param string $message
436 * @param array $context
439 protected static function destination( $channel, $message, $context ) {
440 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
442 // Default destination is the debug log file as historically used by
443 // the wfDebug function.
444 $destination = $wgDebugLogFile;
446 if ( isset( $context['destination'] ) ) {
447 // Use destination explicitly provided in context
448 $destination = $context['destination'];
450 } elseif ( $channel === 'wfDebug' ) {
451 $destination = $wgDebugLogFile;
453 } elseif ( $channel === 'wfLogDBError' ) {
454 $destination = $wgDBerrorLog;
456 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
457 $logConfig = $wgDebugLogGroups[$channel];
459 if ( is_array( $logConfig ) ) {
460 $destination = $logConfig['destination'];
462 $destination = strval( $logConfig );
470 * Log to a file without getting "file size exceeded" signals.
472 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
473 * lines to the specified port, prefixed by the specified prefix and a space.
475 * @param string $text
476 * @param string $file Filename
478 public static function emit( $text, $file ) {
479 if ( substr( $file, 0, 4 ) == 'udp:' ) {
480 $transport = UDPTransport
::newFromString( $file );
481 $transport->emit( $text );
483 \Wikimedia\
suppressWarnings();
484 $exists = file_exists( $file );
485 $size = $exists ?
filesize( $file ) : false;
487 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
489 file_put_contents( $file, $text, FILE_APPEND
);
491 \Wikimedia\restoreWarnings
();