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
;
24 use Psr\Log\AbstractLogger
;
29 * PSR-3 logger that mimics the historic implementation of MediaWiki's
30 * wfErrorLog logging implementation.
32 * This logger is configured by the following global configuration variables:
34 * - `$wgDebugLogGroups`
38 * See documentation in DefaultSettings.php for detailed explanations of each
41 * @see \MediaWiki\Logger\LoggerFactory
43 * @author Bryan Davis <bd808@wikimedia.org>
44 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
46 class LegacyLogger
extends AbstractLogger
{
49 * @var string $channel
54 * Convert Psr\Log\LogLevel constants into int for sane comparisons
55 * These are the same values that Monlog uses
59 protected static $levelMapping = array(
60 LogLevel
::DEBUG
=> 100,
61 LogLevel
::INFO
=> 200,
62 LogLevel
::NOTICE
=> 250,
63 LogLevel
::WARNING
=> 300,
64 LogLevel
::ERROR
=> 400,
65 LogLevel
::CRITICAL
=> 500,
66 LogLevel
::ALERT
=> 550,
67 LogLevel
::EMERGENCY
=> 600,
72 * @param string $channel
74 public function __construct( $channel ) {
75 $this->channel
= $channel;
79 * Logs with an arbitrary level.
81 * @param string|int $level
82 * @param string $message
83 * @param array $context
85 public function log( $level, $message, array $context = array() ) {
86 if ( self
::shouldEmit( $this->channel
, $message, $level, $context ) ) {
87 $text = self
::format( $this->channel
, $message, $context );
88 $destination = self
::destination( $this->channel
, $message, $context );
89 self
::emit( $text, $destination );
91 // Add to debug toolbar
92 MWDebug
::debugMsg( $message, array( 'channel' => $this->channel
) +
$context );
97 * Determine if the given message should be emitted or not.
99 * @param string $channel
100 * @param string $message
101 * @param string|int $level Psr\Log\LogEvent constant or Monlog level int
102 * @param array $context
103 * @return bool True if message should be sent to disk/network, false
106 public static function shouldEmit( $channel, $message, $level, $context ) {
107 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
109 if ( $channel === 'wfLogDBError' ) {
110 // wfLogDBError messages are emitted if a database log location is
112 $shouldEmit = (bool)$wgDBerrorLog;
114 } elseif ( $channel === 'wfErrorLog' ) {
115 // All messages on the wfErrorLog channel should be emitted.
118 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
119 $logConfig = $wgDebugLogGroups[$channel];
121 if ( is_array( $logConfig ) ) {
123 if ( isset( $logConfig['sample'] ) ) {
124 // Emit randomly with a 1 in 'sample' chance for each message.
125 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
128 if ( isset( $logConfig['level'] ) ) {
129 if ( is_string( $level ) ) {
130 $level = self
::$levelMapping[$level];
132 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
135 // Emit unless the config value is explictly false.
136 $shouldEmit = $logConfig !== false;
139 } elseif ( isset( $context['private'] ) && $context['private'] ) {
140 // Don't emit if the message didn't match previous checks based on
141 // the channel and the event is marked as private. This check
142 // discards messages sent via wfDebugLog() with dest == 'private'
143 // and no explicit wgDebugLogGroups configuration.
146 // Default return value is the same as the historic wfDebug
147 // method: emit if $wgDebugLogFile has been set.
148 $shouldEmit = $wgDebugLogFile != '';
158 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
159 * receive special fomatting to mimic the historic output of the functions
160 * of the same name. All other channel values are formatted based on the
161 * historic output of the `wfDebugLog()` global function.
163 * @param string $channel
164 * @param string $message
165 * @param array $context
168 public static function format( $channel, $message, $context ) {
169 global $wgDebugLogGroups;
171 if ( $channel === 'wfDebug' ) {
172 $text = self
::formatAsWfDebug( $channel, $message, $context );
174 } elseif ( $channel === 'wfLogDBError' ) {
175 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
177 } elseif ( $channel === 'wfErrorLog' ) {
178 $text = "{$message}\n";
180 } elseif ( $channel === 'profileoutput' ) {
181 // Legacy wfLogProfilingData formatitng
183 if ( isset( $context['forwarded_for'] )) {
184 $forward = " forwarded for {$context['forwarded_for']}";
186 if ( isset( $context['client_ip'] ) ) {
187 $forward .= " client IP {$context['client_ip']}";
189 if ( isset( $context['from'] ) ) {
190 $forward .= " from {$context['from']}";
193 $forward = "\t(proxied via {$context['proxy']}{$forward})";
195 if ( $context['anon'] ) {
198 if ( !isset( $context['url'] ) ) {
199 $context['url'] = 'n/a';
202 $log = sprintf( "%s\t%04.3f\t%s%s\n",
203 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
205 $text = self
::formatAsWfDebugLog(
206 $channel, $log . $context['output'], $context );
208 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
209 $text = self
::formatAsWfDebug(
210 $channel, "[{$channel}] {$message}", $context );
213 // Default formatting is wfDebugLog's historic style
214 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
217 return self
::interpolate( $text, $context );
222 * Format a message as `wfDebug()` would have formatted it.
224 * @param string $channel
225 * @param string $message
226 * @param array $context
229 protected static function formatAsWfDebug( $channel, $message, $context ) {
230 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
231 if ( isset( $context['seconds_elapsed'] ) ) {
232 // Prepend elapsed request time and real memory usage with two
234 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
236 if ( isset( $context['prefix'] ) ) {
237 $text = "{$context['prefix']}{$text}";
244 * Format a message as `wfLogDBError()` would have formatted it.
246 * @param string $channel
247 * @param string $message
248 * @param array $context
251 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
252 global $wgDBerrorLogTZ;
253 static $cachedTimezone = null;
255 if ( $wgDBerrorLogTZ && !$cachedTimezone ) {
256 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
259 // Workaround for https://bugs.php.net/bug.php?id=52063
260 // Can be removed when min PHP > 5.3.6
261 if ( $cachedTimezone === null ) {
262 $d = date_create( 'now' );
264 $d = date_create( 'now', $cachedTimezone );
266 $date = $d->format( 'D M j G:i:s T Y' );
268 $host = wfHostname();
271 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
277 * Format a message as `wfDebugLog() would have formatted it.
279 * @param string $channel
280 * @param string $message
281 * @param array $context
283 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
284 $time = wfTimestamp( TS_DB
);
286 $host = wfHostname();
287 $text = "{$time} {$host} {$wiki}: {$message}\n";
293 * Interpolate placeholders in logging message.
295 * @param string $message
296 * @param array $context
297 * @return string Interpolated message
299 public static function interpolate( $message, array $context ) {
300 if ( strpos( $message, '{' ) !== false ) {
302 foreach ( $context as $key => $val ) {
303 $replace['{' . $key . '}'] = $val;
305 $message = strtr( $message, $replace );
312 * Select the appropriate log output destination for the given log event.
314 * If the event context contains 'destination'
316 * @param string $channel
317 * @param string $message
318 * @param array $context
321 protected static function destination( $channel, $message, $context ) {
322 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
324 // Default destination is the debug log file as historically used by
325 // the wfDebug function.
326 $destination = $wgDebugLogFile;
328 if ( isset( $context['destination'] ) ) {
329 // Use destination explicitly provided in context
330 $destination = $context['destination'];
332 } elseif ( $channel === 'wfDebug' ) {
333 $destination = $wgDebugLogFile;
335 } elseif ( $channel === 'wfLogDBError' ) {
336 $destination = $wgDBerrorLog;
338 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
339 $logConfig = $wgDebugLogGroups[$channel];
341 if ( is_array( $logConfig ) ) {
342 $destination = $logConfig['destination'];
344 $destination = strval( $logConfig );
353 * Log to a file without getting "file size exceeded" signals.
355 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
356 * lines to the specified port, prefixed by the specified prefix and a space.
358 * @param string $text
359 * @param string $file Filename
360 * @throws MWException
362 public static function emit( $text, $file ) {
363 if ( substr( $file, 0, 4 ) == 'udp:' ) {
364 $transport = UDPTransport
::newFromString( $file );
365 $transport->emit( $text );
367 wfSuppressWarnings();
368 $exists = file_exists( $file );
369 $size = $exists ?
filesize( $file ) : false;
371 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
373 file_put_contents( $file, $text, FILE_APPEND
);