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
;
25 use MWExceptionHandler
;
26 use Psr\Log\AbstractLogger
;
31 * PSR-3 logger that mimics the historic implementation of MediaWiki's
32 * wfErrorLog logging implementation.
34 * This logger is configured by the following global configuration variables:
36 * - `$wgDebugLogGroups`
40 * See documentation in DefaultSettings.php for detailed explanations of each
43 * @see \\MediaWiki\\Logger\\LoggerFactory
45 * @author Bryan Davis <bd808@wikimedia.org>
46 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
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 = array(
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,
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 );
99 * Determine if the given message should be emitted or not.
101 * @param string $channel
102 * @param string $message
103 * @param string|int $level Psr\\Log\\LogEvent constant or Monlog level int
104 * @param array $context
105 * @return bool True if message should be sent to disk/network, false
108 public static function shouldEmit( $channel, $message, $level, $context ) {
109 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
111 if ( $channel === 'wfLogDBError' ) {
112 // wfLogDBError messages are emitted if a database log location is
114 $shouldEmit = (bool)$wgDBerrorLog;
116 } elseif ( $channel === 'wfErrorLog' ) {
117 // All messages on the wfErrorLog channel should be emitted.
120 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
121 $logConfig = $wgDebugLogGroups[$channel];
123 if ( is_array( $logConfig ) ) {
125 if ( isset( $logConfig['sample'] ) ) {
126 // Emit randomly with a 1 in 'sample' chance for each message.
127 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
130 if ( isset( $logConfig['level'] ) ) {
131 if ( is_string( $level ) ) {
132 $level = self
::$levelMapping[$level];
134 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
137 // Emit unless the config value is explictly false.
138 $shouldEmit = $logConfig !== false;
141 } elseif ( isset( $context['private'] ) && $context['private'] ) {
142 // Don't emit if the message didn't match previous checks based on
143 // the channel and the event is marked as private. This check
144 // discards messages sent via wfDebugLog() with dest == 'private'
145 // and no explicit wgDebugLogGroups configuration.
148 // Default return value is the same as the historic wfDebug
149 // method: emit if $wgDebugLogFile has been set.
150 $shouldEmit = $wgDebugLogFile != '';
160 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
161 * receive special fomatting to mimic the historic output of the functions
162 * of the same name. All other channel values are formatted based on the
163 * historic output of the `wfDebugLog()` global function.
165 * @param string $channel
166 * @param string $message
167 * @param array $context
170 public static function format( $channel, $message, $context ) {
171 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
173 if ( $channel === 'wfDebug' ) {
174 $text = self
::formatAsWfDebug( $channel, $message, $context );
176 } elseif ( $channel === 'wfLogDBError' ) {
177 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
179 } elseif ( $channel === 'wfErrorLog' ) {
180 $text = "{$message}\n";
182 } elseif ( $channel === 'profileoutput' ) {
183 // Legacy wfLogProfilingData formatitng
185 if ( isset( $context['forwarded_for'] ) ) {
186 $forward = " forwarded for {$context['forwarded_for']}";
188 if ( isset( $context['client_ip'] ) ) {
189 $forward .= " client IP {$context['client_ip']}";
191 if ( isset( $context['from'] ) ) {
192 $forward .= " from {$context['from']}";
195 $forward = "\t(proxied via {$context['proxy']}{$forward})";
197 if ( $context['anon'] ) {
200 if ( !isset( $context['url'] ) ) {
201 $context['url'] = 'n/a';
204 $log = sprintf( "%s\t%04.3f\t%s%s\n",
205 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
207 $text = self
::formatAsWfDebugLog(
208 $channel, $log . $context['output'], $context );
210 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
211 $text = self
::formatAsWfDebug(
212 $channel, "[{$channel}] {$message}", $context );
215 // Default formatting is wfDebugLog's historic style
216 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
219 // Append stacktrace of exception if available
220 if ( $wgLogExceptionBacktrace &&
221 isset( $context['exception'] ) &&
222 $context['exception'] instanceof Exception
224 $text .= MWExceptionHandler
::getRedactedTraceAsString(
225 $context['exception']
229 return self
::interpolate( $text, $context );
234 * Format a message as `wfDebug()` would have formatted it.
236 * @param string $channel
237 * @param string $message
238 * @param array $context
241 protected static function formatAsWfDebug( $channel, $message, $context ) {
242 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
243 if ( isset( $context['seconds_elapsed'] ) ) {
244 // Prepend elapsed request time and real memory usage with two
246 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
248 if ( isset( $context['prefix'] ) ) {
249 $text = "{$context['prefix']}{$text}";
256 * Format a message as `wfLogDBError()` would have formatted it.
258 * @param string $channel
259 * @param string $message
260 * @param array $context
263 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
264 global $wgDBerrorLogTZ;
265 static $cachedTimezone = null;
267 if ( !$cachedTimezone ) {
268 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
271 // Workaround for https://bugs.php.net/bug.php?id=52063
272 // Can be removed when min PHP > 5.3.6
273 if ( $cachedTimezone === null ) {
274 $d = date_create( 'now' );
276 $d = date_create( 'now', $cachedTimezone );
278 $date = $d->format( 'D M j G:i:s T Y' );
280 $host = wfHostname();
283 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
289 * Format a message as `wfDebugLog() would have formatted it.
291 * @param string $channel
292 * @param string $message
293 * @param array $context
295 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
296 $time = wfTimestamp( TS_DB
);
298 $host = wfHostname();
299 $text = "{$time} {$host} {$wiki}: {$message}\n";
305 * Interpolate placeholders in logging message.
307 * @param string $message
308 * @param array $context
309 * @return string Interpolated message
311 public static function interpolate( $message, array $context ) {
312 if ( strpos( $message, '{' ) !== false ) {
314 foreach ( $context as $key => $val ) {
315 $replace['{' . $key . '}'] = self
::flatten( $val );
317 $message = strtr( $message, $replace );
324 * Convert a logging context element to a string suitable for
330 protected static function flatten( $item ) {
331 if ( null === $item ) {
335 if ( is_bool( $item ) ) {
336 return $item ?
'true' : 'false';
339 if ( is_float( $item ) ) {
340 if ( is_infinite( $item ) ) {
341 return ( $item > 0 ?
'' : '-' ) . 'INF';
343 if ( is_nan( $item ) ) {
349 if ( is_scalar( $item ) ) {
350 return (string) $item;
353 if ( is_array( $item ) ) {
354 return '[Array(' . count( $item ) . ')]';
357 if ( $item instanceof \DateTime
) {
358 return $item->format( 'c' );
361 if ( $item instanceof \Exception
) {
362 return '[Exception ' . get_class( $item ) . '( ' .
363 $item->getFile() . ':' . $item->getLine() . ') ' .
364 $item->getMessage() . ']';
367 if ( is_object( $item ) ) {
368 if ( method_exists( $item, '__toString' ) ) {
369 return (string) $item;
372 return '[Object ' . get_class( $item ) . ']';
375 if ( is_resource( $item ) ) {
376 return '[Resource ' . get_resource_type( $item ) . ']';
379 return '[Unknown ' . gettype( $item ) . ']';
384 * Select the appropriate log output destination for the given log event.
386 * If the event context contains 'destination'
388 * @param string $channel
389 * @param string $message
390 * @param array $context
393 protected static function destination( $channel, $message, $context ) {
394 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
396 // Default destination is the debug log file as historically used by
397 // the wfDebug function.
398 $destination = $wgDebugLogFile;
400 if ( isset( $context['destination'] ) ) {
401 // Use destination explicitly provided in context
402 $destination = $context['destination'];
404 } elseif ( $channel === 'wfDebug' ) {
405 $destination = $wgDebugLogFile;
407 } elseif ( $channel === 'wfLogDBError' ) {
408 $destination = $wgDBerrorLog;
410 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
411 $logConfig = $wgDebugLogGroups[$channel];
413 if ( is_array( $logConfig ) ) {
414 $destination = $logConfig['destination'];
416 $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
();