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 Psr\Log\AbstractLogger
;
30 * PSR-3 logger that mimics the historic implementation of MediaWiki's
31 * wfErrorLog logging implementation.
33 * This logger is configured by the following global configuration variables:
35 * - `$wgDebugLogGroups`
39 * See documentation in DefaultSettings.php for detailed explanations of each
42 * @see \MediaWiki\Logger\LoggerFactory
44 * @author Bryan Davis <bd808@wikimedia.org>
45 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
47 class LegacyLogger
extends AbstractLogger
{
50 * @var string $channel
55 * Convert Psr\Log\LogLevel constants into int for sane comparisons
56 * These are the same values that Monlog uses
60 protected static $levelMapping = array(
61 LogLevel
::DEBUG
=> 100,
62 LogLevel
::INFO
=> 200,
63 LogLevel
::NOTICE
=> 250,
64 LogLevel
::WARNING
=> 300,
65 LogLevel
::ERROR
=> 400,
66 LogLevel
::CRITICAL
=> 500,
67 LogLevel
::ALERT
=> 550,
68 LogLevel
::EMERGENCY
=> 600,
73 * @param string $channel
75 public function __construct( $channel ) {
76 $this->channel
= $channel;
80 * Logs with an arbitrary level.
82 * @param string|int $level
83 * @param string $message
84 * @param array $context
86 public function log( $level, $message, array $context = array() ) {
87 if ( self
::shouldEmit( $this->channel
, $message, $level, $context ) ) {
88 $text = self
::format( $this->channel
, $message, $context );
89 $destination = self
::destination( $this->channel
, $message, $context );
90 self
::emit( $text, $destination );
92 // Add to debug toolbar
93 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 != '';
159 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
160 * receive special fomatting to mimic the historic output of the functions
161 * of the same name. All other channel values are formatted based on the
162 * historic output of the `wfDebugLog()` global function.
164 * @param string $channel
165 * @param string $message
166 * @param array $context
169 public static function format( $channel, $message, $context ) {
170 global $wgDebugLogGroups;
172 if ( $channel === 'wfDebug' ) {
173 $text = self
::formatAsWfDebug( $channel, $message, $context );
175 } elseif ( $channel === 'wfLogDBError' ) {
176 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
178 } elseif ( $channel === 'wfErrorLog' ) {
179 $text = "{$message}\n";
181 } elseif ( $channel === 'profileoutput' ) {
182 // Legacy wfLogProfilingData formatitng
184 if ( isset( $context['forwarded_for'] )) {
185 $forward = " forwarded for {$context['forwarded_for']}";
187 if ( isset( $context['client_ip'] ) ) {
188 $forward .= " client IP {$context['client_ip']}";
190 if ( isset( $context['from'] ) ) {
191 $forward .= " from {$context['from']}";
194 $forward = "\t(proxied via {$context['proxy']}{$forward})";
196 if ( $context['anon'] ) {
199 if ( !isset( $context['url'] ) ) {
200 $context['url'] = 'n/a';
203 $log = sprintf( "%s\t%04.3f\t%s%s\n",
204 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
206 $text = self
::formatAsWfDebugLog(
207 $channel, $log . $context['output'], $context );
209 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
210 $text = self
::formatAsWfDebug(
211 $channel, "[{$channel}] {$message}", $context );
214 // Default formatting is wfDebugLog's historic style
215 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
218 return self
::interpolate( $text, $context );
223 * Format a message as `wfDebug()` would have formatted it.
225 * @param string $channel
226 * @param string $message
227 * @param array $context
230 protected static function formatAsWfDebug( $channel, $message, $context ) {
231 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
232 if ( isset( $context['seconds_elapsed'] ) ) {
233 // Prepend elapsed request time and real memory usage with two
235 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
237 if ( isset( $context['prefix'] ) ) {
238 $text = "{$context['prefix']}{$text}";
245 * Format a message as `wfLogDBError()` would have formatted it.
247 * @param string $channel
248 * @param string $message
249 * @param array $context
252 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
253 global $wgDBerrorLogTZ;
254 static $cachedTimezone = null;
256 if ( !$cachedTimezone ) {
257 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
260 // Workaround for https://bugs.php.net/bug.php?id=52063
261 // Can be removed when min PHP > 5.3.6
262 if ( $cachedTimezone === null ) {
263 $d = date_create( 'now' );
265 $d = date_create( 'now', $cachedTimezone );
267 $date = $d->format( 'D M j G:i:s T Y' );
269 $host = wfHostname();
272 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
278 * Format a message as `wfDebugLog() would have formatted it.
280 * @param string $channel
281 * @param string $message
282 * @param array $context
284 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
285 $time = wfTimestamp( TS_DB
);
287 $host = wfHostname();
288 $text = "{$time} {$host} {$wiki}: {$message}\n";
294 * Interpolate placeholders in logging message.
296 * @param string $message
297 * @param array $context
298 * @return string Interpolated message
300 public static function interpolate( $message, array $context ) {
301 if ( strpos( $message, '{' ) !== false ) {
303 foreach ( $context as $key => $val ) {
304 $replace['{' . $key . '}'] = $val;
306 $message = strtr( $message, $replace );
313 * Select the appropriate log output destination for the given log event.
315 * If the event context contains 'destination'
317 * @param string $channel
318 * @param string $message
319 * @param array $context
322 protected static function destination( $channel, $message, $context ) {
323 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
325 // Default destination is the debug log file as historically used by
326 // the wfDebug function.
327 $destination = $wgDebugLogFile;
329 if ( isset( $context['destination'] ) ) {
330 // Use destination explicitly provided in context
331 $destination = $context['destination'];
333 } elseif ( $channel === 'wfDebug' ) {
334 $destination = $wgDebugLogFile;
336 } elseif ( $channel === 'wfLogDBError' ) {
337 $destination = $wgDBerrorLog;
339 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
340 $logConfig = $wgDebugLogGroups[$channel];
342 if ( is_array( $logConfig ) ) {
343 $destination = $logConfig['destination'];
345 $destination = strval( $logConfig );
354 * Log to a file without getting "file size exceeded" signals.
356 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
357 * lines to the specified port, prefixed by the specified prefix and a space.
359 * @param string $text
360 * @param string $file Filename
361 * @throws MWException
363 public static function emit( $text, $file ) {
364 if ( substr( $file, 0, 4 ) == 'udp:' ) {
365 $transport = UDPTransport
::newFromString( $file );
366 $transport->emit( $text );
368 wfSuppressWarnings();
369 $exists = file_exists( $file );
370 $size = $exists ?
filesize( $file ) : false;
372 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
374 file_put_contents( $file, $text, FILE_APPEND
);