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 );
91 * Determine if the given message should be emitted or not.
93 * @param string $channel
94 * @param string $message
95 * @param string|int $level Psr\Log\LogEvent constant or Monlog level int
96 * @param array $context
97 * @return bool True if message should be sent to disk/network, false
100 public static function shouldEmit( $channel, $message, $level, $context ) {
101 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
103 if ( $channel === 'wfLogDBError' ) {
104 // wfLogDBError messages are emitted if a database log location is
106 $shouldEmit = (bool)$wgDBerrorLog;
108 } elseif ( $channel === 'wfErrorLog' ) {
109 // All messages on the wfErrorLog channel should be emitted.
112 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
113 $logConfig = $wgDebugLogGroups[$channel];
115 if ( is_array( $logConfig ) ) {
117 if ( isset( $logConfig['sample'] ) ) {
118 // Emit randomly with a 1 in 'sample' chance for each message.
119 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
122 if ( isset( $logConfig['level'] ) ) {
123 if ( is_string( $level ) ) {
124 $level = self
::$levelMapping[$level];
126 $shouldEmit = $level >= self
::$levelMapping[$logConfig['level']];
129 // Emit unless the config value is explictly false.
130 $shouldEmit = $logConfig !== false;
133 } elseif ( isset( $context['private'] ) && $context['private'] ) {
134 // Don't emit if the message didn't match previous checks based on
135 // the channel and the event is marked as private. This check
136 // discards messages sent via wfDebugLog() with dest == 'private'
137 // and no explicit wgDebugLogGroups configuration.
140 // Default return value is the same as the historic wfDebug
141 // method: emit if $wgDebugLogFile has been set.
142 $shouldEmit = $wgDebugLogFile != '';
152 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
153 * receive special fomatting to mimic the historic output of the functions
154 * of the same name. All other channel values are formatted based on the
155 * historic output of the `wfDebugLog()` global function.
157 * @param string $channel
158 * @param string $message
159 * @param array $context
162 public static function format( $channel, $message, $context ) {
163 global $wgDebugLogGroups;
165 if ( $channel === 'wfDebug' ) {
166 $text = self
::formatAsWfDebug( $channel, $message, $context );
168 } elseif ( $channel === 'wfLogDBError' ) {
169 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
171 } elseif ( $channel === 'wfErrorLog' ) {
172 $text = "{$message}\n";
174 } elseif ( $channel === 'profileoutput' ) {
175 // Legacy wfLogProfilingData formatitng
177 if ( isset( $context['forwarded_for'] )) {
178 $forward = " forwarded for {$context['forwarded_for']}";
180 if ( isset( $context['client_ip'] ) ) {
181 $forward .= " client IP {$context['client_ip']}";
183 if ( isset( $context['from'] ) ) {
184 $forward .= " from {$context['from']}";
187 $forward = "\t(proxied via {$context['proxy']}{$forward})";
189 if ( $context['anon'] ) {
192 if ( !isset( $context['url'] ) ) {
193 $context['url'] = 'n/a';
196 $log = sprintf( "%s\t%04.3f\t%s%s\n",
197 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
199 $text = self
::formatAsWfDebugLog(
200 $channel, $log . $context['output'], $context );
202 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
203 $text = self
::formatAsWfDebug(
204 $channel, "[{$channel}] {$message}", $context );
207 // Default formatting is wfDebugLog's historic style
208 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
211 return self
::interpolate( $text, $context );
216 * Format a message as `wfDebug()` would have formatted it.
218 * @param string $channel
219 * @param string $message
220 * @param array $context
223 protected static function formatAsWfDebug( $channel, $message, $context ) {
224 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
225 if ( isset( $context['seconds_elapsed'] ) ) {
226 // Prepend elapsed request time and real memory usage with two
228 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
230 if ( isset( $context['prefix'] ) ) {
231 $text = "{$context['prefix']}{$text}";
238 * Format a message as `wfLogDBError()` would have formatted it.
240 * @param string $channel
241 * @param string $message
242 * @param array $context
245 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
246 global $wgDBerrorLogTZ;
247 static $cachedTimezone = null;
249 if ( $wgDBerrorLogTZ && !$cachedTimezone ) {
250 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
253 // Workaround for https://bugs.php.net/bug.php?id=52063
254 // Can be removed when min PHP > 5.3.6
255 if ( $cachedTimezone === null ) {
256 $d = date_create( 'now' );
258 $d = date_create( 'now', $cachedTimezone );
260 $date = $d->format( 'D M j G:i:s T Y' );
262 $host = wfHostname();
265 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
271 * Format a message as `wfDebugLog() would have formatted it.
273 * @param string $channel
274 * @param string $message
275 * @param array $context
277 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
278 $time = wfTimestamp( TS_DB
);
280 $host = wfHostname();
281 $text = "{$time} {$host} {$wiki}: {$message}\n";
287 * Interpolate placeholders in logging message.
289 * @param string $message
290 * @param array $context
292 public static function interpolate( $message, array $context ) {
293 if ( strpos( $message, '{' ) !== false ) {
295 foreach ( $context as $key => $val ) {
296 $replace['{' . $key . '}'] = $val;
298 $message = strtr( $message, $replace );
305 * Select the appropriate log output destination for the given log event.
307 * If the event context contains 'destination'
309 * @param string $channel
310 * @param string $message
311 * @param array $context
314 protected static function destination( $channel, $message, $context ) {
315 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
317 // Default destination is the debug log file as historically used by
318 // the wfDebug function.
319 $destination = $wgDebugLogFile;
321 if ( isset( $context['destination'] ) ) {
322 // Use destination explicitly provided in context
323 $destination = $context['destination'];
325 } elseif ( $channel === 'wfDebug' ) {
326 $destination = $wgDebugLogFile;
328 } elseif ( $channel === 'wfLogDBError' ) {
329 $destination = $wgDBerrorLog;
331 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
332 $logConfig = $wgDebugLogGroups[$channel];
334 if ( is_array( $logConfig ) ) {
335 $destination = $logConfig['destination'];
337 $destination = strval( $logConfig );
346 * Log to a file without getting "file size exceeded" signals.
348 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
349 * lines to the specified port, prefixed by the specified prefix and a space.
351 * @param string $text
352 * @param string $file Filename
353 * @throws MWException
355 public static function emit( $text, $file ) {
356 if ( substr( $file, 0, 4 ) == 'udp:' ) {
357 $transport = UDPTransport
::newFromString( $file );
358 $transport->emit( $text );
360 wfSuppressWarnings();
361 $exists = file_exists( $file );
362 $size = $exists ?
filesize( $file ) : false;
364 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
366 file_put_contents( $file, $text, FILE_APPEND
);