Special case opus mime detction
[mediawiki.git] / includes / debug / logger / LegacyLogger.php
blobbaf4637e835d968dc650333fcaf8a3b23754a92c
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 * @var array
76 protected static $dbChannels = [
77 'DBQuery' => true,
78 'DBConnection' => true
81 /**
82 * @param string $channel
84 public function __construct( $channel ) {
85 $this->channel = $channel;
88 /**
89 * Logs with an arbitrary level.
91 * @param string|int $level
92 * @param string $message
93 * @param array $context
94 * @return null
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';
112 } else {
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
135 * otherwise
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
146 // specfied.
147 $shouldEmit = (bool)$wgDBerrorLog;
149 } elseif ( $channel === 'wfErrorLog' ) {
150 // All messages on the wfErrorLog channel should be emitted.
151 $shouldEmit = true;
153 } elseif ( $channel === 'wfDebug' ) {
154 // wfDebug messages are emitted if a catch all logging file has
155 // been specified. Checked explicitly so that 'private' flagged
156 // messages are not discarded by unset $wgDebugLogGroups channel
157 // handling below.
158 $shouldEmit = $wgDebugLogFile != '';
160 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
161 $logConfig = $wgDebugLogGroups[$channel];
163 if ( is_array( $logConfig ) ) {
164 $shouldEmit = true;
165 if ( isset( $logConfig['sample'] ) ) {
166 // Emit randomly with a 1 in 'sample' chance for each message.
167 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
170 if ( isset( $logConfig['level'] ) ) {
171 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
173 } else {
174 // Emit unless the config value is explictly false.
175 $shouldEmit = $logConfig !== false;
178 } elseif ( isset( $context['private'] ) && $context['private'] ) {
179 // Don't emit if the message didn't match previous checks based on
180 // the channel and the event is marked as private. This check
181 // discards messages sent via wfDebugLog() with dest == 'private'
182 // and no explicit wgDebugLogGroups configuration.
183 $shouldEmit = false;
184 } else {
185 // Default return value is the same as the historic wfDebug
186 // method: emit if $wgDebugLogFile has been set.
187 $shouldEmit = $wgDebugLogFile != '';
190 return $shouldEmit;
194 * Format a message.
196 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
197 * receive special fomatting to mimic the historic output of the functions
198 * of the same name. All other channel values are formatted based on the
199 * historic output of the `wfDebugLog()` global function.
201 * @param string $channel
202 * @param string $message
203 * @param array $context
204 * @return string
206 public static function format( $channel, $message, $context ) {
207 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
209 if ( $channel === 'wfDebug' ) {
210 $text = self::formatAsWfDebug( $channel, $message, $context );
212 } elseif ( $channel === 'wfLogDBError' ) {
213 $text = self::formatAsWfLogDBError( $channel, $message, $context );
215 } elseif ( $channel === 'wfErrorLog' ) {
216 $text = "{$message}\n";
218 } elseif ( $channel === 'profileoutput' ) {
219 // Legacy wfLogProfilingData formatitng
220 $forward = '';
221 if ( isset( $context['forwarded_for'] ) ) {
222 $forward = " forwarded for {$context['forwarded_for']}";
224 if ( isset( $context['client_ip'] ) ) {
225 $forward .= " client IP {$context['client_ip']}";
227 if ( isset( $context['from'] ) ) {
228 $forward .= " from {$context['from']}";
230 if ( $forward ) {
231 $forward = "\t(proxied via {$context['proxy']}{$forward})";
233 if ( $context['anon'] ) {
234 $forward .= ' anon';
236 if ( !isset( $context['url'] ) ) {
237 $context['url'] = 'n/a';
240 $log = sprintf( "%s\t%04.3f\t%s%s\n",
241 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
243 $text = self::formatAsWfDebugLog(
244 $channel, $log . $context['output'], $context );
246 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
247 $text = self::formatAsWfDebug(
248 $channel, "[{$channel}] {$message}", $context );
250 } else {
251 // Default formatting is wfDebugLog's historic style
252 $text = self::formatAsWfDebugLog( $channel, $message, $context );
255 // Append stacktrace of exception if available
256 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
257 $e = $context['exception'];
258 $backtrace = false;
260 if ( $e instanceof Exception ) {
261 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
263 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
264 // Exception has already been unpacked as structured data
265 $backtrace = $e['trace'];
268 if ( $backtrace ) {
269 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
270 "\n";
274 return self::interpolate( $text, $context );
278 * Format a message as `wfDebug()` would have formatted it.
280 * @param string $channel
281 * @param string $message
282 * @param array $context
283 * @return string
285 protected static function formatAsWfDebug( $channel, $message, $context ) {
286 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
287 if ( isset( $context['seconds_elapsed'] ) ) {
288 // Prepend elapsed request time and real memory usage with two
289 // trailing spaces.
290 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
292 if ( isset( $context['prefix'] ) ) {
293 $text = "{$context['prefix']}{$text}";
295 return "{$text}\n";
299 * Format a message as `wfLogDBError()` would have formatted it.
301 * @param string $channel
302 * @param string $message
303 * @param array $context
304 * @return string
306 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
307 global $wgDBerrorLogTZ;
308 static $cachedTimezone = null;
310 if ( !$cachedTimezone ) {
311 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
314 $d = date_create( 'now', $cachedTimezone );
315 $date = $d->format( 'D M j G:i:s T Y' );
317 $host = wfHostname();
318 $wiki = wfWikiID();
320 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
321 return $text;
325 * Format a message as `wfDebugLog() would have formatted it.
327 * @param string $channel
328 * @param string $message
329 * @param array $context
330 * @return string
332 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
333 $time = wfTimestamp( TS_DB );
334 $wiki = wfWikiID();
335 $host = wfHostname();
336 $text = "{$time} {$host} {$wiki}: {$message}\n";
337 return $text;
341 * Interpolate placeholders in logging message.
343 * @param string $message
344 * @param array $context
345 * @return string Interpolated message
347 public static function interpolate( $message, array $context ) {
348 if ( strpos( $message, '{' ) !== false ) {
349 $replace = [];
350 foreach ( $context as $key => $val ) {
351 $replace['{' . $key . '}'] = self::flatten( $val );
353 $message = strtr( $message, $replace );
355 return $message;
359 * Convert a logging context element to a string suitable for
360 * interpolation.
362 * @param mixed $item
363 * @return string
365 protected static function flatten( $item ) {
366 if ( null === $item ) {
367 return '[Null]';
370 if ( is_bool( $item ) ) {
371 return $item ? 'true' : 'false';
374 if ( is_float( $item ) ) {
375 if ( is_infinite( $item ) ) {
376 return ( $item > 0 ? '' : '-' ) . 'INF';
378 if ( is_nan( $item ) ) {
379 return 'NaN';
381 return (string)$item;
384 if ( is_scalar( $item ) ) {
385 return (string)$item;
388 if ( is_array( $item ) ) {
389 return '[Array(' . count( $item ) . ')]';
392 if ( $item instanceof \DateTime ) {
393 return $item->format( 'c' );
396 if ( $item instanceof Exception ) {
397 return '[Exception ' . get_class( $item ) . '( ' .
398 $item->getFile() . ':' . $item->getLine() . ') ' .
399 $item->getMessage() . ']';
402 if ( is_object( $item ) ) {
403 if ( method_exists( $item, '__toString' ) ) {
404 return (string)$item;
407 return '[Object ' . get_class( $item ) . ']';
410 if ( is_resource( $item ) ) {
411 return '[Resource ' . get_resource_type( $item ) . ']';
414 return '[Unknown ' . gettype( $item ) . ']';
418 * Select the appropriate log output destination for the given log event.
420 * If the event context contains 'destination'
422 * @param string $channel
423 * @param string $message
424 * @param array $context
425 * @return string
427 protected static function destination( $channel, $message, $context ) {
428 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
430 // Default destination is the debug log file as historically used by
431 // the wfDebug function.
432 $destination = $wgDebugLogFile;
434 if ( isset( $context['destination'] ) ) {
435 // Use destination explicitly provided in context
436 $destination = $context['destination'];
438 } elseif ( $channel === 'wfDebug' ) {
439 $destination = $wgDebugLogFile;
441 } elseif ( $channel === 'wfLogDBError' ) {
442 $destination = $wgDBerrorLog;
444 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
445 $logConfig = $wgDebugLogGroups[$channel];
447 if ( is_array( $logConfig ) ) {
448 $destination = $logConfig['destination'];
449 } else {
450 $destination = strval( $logConfig );
454 return $destination;
458 * Log to a file without getting "file size exceeded" signals.
460 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
461 * lines to the specified port, prefixed by the specified prefix and a space.
463 * @param string $text
464 * @param string $file Filename
466 public static function emit( $text, $file ) {
467 if ( substr( $file, 0, 4 ) == 'udp:' ) {
468 $transport = UDPTransport::newFromString( $file );
469 $transport->emit( $text );
470 } else {
471 \MediaWiki\suppressWarnings();
472 $exists = file_exists( $file );
473 $size = $exists ? filesize( $file ) : false;
474 if ( !$exists ||
475 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
477 file_put_contents( $file, $text, FILE_APPEND );
479 \MediaWiki\restoreWarnings();