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 * @author Bryan Davis <bd808@wikimedia.org>
47 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
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 = [] ) {
97 if ( isset( self
::$dbChannels[$this->channel
] )
98 && isset( self
::$levelMapping[$level] )
99 && self
::$levelMapping[$level] >= LogLevel
::ERROR
101 // Format and write DB errors to the legacy locations
102 $effectiveChannel = 'wfLogDBError';
104 $effectiveChannel = $this->channel
;
107 if ( self
::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
108 $text = self
::format( $effectiveChannel, $message, $context );
109 $destination = self
::destination( $effectiveChannel, $message, $context );
110 self
::emit( $text, $destination );
112 if ( $this->channel
=== 'DBQuery' && isset( $context['method'] )
113 && isset( $context['master'] ) && isset( $context['runtime'] )
115 MWDebug
::query( $message, $context['method'], $context['master'], $context['runtime'] );
116 } elseif ( !isset( $context['private'] ) ||
!$context['private'] ) {
117 // Add to debug toolbar if not marked as "private"
118 MWDebug
::debugMsg( $message, [ 'channel' => $this->channel
] +
$context );
123 * Determine if the given message should be emitted or not.
125 * @param string $channel
126 * @param string $message
127 * @param string|int $level \Psr\Log\LogEvent constant or Monlog level int
128 * @param array $context
129 * @return bool True if message should be sent to disk/network, false
132 public static function shouldEmit( $channel, $message, $level, $context ) {
133 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
135 if ( $channel === 'wfLogDBError' ) {
136 // wfLogDBError messages are emitted if a database log location is
138 $shouldEmit = (bool)$wgDBerrorLog;
140 } elseif ( $channel === 'wfErrorLog' ) {
141 // All messages on the wfErrorLog channel should be emitted.
144 } elseif ( $channel === 'wfDebug' ) {
145 // wfDebug messages are emitted if a catch all logging file has
146 // been specified. Checked explicitly so that 'private' flagged
147 // messages are not discarded by unset $wgDebugLogGroups channel
149 $shouldEmit = $wgDebugLogFile != '';
151 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
152 $logConfig = $wgDebugLogGroups[$channel];
154 if ( is_array( $logConfig ) ) {
156 if ( isset( $logConfig['sample'] ) ) {
157 // Emit randomly with a 1 in 'sample' chance for each message.
158 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
161 if ( isset( $logConfig['level'] ) ) {
162 if ( is_string( $level ) ) {
163 $level = self
::$levelMapping[$level];
165 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
168 // Emit unless the config value is explictly false.
169 $shouldEmit = $logConfig !== false;
172 } elseif ( isset( $context['private'] ) && $context['private'] ) {
173 // Don't emit if the message didn't match previous checks based on
174 // the channel and the event is marked as private. This check
175 // discards messages sent via wfDebugLog() with dest == 'private'
176 // and no explicit wgDebugLogGroups configuration.
179 // Default return value is the same as the historic wfDebug
180 // method: emit if $wgDebugLogFile has been set.
181 $shouldEmit = $wgDebugLogFile != '';
190 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
191 * receive special fomatting to mimic the historic output of the functions
192 * of the same name. All other channel values are formatted based on the
193 * historic output of the `wfDebugLog()` global function.
195 * @param string $channel
196 * @param string $message
197 * @param array $context
200 public static function format( $channel, $message, $context ) {
201 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
203 if ( $channel === 'wfDebug' ) {
204 $text = self
::formatAsWfDebug( $channel, $message, $context );
206 } elseif ( $channel === 'wfLogDBError' ) {
207 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
209 } elseif ( $channel === 'wfErrorLog' ) {
210 $text = "{$message}\n";
212 } elseif ( $channel === 'profileoutput' ) {
213 // Legacy wfLogProfilingData formatitng
215 if ( isset( $context['forwarded_for'] ) ) {
216 $forward = " forwarded for {$context['forwarded_for']}";
218 if ( isset( $context['client_ip'] ) ) {
219 $forward .= " client IP {$context['client_ip']}";
221 if ( isset( $context['from'] ) ) {
222 $forward .= " from {$context['from']}";
225 $forward = "\t(proxied via {$context['proxy']}{$forward})";
227 if ( $context['anon'] ) {
230 if ( !isset( $context['url'] ) ) {
231 $context['url'] = 'n/a';
234 $log = sprintf( "%s\t%04.3f\t%s%s\n",
235 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
237 $text = self
::formatAsWfDebugLog(
238 $channel, $log . $context['output'], $context );
240 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
241 $text = self
::formatAsWfDebug(
242 $channel, "[{$channel}] {$message}", $context );
245 // Default formatting is wfDebugLog's historic style
246 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
249 // Append stacktrace of exception if available
250 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
251 $e = $context['exception'];
254 if ( $e instanceof Exception
) {
255 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
257 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
258 // Exception has already been unpacked as structured data
259 $backtrace = $e['trace'];
263 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
268 return self
::interpolate( $text, $context );
272 * Format a message as `wfDebug()` would have formatted it.
274 * @param string $channel
275 * @param string $message
276 * @param array $context
279 protected static function formatAsWfDebug( $channel, $message, $context ) {
280 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
281 if ( isset( $context['seconds_elapsed'] ) ) {
282 // Prepend elapsed request time and real memory usage with two
284 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
286 if ( isset( $context['prefix'] ) ) {
287 $text = "{$context['prefix']}{$text}";
293 * Format a message as `wfLogDBError()` would have formatted it.
295 * @param string $channel
296 * @param string $message
297 * @param array $context
300 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
301 global $wgDBerrorLogTZ;
302 static $cachedTimezone = null;
304 if ( !$cachedTimezone ) {
305 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
308 $d = date_create( 'now', $cachedTimezone );
309 $date = $d->format( 'D M j G:i:s T Y' );
311 $host = wfHostname();
314 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
319 * Format a message as `wfDebugLog() would have formatted it.
321 * @param string $channel
322 * @param string $message
323 * @param array $context
326 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
327 $time = wfTimestamp( TS_DB
);
329 $host = wfHostname();
330 $text = "{$time} {$host} {$wiki}: {$message}\n";
335 * Interpolate placeholders in logging message.
337 * @param string $message
338 * @param array $context
339 * @return string Interpolated message
341 public static function interpolate( $message, array $context ) {
342 if ( strpos( $message, '{' ) !== false ) {
344 foreach ( $context as $key => $val ) {
345 $replace['{' . $key . '}'] = self
::flatten( $val );
347 $message = strtr( $message, $replace );
353 * Convert a logging context element to a string suitable for
359 protected static function flatten( $item ) {
360 if ( null === $item ) {
364 if ( is_bool( $item ) ) {
365 return $item ?
'true' : 'false';
368 if ( is_float( $item ) ) {
369 if ( is_infinite( $item ) ) {
370 return ( $item > 0 ?
'' : '-' ) . 'INF';
372 if ( is_nan( $item ) ) {
378 if ( is_scalar( $item ) ) {
379 return (string)$item;
382 if ( is_array( $item ) ) {
383 return '[Array(' . count( $item ) . ')]';
386 if ( $item instanceof \DateTime
) {
387 return $item->format( 'c' );
390 if ( $item instanceof Exception
) {
391 return '[Exception ' . get_class( $item ) . '( ' .
392 $item->getFile() . ':' . $item->getLine() . ') ' .
393 $item->getMessage() . ']';
396 if ( is_object( $item ) ) {
397 if ( method_exists( $item, '__toString' ) ) {
398 return (string)$item;
401 return '[Object ' . get_class( $item ) . ']';
404 if ( is_resource( $item ) ) {
405 return '[Resource ' . get_resource_type( $item ) . ']';
408 return '[Unknown ' . gettype( $item ) . ']';
412 * Select the appropriate log output destination for the given log event.
414 * If the event context contains 'destination'
416 * @param string $channel
417 * @param string $message
418 * @param array $context
421 protected static function destination( $channel, $message, $context ) {
422 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
424 // Default destination is the debug log file as historically used by
425 // the wfDebug function.
426 $destination = $wgDebugLogFile;
428 if ( isset( $context['destination'] ) ) {
429 // Use destination explicitly provided in context
430 $destination = $context['destination'];
432 } elseif ( $channel === 'wfDebug' ) {
433 $destination = $wgDebugLogFile;
435 } elseif ( $channel === 'wfLogDBError' ) {
436 $destination = $wgDBerrorLog;
438 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
439 $logConfig = $wgDebugLogGroups[$channel];
441 if ( is_array( $logConfig ) ) {
442 $destination = $logConfig['destination'];
444 $destination = strval( $logConfig );
452 * Log to a file without getting "file size exceeded" signals.
454 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
455 * lines to the specified port, prefixed by the specified prefix and a space.
457 * @param string $text
458 * @param string $file Filename
460 public static function emit( $text, $file ) {
461 if ( substr( $file, 0, 4 ) == 'udp:' ) {
462 $transport = UDPTransport
::newFromString( $file );
463 $transport->emit( $text );
465 \MediaWiki\
suppressWarnings();
466 $exists = file_exists( $file );
467 $size = $exists ?
filesize( $file ) : false;
469 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
471 file_put_contents( $file, $text, FILE_APPEND
);
473 \MediaWiki\restoreWarnings
();