Expose $wgMaxArticleSize in siteinfo query api
[mediawiki.git] / includes / debug / logger / LegacyLogger.php
blob526b4ab03b8888315608691f195143238e8cfd3e
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 = [
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 = [] ) {
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, [ '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 $d = date_create( 'now', $cachedTimezone );
286 $date = $d->format( 'D M j G:i:s T Y' );
288 $host = wfHostname();
289 $wiki = wfWikiID();
291 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
292 return $text;
296 * Format a message as `wfDebugLog() would have formatted it.
298 * @param string $channel
299 * @param string $message
300 * @param array $context
302 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
303 $time = wfTimestamp( TS_DB );
304 $wiki = wfWikiID();
305 $host = wfHostname();
306 $text = "{$time} {$host} {$wiki}: {$message}\n";
307 return $text;
311 * Interpolate placeholders in logging message.
313 * @param string $message
314 * @param array $context
315 * @return string Interpolated message
317 public static function interpolate( $message, array $context ) {
318 if ( strpos( $message, '{' ) !== false ) {
319 $replace = [];
320 foreach ( $context as $key => $val ) {
321 $replace['{' . $key . '}'] = self::flatten( $val );
323 $message = strtr( $message, $replace );
325 return $message;
329 * Convert a logging context element to a string suitable for
330 * interpolation.
332 * @param mixed $item
333 * @return string
335 protected static function flatten( $item ) {
336 if ( null === $item ) {
337 return '[Null]';
340 if ( is_bool( $item ) ) {
341 return $item ? 'true' : 'false';
344 if ( is_float( $item ) ) {
345 if ( is_infinite( $item ) ) {
346 return ( $item > 0 ? '' : '-' ) . 'INF';
348 if ( is_nan( $item ) ) {
349 return 'NaN';
351 return $item;
354 if ( is_scalar( $item ) ) {
355 return (string)$item;
358 if ( is_array( $item ) ) {
359 return '[Array(' . count( $item ) . ')]';
362 if ( $item instanceof \DateTime ) {
363 return $item->format( 'c' );
366 if ( $item instanceof Exception ) {
367 return '[Exception ' . get_class( $item ) . '( ' .
368 $item->getFile() . ':' . $item->getLine() . ') ' .
369 $item->getMessage() . ']';
372 if ( is_object( $item ) ) {
373 if ( method_exists( $item, '__toString' ) ) {
374 return (string)$item;
377 return '[Object ' . get_class( $item ) . ']';
380 if ( is_resource( $item ) ) {
381 return '[Resource ' . get_resource_type( $item ) . ']';
384 return '[Unknown ' . gettype( $item ) . ']';
388 * Select the appropriate log output destination for the given log event.
390 * If the event context contains 'destination'
392 * @param string $channel
393 * @param string $message
394 * @param array $context
395 * @return string
397 protected static function destination( $channel, $message, $context ) {
398 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
400 // Default destination is the debug log file as historically used by
401 // the wfDebug function.
402 $destination = $wgDebugLogFile;
404 if ( isset( $context['destination'] ) ) {
405 // Use destination explicitly provided in context
406 $destination = $context['destination'];
408 } elseif ( $channel === 'wfDebug' ) {
409 $destination = $wgDebugLogFile;
411 } elseif ( $channel === 'wfLogDBError' ) {
412 $destination = $wgDBerrorLog;
414 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
415 $logConfig = $wgDebugLogGroups[$channel];
417 if ( is_array( $logConfig ) ) {
418 $destination = $logConfig['destination'];
419 } else {
420 $destination = strval( $logConfig );
424 return $destination;
428 * Log to a file without getting "file size exceeded" signals.
430 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
431 * lines to the specified port, prefixed by the specified prefix and a space.
433 * @param string $text
434 * @param string $file Filename
435 * @throws MWException
437 public static function emit( $text, $file ) {
438 if ( substr( $file, 0, 4 ) == 'udp:' ) {
439 $transport = UDPTransport::newFromString( $file );
440 $transport->emit( $text );
441 } else {
442 \MediaWiki\suppressWarnings();
443 $exists = file_exists( $file );
444 $size = $exists ? filesize( $file ) : false;
445 if ( !$exists ||
446 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
448 file_put_contents( $file, $text, FILE_APPEND );
450 \MediaWiki\restoreWarnings();