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 ( is_string( $level ) ) {
98 $level = self
::$levelMapping[$level];
100 if ( $this->channel
=== 'DBQuery' && isset( $context['method'] )
101 && isset( $context['master'] ) && isset( $context['runtime'] )
103 MWDebug
::query( $message, $context['method'], $context['master'], $context['runtime'] );
104 return; // only send profiling data to MWDebug profiling
107 if ( isset( self
::$dbChannels[$this->channel
] )
108 && $level >= self
::$levelMapping[LogLevel
::ERROR
]
110 // Format and write DB errors to the legacy locations
111 $effectiveChannel = 'wfLogDBError';
113 $effectiveChannel = $this->channel
;
116 if ( self
::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
117 $text = self
::format( $effectiveChannel, $message, $context );
118 $destination = self
::destination( $effectiveChannel, $message, $context );
119 self
::emit( $text, $destination );
121 if ( !isset( $context['private'] ) ||
!$context['private'] ) {
122 // Add to debug toolbar if not marked as "private"
123 MWDebug
::debugMsg( $message, [ 'channel' => $this->channel
] +
$context );
128 * Determine if the given message should be emitted or not.
130 * @param string $channel
131 * @param string $message
132 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
133 * @param array $context
134 * @return bool True if message should be sent to disk/network, false
137 public static function shouldEmit( $channel, $message, $level, $context ) {
138 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
140 if ( is_string( $level ) ) {
141 $level = self
::$levelMapping[$level];
144 if ( $channel === 'wfLogDBError' ) {
145 // wfLogDBError messages are emitted if a database log location is
147 $shouldEmit = (bool)$wgDBerrorLog;
149 } elseif ( $channel === 'wfErrorLog' ) {
150 // All messages on the wfErrorLog channel should be emitted.
153 } elseif ( $channel === 'wfDebug' ) {
154 // wfDebug messages are emitted if a catch all logging file has
155 // been specified. Checked explicitly so that 'private' flagged
156 // messages are not discarded by unset $wgDebugLogGroups channel
158 $shouldEmit = $wgDebugLogFile != '';
160 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
161 $logConfig = $wgDebugLogGroups[$channel];
163 if ( is_array( $logConfig ) ) {
165 if ( isset( $logConfig['sample'] ) ) {
166 // Emit randomly with a 1 in 'sample' chance for each message.
167 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
170 if ( isset( $logConfig['level'] ) ) {
171 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
174 // Emit unless the config value is explictly false.
175 $shouldEmit = $logConfig !== false;
178 } elseif ( isset( $context['private'] ) && $context['private'] ) {
179 // Don't emit if the message didn't match previous checks based on
180 // the channel and the event is marked as private. This check
181 // discards messages sent via wfDebugLog() with dest == 'private'
182 // and no explicit wgDebugLogGroups configuration.
185 // Default return value is the same as the historic wfDebug
186 // method: emit if $wgDebugLogFile has been set.
187 $shouldEmit = $wgDebugLogFile != '';
196 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
197 * receive special fomatting to mimic the historic output of the functions
198 * of the same name. All other channel values are formatted based on the
199 * historic output of the `wfDebugLog()` global function.
201 * @param string $channel
202 * @param string $message
203 * @param array $context
206 public static function format( $channel, $message, $context ) {
207 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
209 if ( $channel === 'wfDebug' ) {
210 $text = self
::formatAsWfDebug( $channel, $message, $context );
212 } elseif ( $channel === 'wfLogDBError' ) {
213 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
215 } elseif ( $channel === 'wfErrorLog' ) {
216 $text = "{$message}\n";
218 } elseif ( $channel === 'profileoutput' ) {
219 // Legacy wfLogProfilingData formatitng
221 if ( isset( $context['forwarded_for'] ) ) {
222 $forward = " forwarded for {$context['forwarded_for']}";
224 if ( isset( $context['client_ip'] ) ) {
225 $forward .= " client IP {$context['client_ip']}";
227 if ( isset( $context['from'] ) ) {
228 $forward .= " from {$context['from']}";
231 $forward = "\t(proxied via {$context['proxy']}{$forward})";
233 if ( $context['anon'] ) {
236 if ( !isset( $context['url'] ) ) {
237 $context['url'] = 'n/a';
240 $log = sprintf( "%s\t%04.3f\t%s%s\n",
241 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
243 $text = self
::formatAsWfDebugLog(
244 $channel, $log . $context['output'], $context );
246 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
247 $text = self
::formatAsWfDebug(
248 $channel, "[{$channel}] {$message}", $context );
251 // Default formatting is wfDebugLog's historic style
252 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
255 // Append stacktrace of exception if available
256 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
257 $e = $context['exception'];
260 if ( $e instanceof Exception
) {
261 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
263 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
264 // Exception has already been unpacked as structured data
265 $backtrace = $e['trace'];
269 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
274 return self
::interpolate( $text, $context );
278 * Format a message as `wfDebug()` would have formatted it.
280 * @param string $channel
281 * @param string $message
282 * @param array $context
285 protected static function formatAsWfDebug( $channel, $message, $context ) {
286 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
287 if ( isset( $context['seconds_elapsed'] ) ) {
288 // Prepend elapsed request time and real memory usage with two
290 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
292 if ( isset( $context['prefix'] ) ) {
293 $text = "{$context['prefix']}{$text}";
299 * Format a message as `wfLogDBError()` would have formatted it.
301 * @param string $channel
302 * @param string $message
303 * @param array $context
306 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
307 global $wgDBerrorLogTZ;
308 static $cachedTimezone = null;
310 if ( !$cachedTimezone ) {
311 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
314 $d = date_create( 'now', $cachedTimezone );
315 $date = $d->format( 'D M j G:i:s T Y' );
317 $host = wfHostname();
320 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
325 * Format a message as `wfDebugLog() would have formatted it.
327 * @param string $channel
328 * @param string $message
329 * @param array $context
332 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
333 $time = wfTimestamp( TS_DB
);
335 $host = wfHostname();
336 $text = "{$time} {$host} {$wiki}: {$message}\n";
341 * Interpolate placeholders in logging message.
343 * @param string $message
344 * @param array $context
345 * @return string Interpolated message
347 public static function interpolate( $message, array $context ) {
348 if ( strpos( $message, '{' ) !== false ) {
350 foreach ( $context as $key => $val ) {
351 $replace['{' . $key . '}'] = self
::flatten( $val );
353 $message = strtr( $message, $replace );
359 * Convert a logging context element to a string suitable for
365 protected static function flatten( $item ) {
366 if ( null === $item ) {
370 if ( is_bool( $item ) ) {
371 return $item ?
'true' : 'false';
374 if ( is_float( $item ) ) {
375 if ( is_infinite( $item ) ) {
376 return ( $item > 0 ?
'' : '-' ) . 'INF';
378 if ( is_nan( $item ) ) {
384 if ( is_scalar( $item ) ) {
385 return (string)$item;
388 if ( is_array( $item ) ) {
389 return '[Array(' . count( $item ) . ')]';
392 if ( $item instanceof \DateTime
) {
393 return $item->format( 'c' );
396 if ( $item instanceof Exception
) {
397 return '[Exception ' . get_class( $item ) . '( ' .
398 $item->getFile() . ':' . $item->getLine() . ') ' .
399 $item->getMessage() . ']';
402 if ( is_object( $item ) ) {
403 if ( method_exists( $item, '__toString' ) ) {
404 return (string)$item;
407 return '[Object ' . get_class( $item ) . ']';
410 if ( is_resource( $item ) ) {
411 return '[Resource ' . get_resource_type( $item ) . ']';
414 return '[Unknown ' . gettype( $item ) . ']';
418 * Select the appropriate log output destination for the given log event.
420 * If the event context contains 'destination'
422 * @param string $channel
423 * @param string $message
424 * @param array $context
427 protected static function destination( $channel, $message, $context ) {
428 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
430 // Default destination is the debug log file as historically used by
431 // the wfDebug function.
432 $destination = $wgDebugLogFile;
434 if ( isset( $context['destination'] ) ) {
435 // Use destination explicitly provided in context
436 $destination = $context['destination'];
438 } elseif ( $channel === 'wfDebug' ) {
439 $destination = $wgDebugLogFile;
441 } elseif ( $channel === 'wfLogDBError' ) {
442 $destination = $wgDBerrorLog;
444 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
445 $logConfig = $wgDebugLogGroups[$channel];
447 if ( is_array( $logConfig ) ) {
448 $destination = $logConfig['destination'];
450 $destination = strval( $logConfig );
458 * Log to a file without getting "file size exceeded" signals.
460 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
461 * lines to the specified port, prefixed by the specified prefix and a space.
463 * @param string $text
464 * @param string $file Filename
466 public static function emit( $text, $file ) {
467 if ( substr( $file, 0, 4 ) == 'udp:' ) {
468 $transport = UDPTransport
::newFromString( $file );
469 $transport->emit( $text );
471 \MediaWiki\
suppressWarnings();
472 $exists = file_exists( $file );
473 $size = $exists ?
filesize( $file ) : false;
475 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
477 file_put_contents( $file, $text, FILE_APPEND
);
479 \MediaWiki\restoreWarnings
();