4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
23 * PSR-3 logger that mimics the historic implementation of MediaWiki's
24 * wfErrorLog logging implementation.
26 * This logger is configured by the following global configuration variables:
28 * - `$wgDebugLogGroups`
32 * See documentation in DefaultSettings.php for detailed explanations of each
37 * @author Bryan Davis <bd808@wikimedia.org>
38 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
40 class MWLoggerLegacyLogger
extends \Psr\Log\AbstractLogger
{
43 * @var string $channel
49 * @param string $channel
51 public function __construct( $channel ) {
52 $this->channel
= $channel;
56 * Logs with an arbitrary level.
58 * @param string|int $level
59 * @param string $message
60 * @param array $context
62 public function log( $level, $message, array $context = array() ) {
63 if ( self
::shouldEmit( $this->channel
, $message, $context ) ) {
64 $text = self
::format( $this->channel
, $message, $context );
65 $destination = self
::destination( $this->channel
, $message, $context );
66 self
::emit( $text, $destination );
72 * Determine if the given message should be emitted or not.
74 * @param string $channel
75 * @param string $message
76 * @param array $context
77 * @return bool True if message should be sent to disk/network, false
80 public static function shouldEmit( $channel, $message, $context ) {
81 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
83 if ( $channel === 'wfLogDBError' ) {
84 // wfLogDBError messages are emitted if a database log location is
86 $shouldEmit = (bool)$wgDBerrorLog;
88 } elseif ( $channel === 'wfErrorLog' ) {
89 // All messages on the wfErrorLog channel should be emitted.
92 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
93 $logConfig = $wgDebugLogGroups[$channel];
95 if ( is_array( $logConfig ) && isset( $logConfig['sample'] ) ) {
96 // Emit randomly with a 1 in 'sample' chance for each message.
97 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
100 // Emit unless the config value is explictly false.
101 $shouldEmit = $logConfig !== false;
104 } elseif ( isset( $context['private'] ) && $context['private'] ) {
105 // Don't emit if the message didn't match previous checks based on
106 // the channel and the event is marked as private. This check
107 // discards messages sent via wfDebugLog() with dest == 'private'
108 // and no explicit wgDebugLogGroups configuration.
111 // Default return value is the the same as the historic wfDebug
112 // method: emit if $wgDebugLogFile has been set.
113 $shouldEmit = $wgDebugLogFile != '';
123 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
124 * receive special fomatting to mimic the historic output of the functions
125 * of the same name. All other channel values are formatted based on the
126 * historic output of the `wfDebugLog()` global function.
128 * @param string $channel
129 * @param string $message
130 * @param array $context
133 public static function format( $channel, $message, $context ) {
134 global $wgDebugLogGroups;
136 if ( $channel === 'wfDebug' ) {
137 $text = self
::formatAsWfDebug( $channel, $message, $context );
139 } elseif ( $channel === 'wfLogDBError' ) {
140 $text = self
::formatAsWfLogDBError( $channel, $message, $context );
142 } elseif ( $channel === 'wfErrorLog' ) {
143 $text = "{$message}\n";
145 } elseif ( $channel === 'profileoutput' ) {
146 // Legacy wfLogProfilingData formatitng
148 if ( isset( $context['forwarded_for'] )) {
149 $forward = " forwarded for {$context['forwarded_for']}";
151 if ( isset( $context['client_ip'] ) ) {
152 $forward .= " client IP {$context['client_ip']}";
154 if ( isset( $context['from'] ) ) {
155 $forward .= " from {$context['from']}";
158 $forward = "\t(proxied via {$context['proxy']}{$forward})";
160 if ( $context['anon'] ) {
163 if ( !isset( $context['url'] ) ) {
164 $context['url'] = 'n/a';
167 $log = sprintf( "%s\t%04.3f\t%s%s\n",
168 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
170 $text = self
::formatAsWfDebugLog(
171 $channel, $log . $context['output'], $context );
173 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
174 $text = self
::formatAsWfDebug(
175 $channel, "[{$channel}] {$message}", $context );
178 // Default formatting is wfDebugLog's historic style
179 $text = self
::formatAsWfDebugLog( $channel, $message, $context );
182 return self
::interpolate( $text, $context );
187 * Format a message as `wfDebug()` would have formatted it.
189 * @param string $channel
190 * @param string $message
191 * @param array $context
194 protected static function formatAsWfDebug( $channel, $message, $context ) {
195 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
196 if ( isset( $context['seconds_elapsed'] ) ) {
197 // Prepend elapsed request time and real memory usage with two
199 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
201 if ( isset( $context['prefix'] ) ) {
202 $text = "{$context['prefix']}{$text}";
209 * Format a message as `wfLogDBError()` would have formatted it.
211 * @param string $channel
212 * @param string $message
213 * @param array $context
216 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
217 global $wgDBerrorLogTZ;
218 static $cachedTimezone = null;
220 if ( $wgDBerrorLogTZ && !$cachedTimezone ) {
221 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
224 // Workaround for https://bugs.php.net/bug.php?id=52063
225 // Can be removed when min PHP > 5.3.6
226 if ( $cachedTimezone === null ) {
227 $d = date_create( 'now' );
229 $d = date_create( 'now', $cachedTimezone );
231 $date = $d->format( 'D M j G:i:s T Y' );
233 $host = wfHostname();
236 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
242 * Format a message as `wfDebugLog() would have formatted it.
244 * @param string $channel
245 * @param string $message
246 * @param array $context
248 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
249 $time = wfTimestamp( TS_DB
);
251 $host = wfHostname();
252 $text = "{$time} {$host} {$wiki}: {$message}\n";
258 * Interpolate placeholders in logging message.
260 * @param string $message
261 * @param array $context
263 public static function interpolate( $message, array $context ) {
264 if ( strpos( $message, '{' ) !== false ) {
266 foreach ( $context as $key => $val ) {
267 $replace['{' . $key . '}'] = $val;
269 $message = strtr( $message, $replace );
276 * Select the appropriate log output destination for the given log event.
278 * If the event context contains 'destination'
280 * @param string $channel
281 * @param string $message
282 * @param array $context
285 protected static function destination( $channel, $message, $context ) {
286 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
288 // Default destination is the debug log file as historically used by
289 // the wfDebug function.
290 $destination = $wgDebugLogFile;
292 if ( isset( $context['destination'] ) ) {
293 // Use destination explicitly provided in context
294 $destination = $context['destination'];
296 } elseif ( $channel === 'wfDebug' ) {
297 $destination = $wgDebugLogFile;
299 } elseif ( $channel === 'wfLogDBError' ) {
300 $destination = $wgDBerrorLog;
302 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
303 $logConfig = $wgDebugLogGroups[$channel];
305 if ( is_array( $logConfig ) ) {
306 $destination = $logConfig['destination'];
308 $destination = strval( $logConfig );
317 * Log to a file without getting "file size exceeded" signals.
319 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
320 * lines to the specified port, prefixed by the specified prefix and a space.
322 * @param string $text
323 * @param string $file Filename
324 * @throws MWException
326 public static function emit( $text, $file ) {
327 if ( substr( $file, 0, 4 ) == 'udp:' ) {
328 # Needs the sockets extension
329 if ( preg_match( '!^udp:(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
330 // IPv6 bracketed host
332 $port = intval( $m[2] );
333 $prefix = isset( $m[3] ) ?
$m[3] : false;
335 } elseif ( preg_match( '!^udp:(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
337 if ( !IP
::isIPv4( $host ) ) {
338 $host = gethostbyname( $host );
340 $port = intval( $m[2] );
341 $prefix = isset( $m[3] ) ?
$m[3] : false;
344 throw new MWException( __METHOD__
. ': Invalid UDP specification' );
347 // Clean it up for the multiplexer
348 if ( strval( $prefix ) !== '' ) {
349 $text = preg_replace( '/^/m', $prefix . ' ', $text );
352 if ( strlen( $text ) > 65506 ) {
353 $text = substr( $text, 0, 65506 );
356 if ( substr( $text, -1 ) != "\n" ) {
359 } elseif ( strlen( $text ) > 65507 ) {
360 $text = substr( $text, 0, 65507 );
363 $sock = socket_create( $domain, SOCK_DGRAM
, SOL_UDP
);
368 socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
369 socket_close( $sock );
371 wfSuppressWarnings();
372 $exists = file_exists( $file );
373 $size = $exists ?
filesize( $file ) : false;
375 ( $size !== false && $size +
strlen( $text ) < 0x7fffffff )
377 file_put_contents( $file, $text, FILE_APPEND
);