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 = [] ) {
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 === 'wfDebug' ) {
150 // wfDebug messages are emitted if a catch all logging file has
151 // been specified. Checked explicitly so that 'private' flagged
152 // messages are not discarded by unset $wgDebugLogGroups channel
154 $shouldEmit = $wgDebugLogFile != '';
156 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
157 $logConfig = $wgDebugLogGroups[$channel];
159 if ( is_array( $logConfig ) ) {
161 if ( isset( $logConfig['sample'] ) ) {
162 // Emit randomly with a 1 in 'sample' chance for each message.
163 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
166 if ( isset( $logConfig['level'] ) ) {
167 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
170 // Emit unless the config value is explictly false.
171 $shouldEmit = $logConfig !== false;
174 } elseif ( isset( $context['private'] ) && $context['private'] ) {
175 // Don't emit if the message didn't match previous checks based on
176 // the channel and the event is marked as private. This check
177 // discards messages sent via wfDebugLog() with dest == 'private'
178 // and no explicit wgDebugLogGroups configuration.
181 // Default return value is the same as the historic wfDebug
182 // method: emit if $wgDebugLogFile has been set.
183 $shouldEmit = $wgDebugLogFile != '';
192 * Messages to the 'wfDebug' and 'wfLogDBError' channels receive special formatting to mimic the
193 * historic output of the functions of the same name. All other channel values are formatted
194 * based on the historic output of the `wfDebugLog()` global function.
196 * @param string $channel
197 * @param string $message
198 * @param array $context
201 public static function format( $channel, $message, $context ) {
202 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
204 if ( $channel === 'wfDebug' ) {
205 $text = self
::formatAsWfDebug( $channel, $message, $context );
207 } elseif ( $channel === 'wfLogDBError' ) {
208 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
210 } elseif ( $channel === 'profileoutput' ) {
211 // Legacy wfLogProfilingData formatitng
213 if ( isset( $context['forwarded_for'] ) ) {
214 $forward = " forwarded for {$context['forwarded_for']}";
216 if ( isset( $context['client_ip'] ) ) {
217 $forward .= " client IP {$context['client_ip']}";
219 if ( isset( $context['from'] ) ) {
220 $forward .= " from {$context['from']}";
223 $forward = "\t(proxied via {$context['proxy']}{$forward})";
225 if ( $context['anon'] ) {
228 if ( !isset( $context['url'] ) ) {
229 $context['url'] = 'n/a';
232 $log = sprintf( "%s\t%04.3f\t%s%s\n",
233 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
235 $text = self
::formatAsWfDebugLog(
236 $channel, $log . $context['output'], $context );
238 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
239 $text = self
::formatAsWfDebug(
240 $channel, "[{$channel}] {$message}", $context );
243 // Default formatting is wfDebugLog's historic style
244 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
247 // Append stacktrace of exception if available
248 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
249 $e = $context['exception'];
252 if ( $e instanceof Exception
) {
253 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
255 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
256 // Exception has already been unpacked as structured data
257 $backtrace = $e['trace'];
261 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
266 return self
::interpolate( $text, $context );
270 * Format a message as `wfDebug()` would have formatted it.
272 * @param string $channel
273 * @param string $message
274 * @param array $context
277 protected static function formatAsWfDebug( $channel, $message, $context ) {
278 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
279 if ( isset( $context['seconds_elapsed'] ) ) {
280 // Prepend elapsed request time and real memory usage with two
282 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
284 if ( isset( $context['prefix'] ) ) {
285 $text = "{$context['prefix']}{$text}";
291 * Format a message as `wfLogDBError()` would have formatted it.
293 * @param string $channel
294 * @param string $message
295 * @param array $context
298 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
299 global $wgDBerrorLogTZ;
300 static $cachedTimezone = null;
302 if ( !$cachedTimezone ) {
303 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
306 $d = date_create( 'now', $cachedTimezone );
307 $date = $d->format( 'D M j G:i:s T Y' );
309 $host = wfHostname();
310 $wiki = WikiMap
::getWikiIdFromDomain( WikiMap
::getCurrentWikiDomain() );
312 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
317 * Format a message as `wfDebugLog() would have formatted it.
319 * @param string $channel
320 * @param string $message
321 * @param array $context
324 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
325 $time = wfTimestamp( TS_DB
);
326 $wiki = WikiMap
::getWikiIdFromDomain( WikiMap
::getCurrentWikiDomain() );
327 $host = wfHostname();
328 $text = "{$time} {$host} {$wiki}: {$message}\n";
333 * Interpolate placeholders in logging message.
335 * @param string $message
336 * @param array $context
337 * @return string Interpolated message
339 public static function interpolate( $message, array $context ) {
340 if ( strpos( $message, '{' ) !== false ) {
342 foreach ( $context as $key => $val ) {
343 $replace['{' . $key . '}'] = self
::flatten( $val );
345 $message = strtr( $message, $replace );
351 * Convert a logging context element to a string suitable for
357 protected static function flatten( $item ) {
358 if ( null === $item ) {
362 if ( is_bool( $item ) ) {
363 return $item ?
'true' : 'false';
366 if ( is_float( $item ) ) {
367 if ( is_infinite( $item ) ) {
368 return ( $item > 0 ?
'' : '-' ) . 'INF';
370 if ( is_nan( $item ) ) {
373 return (string)$item;
376 if ( is_scalar( $item ) ) {
377 return (string)$item;
380 if ( is_array( $item ) ) {
381 return '[Array(' . count( $item ) . ')]';
384 if ( $item instanceof \DateTime
) {
385 return $item->format( 'c' );
388 if ( $item instanceof Exception
) {
389 return '[Exception ' . get_class( $item ) . '( ' .
390 $item->getFile() . ':' . $item->getLine() . ') ' .
391 $item->getMessage() . ']';
394 if ( is_object( $item ) ) {
395 if ( method_exists( $item, '__toString' ) ) {
396 return (string)$item;
399 return '[Object ' . get_class( $item ) . ']';
402 if ( is_resource( $item ) ) {
403 return '[Resource ' . get_resource_type( $item ) . ']';
406 return '[Unknown ' . gettype( $item ) . ']';
410 * Select the appropriate log output destination for the given log event.
412 * If the event context contains 'destination'
414 * @param string $channel
415 * @param string $message
416 * @param array $context
419 protected static function destination( $channel, $message, $context ) {
420 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
422 // Default destination is the debug log file as historically used by
423 // the wfDebug function.
424 $destination = $wgDebugLogFile;
426 if ( isset( $context['destination'] ) ) {
427 // Use destination explicitly provided in context
428 $destination = $context['destination'];
430 } elseif ( $channel === 'wfDebug' ) {
431 $destination = $wgDebugLogFile;
433 } elseif ( $channel === 'wfLogDBError' ) {
434 $destination = $wgDBerrorLog;
436 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
437 $logConfig = $wgDebugLogGroups[$channel];
439 if ( is_array( $logConfig ) ) {
440 $destination = $logConfig['destination'];
442 $destination = strval( $logConfig );
450 * Log to a file without getting "file size exceeded" signals.
452 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
453 * lines to the specified port, prefixed by the specified prefix and a space.
455 * @param string $text
456 * @param string $file Filename
458 public static function emit( $text, $file ) {
459 if ( substr( $file, 0, 4 ) == 'udp:' ) {
460 $transport = UDPTransport
::newFromString( $file );
461 $transport->emit( $text );
463 \Wikimedia\
suppressWarnings();
464 $exists = file_exists( $file );
465 $size = $exists ?
filesize( $file ) : false;
467 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
469 file_put_contents( $file, $text, FILE_APPEND
);
471 \Wikimedia\restoreWarnings
();