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
22 * PSR-3 logger that mimics the historic implementation of MediaWiki's
23 * wfErrorLog logging implementation.
25 * This logger is configured by the following global configuration variables:
27 * - `$wgDebugLogGroups`
31 * See documentation in DefaultSettings.php for detailed explanations of each
34 * @see MWLoggerFactory
36 * @author Bryan Davis <bd808@wikimedia.org>
37 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
39 use Psr\Log\AbstractLogger
;
42 class MWLoggerLegacyLogger
extends AbstractLogger
{
45 * @var string $channel
50 * Convert Psr\Log\LogLevel constants into int for sane comparisons
51 * These are the same values that Monlog uses
55 protected static $levelMapping = array(
56 LogLevel
::DEBUG
=> 100,
57 LogLevel
::INFO
=> 200,
58 LogLevel
::NOTICE
=> 250,
59 LogLevel
::WARNING
=> 300,
60 LogLevel
::ERROR
=> 400,
61 LogLevel
::CRITICAL
=> 500,
62 LogLevel
::ALERT
=> 550,
63 LogLevel
::EMERGENCY
=> 600,
68 * @param string $channel
70 public function __construct( $channel ) {
71 $this->channel
= $channel;
75 * Logs with an arbitrary level.
77 * @param string|int $level
78 * @param string $message
79 * @param array $context
81 public function log( $level, $message, array $context = array() ) {
82 if ( self
::shouldEmit( $this->channel
, $message, $level, $context ) ) {
83 $text = self
::format( $this->channel
, $message, $context );
84 $destination = self
::destination( $this->channel
, $message, $context );
85 self
::emit( $text, $destination );
87 // Add to debug toolbar
88 MWDebug
::debugMsg( $message, array( 'channel' => $this->channel
) +
$context );
93 * Determine if the given message should be emitted or not.
95 * @param string $channel
96 * @param string $message
97 * @param string|int $level Psr\Log\LogEvent constant or Monlog level int
98 * @param array $context
99 * @return bool True if message should be sent to disk/network, false
102 public static function shouldEmit( $channel, $message, $level, $context ) {
103 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
105 if ( $channel === 'wfLogDBError' ) {
106 // wfLogDBError messages are emitted if a database log location is
108 $shouldEmit = (bool)$wgDBerrorLog;
110 } elseif ( $channel === 'wfErrorLog' ) {
111 // All messages on the wfErrorLog channel should be emitted.
114 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
115 $logConfig = $wgDebugLogGroups[$channel];
117 if ( is_array( $logConfig ) ) {
119 if ( isset( $logConfig['sample'] ) ) {
120 // Emit randomly with a 1 in 'sample' chance for each message.
121 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
124 if ( isset( $logConfig['level'] ) ) {
125 if ( is_string( $level ) ) {
126 $level = self
::$levelMapping[$level];
128 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
131 // Emit unless the config value is explictly false.
132 $shouldEmit = $logConfig !== false;
135 } elseif ( isset( $context['private'] ) && $context['private'] ) {
136 // Don't emit if the message didn't match previous checks based on
137 // the channel and the event is marked as private. This check
138 // discards messages sent via wfDebugLog() with dest == 'private'
139 // and no explicit wgDebugLogGroups configuration.
142 // Default return value is the same as the historic wfDebug
143 // method: emit if $wgDebugLogFile has been set.
144 $shouldEmit = $wgDebugLogFile != '';
154 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
155 * receive special fomatting to mimic the historic output of the functions
156 * of the same name. All other channel values are formatted based on the
157 * historic output of the `wfDebugLog()` global function.
159 * @param string $channel
160 * @param string $message
161 * @param array $context
164 public static function format( $channel, $message, $context ) {
165 global $wgDebugLogGroups;
167 if ( $channel === 'wfDebug' ) {
168 $text = self
::formatAsWfDebug( $channel, $message, $context );
170 } elseif ( $channel === 'wfLogDBError' ) {
171 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
173 } elseif ( $channel === 'wfErrorLog' ) {
174 $text = "{$message}\n";
176 } elseif ( $channel === 'profileoutput' ) {
177 // Legacy wfLogProfilingData formatitng
179 if ( isset( $context['forwarded_for'] )) {
180 $forward = " forwarded for {$context['forwarded_for']}";
182 if ( isset( $context['client_ip'] ) ) {
183 $forward .= " client IP {$context['client_ip']}";
185 if ( isset( $context['from'] ) ) {
186 $forward .= " from {$context['from']}";
189 $forward = "\t(proxied via {$context['proxy']}{$forward})";
191 if ( $context['anon'] ) {
194 if ( !isset( $context['url'] ) ) {
195 $context['url'] = 'n/a';
198 $log = sprintf( "%s\t%04.3f\t%s%s\n",
199 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
201 $text = self
::formatAsWfDebugLog(
202 $channel, $log . $context['output'], $context );
204 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
205 $text = self
::formatAsWfDebug(
206 $channel, "[{$channel}] {$message}", $context );
209 // Default formatting is wfDebugLog's historic style
210 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
213 return self
::interpolate( $text, $context );
218 * Format a message as `wfDebug()` would have formatted it.
220 * @param string $channel
221 * @param string $message
222 * @param array $context
225 protected static function formatAsWfDebug( $channel, $message, $context ) {
226 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
227 if ( isset( $context['seconds_elapsed'] ) ) {
228 // Prepend elapsed request time and real memory usage with two
230 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
232 if ( isset( $context['prefix'] ) ) {
233 $text = "{$context['prefix']}{$text}";
240 * Format a message as `wfLogDBError()` would have formatted it.
242 * @param string $channel
243 * @param string $message
244 * @param array $context
247 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
248 global $wgDBerrorLogTZ;
249 static $cachedTimezone = null;
251 if ( $wgDBerrorLogTZ && !$cachedTimezone ) {
252 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
255 // Workaround for https://bugs.php.net/bug.php?id=52063
256 // Can be removed when min PHP > 5.3.6
257 if ( $cachedTimezone === null ) {
258 $d = date_create( 'now' );
260 $d = date_create( 'now', $cachedTimezone );
262 $date = $d->format( 'D M j G:i:s T Y' );
264 $host = wfHostname();
267 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
273 * Format a message as `wfDebugLog() would have formatted it.
275 * @param string $channel
276 * @param string $message
277 * @param array $context
279 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
280 $time = wfTimestamp( TS_DB
);
282 $host = wfHostname();
283 $text = "{$time} {$host} {$wiki}: {$message}\n";
289 * Interpolate placeholders in logging message.
291 * @param string $message
292 * @param array $context
294 public static function interpolate( $message, array $context ) {
295 if ( strpos( $message, '{' ) !== false ) {
297 foreach ( $context as $key => $val ) {
298 $replace['{' . $key . '}'] = $val;
300 $message = strtr( $message, $replace );
307 * Select the appropriate log output destination for the given log event.
309 * If the event context contains 'destination'
311 * @param string $channel
312 * @param string $message
313 * @param array $context
316 protected static function destination( $channel, $message, $context ) {
317 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
319 // Default destination is the debug log file as historically used by
320 // the wfDebug function.
321 $destination = $wgDebugLogFile;
323 if ( isset( $context['destination'] ) ) {
324 // Use destination explicitly provided in context
325 $destination = $context['destination'];
327 } elseif ( $channel === 'wfDebug' ) {
328 $destination = $wgDebugLogFile;
330 } elseif ( $channel === 'wfLogDBError' ) {
331 $destination = $wgDBerrorLog;
333 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
334 $logConfig = $wgDebugLogGroups[$channel];
336 if ( is_array( $logConfig ) ) {
337 $destination = $logConfig['destination'];
339 $destination = strval( $logConfig );
348 * Log to a file without getting "file size exceeded" signals.
350 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
351 * lines to the specified port, prefixed by the specified prefix and a space.
353 * @param string $text
354 * @param string $file Filename
355 * @throws MWException
357 public static function emit( $text, $file ) {
358 if ( substr( $file, 0, 4 ) == 'udp:' ) {
359 $transport = UDPTransport
::newFromString( $file );
360 $transport->emit( $text );
362 wfSuppressWarnings();
363 $exists = file_exists( $file );
364 $size = $exists ?
filesize( $file ) : false;
366 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
368 file_put_contents( $file, $text, FILE_APPEND
);