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 former
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 === 'wfDebug' ) {
149 // wfDebug messages are emitted if a catch all logging file has
150 // been specified. Checked explicitly so that 'private' flagged
151 // messages are not discarded by unset $wgDebugLogGroups channel
153 $shouldEmit = $wgDebugLogFile != '';
155 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
156 $logConfig = $wgDebugLogGroups[$channel];
158 if ( is_array( $logConfig ) ) {
160 if ( isset( $logConfig['sample'] ) ) {
161 // Emit randomly with a 1 in 'sample' chance for each message.
162 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
165 if ( isset( $logConfig['level'] ) ) {
166 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
169 // Emit unless the config value is explictly false.
170 $shouldEmit = $logConfig !== false;
173 } elseif ( isset( $context['private'] ) && $context['private'] ) {
174 // Don't emit if the message didn't match previous checks based on
175 // the channel and the event is marked as private. This check
176 // discards messages sent via wfDebugLog() with dest == 'private'
177 // and no explicit wgDebugLogGroups configuration.
180 // Default return value is the same as the historic wfDebug
181 // method: emit if $wgDebugLogFile has been set.
182 $shouldEmit = $wgDebugLogFile != '';
191 * Messages to the 'wfDebug' and 'wfLogDBError' channels receive special formatting to mimic the
192 * historic output of the functions of the same name. All other channel values are formatted
193 * based on the 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 === 'profileoutput' ) {
210 // Legacy wfLogProfilingData formatitng
212 if ( isset( $context['forwarded_for'] ) ) {
213 $forward = " forwarded for {$context['forwarded_for']}";
215 if ( isset( $context['client_ip'] ) ) {
216 $forward .= " client IP {$context['client_ip']}";
218 if ( isset( $context['from'] ) ) {
219 $forward .= " from {$context['from']}";
222 $forward = "\t(proxied via {$context['proxy']}{$forward})";
224 if ( $context['anon'] ) {
227 if ( !isset( $context['url'] ) ) {
228 $context['url'] = 'n/a';
231 $log = sprintf( "%s\t%04.3f\t%s%s\n",
232 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
234 $text = self
::formatAsWfDebugLog(
235 $channel, $log . $context['output'], $context );
237 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
238 $text = self
::formatAsWfDebug(
239 $channel, "[{$channel}] {$message}", $context );
242 // Default formatting is wfDebugLog's historic style
243 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
246 // Append stacktrace of exception if available
247 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
248 $e = $context['exception'];
251 if ( $e instanceof Exception
) {
252 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
254 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
255 // Exception has already been unpacked as structured data
256 $backtrace = $e['trace'];
260 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
265 return self
::interpolate( $text, $context );
269 * Format a message as `wfDebug()` would have formatted it.
271 * @param string $channel
272 * @param string $message
273 * @param array $context
276 protected static function formatAsWfDebug( $channel, $message, $context ) {
277 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
278 if ( isset( $context['seconds_elapsed'] ) ) {
279 // Prepend elapsed request time and real memory usage with two
281 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
283 if ( isset( $context['prefix'] ) ) {
284 $text = "{$context['prefix']}{$text}";
290 * Format a message as `wfLogDBError()` would have formatted it.
292 * @param string $channel
293 * @param string $message
294 * @param array $context
297 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
298 global $wgDBerrorLogTZ;
299 static $cachedTimezone = null;
301 if ( !$cachedTimezone ) {
302 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
305 $d = date_create( 'now', $cachedTimezone );
306 $date = $d->format( 'D M j G:i:s T Y' );
308 $host = wfHostname();
311 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
316 * Format a message as `wfDebugLog() would have formatted it.
318 * @param string $channel
319 * @param string $message
320 * @param array $context
323 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
324 $time = wfTimestamp( TS_DB
);
326 $host = wfHostname();
327 $text = "{$time} {$host} {$wiki}: {$message}\n";
332 * Interpolate placeholders in logging message.
334 * @param string $message
335 * @param array $context
336 * @return string Interpolated message
338 public static function interpolate( $message, array $context ) {
339 if ( strpos( $message, '{' ) !== false ) {
341 foreach ( $context as $key => $val ) {
342 $replace['{' . $key . '}'] = self
::flatten( $val );
344 $message = strtr( $message, $replace );
350 * Convert a logging context element to a string suitable for
356 protected static function flatten( $item ) {
357 if ( null === $item ) {
361 if ( is_bool( $item ) ) {
362 return $item ?
'true' : 'false';
365 if ( is_float( $item ) ) {
366 if ( is_infinite( $item ) ) {
367 return ( $item > 0 ?
'' : '-' ) . 'INF';
369 if ( is_nan( $item ) ) {
372 return (string)$item;
375 if ( is_scalar( $item ) ) {
376 return (string)$item;
379 if ( is_array( $item ) ) {
380 return '[Array(' . count( $item ) . ')]';
383 if ( $item instanceof \DateTime
) {
384 return $item->format( 'c' );
387 if ( $item instanceof Exception
) {
388 return '[Exception ' . get_class( $item ) . '( ' .
389 $item->getFile() . ':' . $item->getLine() . ') ' .
390 $item->getMessage() . ']';
393 if ( is_object( $item ) ) {
394 if ( method_exists( $item, '__toString' ) ) {
395 return (string)$item;
398 return '[Object ' . get_class( $item ) . ']';
401 if ( is_resource( $item ) ) {
402 return '[Resource ' . get_resource_type( $item ) . ']';
405 return '[Unknown ' . gettype( $item ) . ']';
409 * Select the appropriate log output destination for the given log event.
411 * If the event context contains 'destination'
413 * @param string $channel
414 * @param string $message
415 * @param array $context
418 protected static function destination( $channel, $message, $context ) {
419 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
421 // Default destination is the debug log file as historically used by
422 // the wfDebug function.
423 $destination = $wgDebugLogFile;
425 if ( isset( $context['destination'] ) ) {
426 // Use destination explicitly provided in context
427 $destination = $context['destination'];
429 } elseif ( $channel === 'wfDebug' ) {
430 $destination = $wgDebugLogFile;
432 } elseif ( $channel === 'wfLogDBError' ) {
433 $destination = $wgDBerrorLog;
435 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
436 $logConfig = $wgDebugLogGroups[$channel];
438 if ( is_array( $logConfig ) ) {
439 $destination = $logConfig['destination'];
441 $destination = strval( $logConfig );
449 * Log to a file without getting "file size exceeded" signals.
451 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
452 * lines to the specified port, prefixed by the specified prefix and a space.
454 * @param string $text
455 * @param string $file Filename
457 public static function emit( $text, $file ) {
458 if ( substr( $file, 0, 4 ) == 'udp:' ) {
459 $transport = UDPTransport
::newFromString( $file );
460 $transport->emit( $text );
462 \Wikimedia\
suppressWarnings();
463 $exists = file_exists( $file );
464 $size = $exists ?
filesize( $file ) : false;
466 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
468 file_put_contents( $file, $text, FILE_APPEND
);
470 \Wikimedia\restoreWarnings
();