Merge "Remove not used private member variable mParserWarnings from OutputPage"
[mediawiki.git] / includes / debug / logger / LegacyLogger.php
blob34ea64135c9812486816c7ae202da8f68a6d4c76
1 <?php
2 /**
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
18 * @file
21 namespace MediaWiki\Logger;
23 use DateTimeZone;
24 use Exception;
25 use MWDebug;
26 use MWExceptionHandler;
27 use Psr\Log\AbstractLogger;
28 use Psr\Log\LogLevel;
29 use UDPTransport;
31 /**
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:
36 * - `$wgDebugLogFile`
37 * - `$wgDebugLogGroups`
38 * - `$wgDBerrorLog`
39 * - `$wgDBerrorLogTZ`
41 * See documentation in DefaultSettings.php for detailed explanations of each
42 * variable.
44 * @see \MediaWiki\Logger\LoggerFactory
45 * @since 1.25
46 * @author Bryan Davis <bd808@wikimedia.org>
47 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
49 class LegacyLogger extends AbstractLogger {
51 /**
52 * @var string $channel
54 protected $channel;
56 /**
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,
73 /**
74 * @param string $channel
76 public function __construct( $channel ) {
77 $this->channel = $channel;
80 /**
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 if ( !isset( $context['private'] ) || !$context['private'] ) {
94 // Add to debug toolbar if not marked as "private"
95 MWDebug::debugMsg( $message, array( 'channel' => $this->channel ) + $context );
99 /**
100 * Determine if the given message should be emitted or not.
102 * @param string $channel
103 * @param string $message
104 * @param string|int $level \Psr\Log\LogEvent constant or Monlog level int
105 * @param array $context
106 * @return bool True if message should be sent to disk/network, false
107 * otherwise
109 public static function shouldEmit( $channel, $message, $level, $context ) {
110 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
112 if ( $channel === 'wfLogDBError' ) {
113 // wfLogDBError messages are emitted if a database log location is
114 // specfied.
115 $shouldEmit = (bool)$wgDBerrorLog;
117 } elseif ( $channel === 'wfErrorLog' ) {
118 // All messages on the wfErrorLog channel should be emitted.
119 $shouldEmit = true;
121 } elseif ( $channel === 'wfDebug' ) {
122 // wfDebug messages are emitted if a catch all logging file has
123 // been specified. Checked explicitly so that 'private' flagged
124 // messages are not discarded by unset $wgDebugLogGroups channel
125 // handling below.
126 $shouldEmit = $wgDebugLogFile != '';
128 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
129 $logConfig = $wgDebugLogGroups[$channel];
131 if ( is_array( $logConfig ) ) {
132 $shouldEmit = true;
133 if ( isset( $logConfig['sample'] ) ) {
134 // Emit randomly with a 1 in 'sample' chance for each message.
135 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
138 if ( isset( $logConfig['level'] ) ) {
139 if ( is_string( $level ) ) {
140 $level = self::$levelMapping[$level];
142 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
144 } else {
145 // Emit unless the config value is explictly false.
146 $shouldEmit = $logConfig !== false;
149 } elseif ( isset( $context['private'] ) && $context['private'] ) {
150 // Don't emit if the message didn't match previous checks based on
151 // the channel and the event is marked as private. This check
152 // discards messages sent via wfDebugLog() with dest == 'private'
153 // and no explicit wgDebugLogGroups configuration.
154 $shouldEmit = false;
155 } else {
156 // Default return value is the same as the historic wfDebug
157 // method: emit if $wgDebugLogFile has been set.
158 $shouldEmit = $wgDebugLogFile != '';
161 return $shouldEmit;
165 * Format a message.
167 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
168 * receive special fomatting to mimic the historic output of the functions
169 * of the same name. All other channel values are formatted based on the
170 * historic output of the `wfDebugLog()` global function.
172 * @param string $channel
173 * @param string $message
174 * @param array $context
175 * @return string
177 public static function format( $channel, $message, $context ) {
178 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
180 if ( $channel === 'wfDebug' ) {
181 $text = self::formatAsWfDebug( $channel, $message, $context );
183 } elseif ( $channel === 'wfLogDBError' ) {
184 $text = self::formatAsWfLogDBError( $channel, $message, $context );
186 } elseif ( $channel === 'wfErrorLog' ) {
187 $text = "{$message}\n";
189 } elseif ( $channel === 'profileoutput' ) {
190 // Legacy wfLogProfilingData formatitng
191 $forward = '';
192 if ( isset( $context['forwarded_for'] ) ) {
193 $forward = " forwarded for {$context['forwarded_for']}";
195 if ( isset( $context['client_ip'] ) ) {
196 $forward .= " client IP {$context['client_ip']}";
198 if ( isset( $context['from'] ) ) {
199 $forward .= " from {$context['from']}";
201 if ( $forward ) {
202 $forward = "\t(proxied via {$context['proxy']}{$forward})";
204 if ( $context['anon'] ) {
205 $forward .= ' anon';
207 if ( !isset( $context['url'] ) ) {
208 $context['url'] = 'n/a';
211 $log = sprintf( "%s\t%04.3f\t%s%s\n",
212 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
214 $text = self::formatAsWfDebugLog(
215 $channel, $log . $context['output'], $context );
217 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
218 $text = self::formatAsWfDebug(
219 $channel, "[{$channel}] {$message}", $context );
221 } else {
222 // Default formatting is wfDebugLog's historic style
223 $text = self::formatAsWfDebugLog( $channel, $message, $context );
226 // Append stacktrace of exception if available
227 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
228 $e = $context['exception'];
229 $backtrace = false;
231 if ( $e instanceof Exception ) {
232 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
234 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
235 // Exception has already been unpacked as structured data
236 $backtrace = $e['trace'];
239 if ( $backtrace ) {
240 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
241 "\n";
245 return self::interpolate( $text, $context );
249 * Format a message as `wfDebug()` would have formatted it.
251 * @param string $channel
252 * @param string $message
253 * @param array $context
254 * @return string
256 protected static function formatAsWfDebug( $channel, $message, $context ) {
257 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
258 if ( isset( $context['seconds_elapsed'] ) ) {
259 // Prepend elapsed request time and real memory usage with two
260 // trailing spaces.
261 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
263 if ( isset( $context['prefix'] ) ) {
264 $text = "{$context['prefix']}{$text}";
266 return "{$text}\n";
270 * Format a message as `wfLogDBError()` would have formatted it.
272 * @param string $channel
273 * @param string $message
274 * @param array $context
275 * @return string
277 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
278 global $wgDBerrorLogTZ;
279 static $cachedTimezone = null;
281 if ( !$cachedTimezone ) {
282 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
285 // Workaround for https://bugs.php.net/bug.php?id=52063
286 // Can be removed when min PHP > 5.3.6
287 if ( $cachedTimezone === null ) {
288 $d = date_create( 'now' );
289 } else {
290 $d = date_create( 'now', $cachedTimezone );
292 $date = $d->format( 'D M j G:i:s T Y' );
294 $host = wfHostname();
295 $wiki = wfWikiID();
297 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
298 return $text;
302 * Format a message as `wfDebugLog() would have formatted it.
304 * @param string $channel
305 * @param string $message
306 * @param array $context
308 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
309 $time = wfTimestamp( TS_DB );
310 $wiki = wfWikiID();
311 $host = wfHostname();
312 $text = "{$time} {$host} {$wiki}: {$message}\n";
313 return $text;
317 * Interpolate placeholders in logging message.
319 * @param string $message
320 * @param array $context
321 * @return string Interpolated message
323 public static function interpolate( $message, array $context ) {
324 if ( strpos( $message, '{' ) !== false ) {
325 $replace = array();
326 foreach ( $context as $key => $val ) {
327 $replace['{' . $key . '}'] = self::flatten( $val );
329 $message = strtr( $message, $replace );
331 return $message;
335 * Convert a logging context element to a string suitable for
336 * interpolation.
338 * @param mixed $item
339 * @return string
341 protected static function flatten( $item ) {
342 if ( null === $item ) {
343 return '[Null]';
346 if ( is_bool( $item ) ) {
347 return $item ? 'true' : 'false';
350 if ( is_float( $item ) ) {
351 if ( is_infinite( $item ) ) {
352 return ( $item > 0 ? '' : '-' ) . 'INF';
354 if ( is_nan( $item ) ) {
355 return 'NaN';
357 return $item;
360 if ( is_scalar( $item ) ) {
361 return (string)$item;
364 if ( is_array( $item ) ) {
365 return '[Array(' . count( $item ) . ')]';
368 if ( $item instanceof \DateTime ) {
369 return $item->format( 'c' );
372 if ( $item instanceof Exception ) {
373 return '[Exception ' . get_class( $item ) . '( ' .
374 $item->getFile() . ':' . $item->getLine() . ') ' .
375 $item->getMessage() . ']';
378 if ( is_object( $item ) ) {
379 if ( method_exists( $item, '__toString' ) ) {
380 return (string)$item;
383 return '[Object ' . get_class( $item ) . ']';
386 if ( is_resource( $item ) ) {
387 return '[Resource ' . get_resource_type( $item ) . ']';
390 return '[Unknown ' . gettype( $item ) . ']';
394 * Select the appropriate log output destination for the given log event.
396 * If the event context contains 'destination'
398 * @param string $channel
399 * @param string $message
400 * @param array $context
401 * @return string
403 protected static function destination( $channel, $message, $context ) {
404 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
406 // Default destination is the debug log file as historically used by
407 // the wfDebug function.
408 $destination = $wgDebugLogFile;
410 if ( isset( $context['destination'] ) ) {
411 // Use destination explicitly provided in context
412 $destination = $context['destination'];
414 } elseif ( $channel === 'wfDebug' ) {
415 $destination = $wgDebugLogFile;
417 } elseif ( $channel === 'wfLogDBError' ) {
418 $destination = $wgDBerrorLog;
420 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
421 $logConfig = $wgDebugLogGroups[$channel];
423 if ( is_array( $logConfig ) ) {
424 $destination = $logConfig['destination'];
425 } else {
426 $destination = strval( $logConfig );
430 return $destination;
434 * Log to a file without getting "file size exceeded" signals.
436 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
437 * lines to the specified port, prefixed by the specified prefix and a space.
439 * @param string $text
440 * @param string $file Filename
441 * @throws MWException
443 public static function emit( $text, $file ) {
444 if ( substr( $file, 0, 4 ) == 'udp:' ) {
445 $transport = UDPTransport::newFromString( $file );
446 $transport->emit( $text );
447 } else {
448 \MediaWiki\suppressWarnings();
449 $exists = file_exists( $file );
450 $size = $exists ? filesize( $file ) : false;
451 if ( !$exists ||
452 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
454 file_put_contents( $file, $text, FILE_APPEND );
456 \MediaWiki\restoreWarnings();