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 = array(
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,
74 * @param string $channel
76 public function __construct( $channel ) {
77 $this->channel
= $channel;
81 * Logs with an arbitrary level.
83 * @param string|int $level
84 * @param string $message
85 * @param array $context
87 public function log( $level, $message, array $context = array() ) {
88 if ( self
::shouldEmit( $this->channel
, $message, $level, $context ) ) {
89 $text = self
::format( $this->channel
, $message, $context );
90 $destination = self
::destination( $this->channel
, $message, $context );
91 self
::emit( $text, $destination );
93 // Add to debug toolbar
94 MWDebug
::debugMsg( $message, array( 'channel' => $this->channel
) +
$context );
98 * Determine if the given message should be emitted or not.
100 * @param string $channel
101 * @param string $message
102 * @param string|int $level \Psr\Log\LogEvent constant or Monlog level int
103 * @param array $context
104 * @return bool True if message should be sent to disk/network, false
107 public static function shouldEmit( $channel, $message, $level, $context ) {
108 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
110 if ( $channel === 'wfLogDBError' ) {
111 // wfLogDBError messages are emitted if a database log location is
113 $shouldEmit = (bool)$wgDBerrorLog;
115 } elseif ( $channel === 'wfErrorLog' ) {
116 // All messages on the wfErrorLog channel should be emitted.
119 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
120 $logConfig = $wgDebugLogGroups[$channel];
122 if ( is_array( $logConfig ) ) {
124 if ( isset( $logConfig['sample'] ) ) {
125 // Emit randomly with a 1 in 'sample' chance for each message.
126 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
129 if ( isset( $logConfig['level'] ) ) {
130 if ( is_string( $level ) ) {
131 $level = self
::$levelMapping[$level];
133 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
136 // Emit unless the config value is explictly false.
137 $shouldEmit = $logConfig !== false;
140 } elseif ( isset( $context['private'] ) && $context['private'] ) {
141 // Don't emit if the message didn't match previous checks based on
142 // the channel and the event is marked as private. This check
143 // discards messages sent via wfDebugLog() with dest == 'private'
144 // and no explicit wgDebugLogGroups configuration.
147 // Default return value is the same as the historic wfDebug
148 // method: emit if $wgDebugLogFile has been set.
149 $shouldEmit = $wgDebugLogFile != '';
158 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
159 * receive special fomatting to mimic the historic output of the functions
160 * of the same name. All other channel values are formatted based on the
161 * historic output of the `wfDebugLog()` global function.
163 * @param string $channel
164 * @param string $message
165 * @param array $context
168 public static function format( $channel, $message, $context ) {
169 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
171 if ( $channel === 'wfDebug' ) {
172 $text = self
::formatAsWfDebug( $channel, $message, $context );
174 } elseif ( $channel === 'wfLogDBError' ) {
175 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
177 } elseif ( $channel === 'wfErrorLog' ) {
178 $text = "{$message}\n";
180 } elseif ( $channel === 'profileoutput' ) {
181 // Legacy wfLogProfilingData formatitng
183 if ( isset( $context['forwarded_for'] ) ) {
184 $forward = " forwarded for {$context['forwarded_for']}";
186 if ( isset( $context['client_ip'] ) ) {
187 $forward .= " client IP {$context['client_ip']}";
189 if ( isset( $context['from'] ) ) {
190 $forward .= " from {$context['from']}";
193 $forward = "\t(proxied via {$context['proxy']}{$forward})";
195 if ( $context['anon'] ) {
198 if ( !isset( $context['url'] ) ) {
199 $context['url'] = 'n/a';
202 $log = sprintf( "%s\t%04.3f\t%s%s\n",
203 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
205 $text = self
::formatAsWfDebugLog(
206 $channel, $log . $context['output'], $context );
208 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
209 $text = self
::formatAsWfDebug(
210 $channel, "[{$channel}] {$message}", $context );
213 // Default formatting is wfDebugLog's historic style
214 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
217 // Append stacktrace of exception if available
218 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
219 $e = $context['exception'];
222 if ( $e instanceof Exception
) {
223 $backtrace = MWExceptionHandler
::getRedactedTrace( $e );
225 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
226 // Exception has already been unpacked as structured data
227 $backtrace = $e['trace'];
231 $text .= MWExceptionHandler
::prettyPrintTrace( $backtrace ) .
236 return self
::interpolate( $text, $context );
240 * Format a message as `wfDebug()` would have formatted it.
242 * @param string $channel
243 * @param string $message
244 * @param array $context
247 protected static function formatAsWfDebug( $channel, $message, $context ) {
248 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
249 if ( isset( $context['seconds_elapsed'] ) ) {
250 // Prepend elapsed request time and real memory usage with two
252 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
254 if ( isset( $context['prefix'] ) ) {
255 $text = "{$context['prefix']}{$text}";
261 * Format a message as `wfLogDBError()` would have formatted it.
263 * @param string $channel
264 * @param string $message
265 * @param array $context
268 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
269 global $wgDBerrorLogTZ;
270 static $cachedTimezone = null;
272 if ( !$cachedTimezone ) {
273 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
276 // Workaround for https://bugs.php.net/bug.php?id=52063
277 // Can be removed when min PHP > 5.3.6
278 if ( $cachedTimezone === null ) {
279 $d = date_create( 'now' );
281 $d = date_create( 'now', $cachedTimezone );
283 $date = $d->format( 'D M j G:i:s T Y' );
285 $host = wfHostname();
288 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
293 * Format a message as `wfDebugLog() would have formatted it.
295 * @param string $channel
296 * @param string $message
297 * @param array $context
299 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
300 $time = wfTimestamp( TS_DB
);
302 $host = wfHostname();
303 $text = "{$time} {$host} {$wiki}: {$message}\n";
308 * Interpolate placeholders in logging message.
310 * @param string $message
311 * @param array $context
312 * @return string Interpolated message
314 public static function interpolate( $message, array $context ) {
315 if ( strpos( $message, '{' ) !== false ) {
317 foreach ( $context as $key => $val ) {
318 $replace['{' . $key . '}'] = self
::flatten( $val );
320 $message = strtr( $message, $replace );
326 * Convert a logging context element to a string suitable for
332 protected static function flatten( $item ) {
333 if ( null === $item ) {
337 if ( is_bool( $item ) ) {
338 return $item ?
'true' : 'false';
341 if ( is_float( $item ) ) {
342 if ( is_infinite( $item ) ) {
343 return ( $item > 0 ?
'' : '-' ) . 'INF';
345 if ( is_nan( $item ) ) {
351 if ( is_scalar( $item ) ) {
352 return (string)$item;
355 if ( is_array( $item ) ) {
356 return '[Array(' . count( $item ) . ')]';
359 if ( $item instanceof \DateTime
) {
360 return $item->format( 'c' );
363 if ( $item instanceof Exception
) {
364 return '[Exception ' . get_class( $item ) . '( ' .
365 $item->getFile() . ':' . $item->getLine() . ') ' .
366 $item->getMessage() . ']';
369 if ( is_object( $item ) ) {
370 if ( method_exists( $item, '__toString' ) ) {
371 return (string)$item;
374 return '[Object ' . get_class( $item ) . ']';
377 if ( is_resource( $item ) ) {
378 return '[Resource ' . get_resource_type( $item ) . ']';
381 return '[Unknown ' . gettype( $item ) . ']';
385 * Select the appropriate log output destination for the given log event.
387 * If the event context contains 'destination'
389 * @param string $channel
390 * @param string $message
391 * @param array $context
394 protected static function destination( $channel, $message, $context ) {
395 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
397 // Default destination is the debug log file as historically used by
398 // the wfDebug function.
399 $destination = $wgDebugLogFile;
401 if ( isset( $context['destination'] ) ) {
402 // Use destination explicitly provided in context
403 $destination = $context['destination'];
405 } elseif ( $channel === 'wfDebug' ) {
406 $destination = $wgDebugLogFile;
408 } elseif ( $channel === 'wfLogDBError' ) {
409 $destination = $wgDBerrorLog;
411 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
412 $logConfig = $wgDebugLogGroups[$channel];
414 if ( is_array( $logConfig ) ) {
415 $destination = $logConfig['destination'];
417 $destination = strval( $logConfig );
425 * Log to a file without getting "file size exceeded" signals.
427 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
428 * lines to the specified port, prefixed by the specified prefix and a space.
430 * @param string $text
431 * @param string $file Filename
432 * @throws MWException
434 public static function emit( $text, $file ) {
435 if ( substr( $file, 0, 4 ) == 'udp:' ) {
436 $transport = UDPTransport
::newFromString( $file );
437 $transport->emit( $text );
439 \MediaWiki\
suppressWarnings();
440 $exists = file_exists( $file );
441 $size = $exists ?
filesize( $file ) : false;
443 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
445 file_put_contents( $file, $text, FILE_APPEND
);
447 \MediaWiki\restoreWarnings
();