Merge "Support fragments in getUrl() of mw.Title"
[lhc/web/wiklou.git] / includes / debug / logger / LegacyLogger.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Logger;
22
23 use DateTimeZone;
24 use Exception;
25 use MWDebug;
26 use MWExceptionHandler;
27 use Psr\Log\AbstractLogger;
28 use Psr\Log\LogLevel;
29 use UDPTransport;
30
31 /**
32 * PSR-3 logger that mimics the historic implementation of MediaWiki's
33 * wfErrorLog logging implementation.
34 *
35 * This logger is configured by the following global configuration variables:
36 * - `$wgDebugLogFile`
37 * - `$wgDebugLogGroups`
38 * - `$wgDBerrorLog`
39 * - `$wgDBerrorLogTZ`
40 *
41 * See documentation in DefaultSettings.php for detailed explanations of each
42 * variable.
43 *
44 * @see \MediaWiki\Logger\LoggerFactory
45 * @since 1.25
46 * @author Bryan Davis <bd808@wikimedia.org>
47 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
48 */
49 class LegacyLogger extends AbstractLogger {
50
51 /**
52 * @var string $channel
53 */
54 protected $channel;
55
56 /**
57 * Convert \Psr\Log\LogLevel constants into int for sane comparisons
58 * These are the same values that Monlog uses
59 *
60 * @var array $levelMapping
61 */
62 protected static $levelMapping = array(
63 LogLevel::DEBUG => 100,
64 LogLevel::INFO => 200,
65 LogLevel::NOTICE => 250,
66 LogLevel::WARNING => 300,
67 LogLevel::ERROR => 400,
68 LogLevel::CRITICAL => 500,
69 LogLevel::ALERT => 550,
70 LogLevel::EMERGENCY => 600,
71 );
72
73 /**
74 * @param string $channel
75 */
76 public function __construct( $channel ) {
77 $this->channel = $channel;
78 }
79
80 /**
81 * Logs with an arbitrary level.
82 *
83 * @param string|int $level
84 * @param string $message
85 * @param array $context
86 */
87 public function log( $level, $message, array $context = array() ) {
88 if ( self::shouldEmit( $this->channel, $message, $level, $context ) ) {
89 $text = self::format( $this->channel, $message, $context );
90 $destination = self::destination( $this->channel, $message, $context );
91 self::emit( $text, $destination );
92 }
93 // Add to debug toolbar
94 MWDebug::debugMsg( $message, array( 'channel' => $this->channel ) + $context );
95 }
96
97 /**
98 * Determine if the given message should be emitted or not.
99 *
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
105 * otherwise
106 */
107 public static function shouldEmit( $channel, $message, $level, $context ) {
108 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
109
110 if ( $channel === 'wfLogDBError' ) {
111 // wfLogDBError messages are emitted if a database log location is
112 // specfied.
113 $shouldEmit = (bool)$wgDBerrorLog;
114
115 } elseif ( $channel === 'wfErrorLog' ) {
116 // All messages on the wfErrorLog channel should be emitted.
117 $shouldEmit = true;
118
119 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
120 $logConfig = $wgDebugLogGroups[$channel];
121
122 if ( is_array( $logConfig ) ) {
123 $shouldEmit = true;
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;
127 }
128
129 if ( isset( $logConfig['level'] ) ) {
130 if ( is_string( $level ) ) {
131 $level = self::$levelMapping[$level];
132 }
133 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
134 }
135 } else {
136 // Emit unless the config value is explictly false.
137 $shouldEmit = $logConfig !== false;
138 }
139
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.
145 $shouldEmit = false;
146 } else {
147 // Default return value is the same as the historic wfDebug
148 // method: emit if $wgDebugLogFile has been set.
149 $shouldEmit = $wgDebugLogFile != '';
150 }
151
152 return $shouldEmit;
153 }
154
155 /**
156 * Format a message.
157 *
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.
162 *
163 * @param string $channel
164 * @param string $message
165 * @param array $context
166 * @return string
167 */
168 public static function format( $channel, $message, $context ) {
169 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
170
171 if ( $channel === 'wfDebug' ) {
172 $text = self::formatAsWfDebug( $channel, $message, $context );
173
174 } elseif ( $channel === 'wfLogDBError' ) {
175 $text = self::formatAsWfLogDBError( $channel, $message, $context );
176
177 } elseif ( $channel === 'wfErrorLog' ) {
178 $text = "{$message}\n";
179
180 } elseif ( $channel === 'profileoutput' ) {
181 // Legacy wfLogProfilingData formatitng
182 $forward = '';
183 if ( isset( $context['forwarded_for'] ) ) {
184 $forward = " forwarded for {$context['forwarded_for']}";
185 }
186 if ( isset( $context['client_ip'] ) ) {
187 $forward .= " client IP {$context['client_ip']}";
188 }
189 if ( isset( $context['from'] ) ) {
190 $forward .= " from {$context['from']}";
191 }
192 if ( $forward ) {
193 $forward = "\t(proxied via {$context['proxy']}{$forward})";
194 }
195 if ( $context['anon'] ) {
196 $forward .= ' anon';
197 }
198 if ( !isset( $context['url'] ) ) {
199 $context['url'] = 'n/a';
200 }
201
202 $log = sprintf( "%s\t%04.3f\t%s%s\n",
203 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
204
205 $text = self::formatAsWfDebugLog(
206 $channel, $log . $context['output'], $context );
207
208 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
209 $text = self::formatAsWfDebug(
210 $channel, "[{$channel}] {$message}", $context );
211
212 } else {
213 // Default formatting is wfDebugLog's historic style
214 $text = self::formatAsWfDebugLog( $channel, $message, $context );
215 }
216
217 // Append stacktrace of exception if available
218 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
219 $e = $context['exception'];
220 $backtrace = false;
221
222 if ( $e instanceof Exception ) {
223 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
224
225 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
226 // Exception has already been unpacked as structured data
227 $backtrace = $e['trace'];
228 }
229
230 if ( $backtrace ) {
231 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
232 "\n";
233 }
234 }
235
236 return self::interpolate( $text, $context );
237 }
238
239 /**
240 * Format a message as `wfDebug()` would have formatted it.
241 *
242 * @param string $channel
243 * @param string $message
244 * @param array $context
245 * @return string
246 */
247 protected static function formatAsWfDebug( $channel, $message, $context ) {
248 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
249 if ( isset( $context['seconds_elapsed'] ) ) {
250 // Prepend elapsed request time and real memory usage with two
251 // trailing spaces.
252 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
253 }
254 if ( isset( $context['prefix'] ) ) {
255 $text = "{$context['prefix']}{$text}";
256 }
257 return "{$text}\n";
258 }
259
260 /**
261 * Format a message as `wfLogDBError()` would have formatted it.
262 *
263 * @param string $channel
264 * @param string $message
265 * @param array $context
266 * @return string
267 */
268 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
269 global $wgDBerrorLogTZ;
270 static $cachedTimezone = null;
271
272 if ( !$cachedTimezone ) {
273 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
274 }
275
276 // Workaround for https://bugs.php.net/bug.php?id=52063
277 // Can be removed when min PHP > 5.3.6
278 if ( $cachedTimezone === null ) {
279 $d = date_create( 'now' );
280 } else {
281 $d = date_create( 'now', $cachedTimezone );
282 }
283 $date = $d->format( 'D M j G:i:s T Y' );
284
285 $host = wfHostname();
286 $wiki = wfWikiID();
287
288 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
289 return $text;
290 }
291
292 /**
293 * Format a message as `wfDebugLog() would have formatted it.
294 *
295 * @param string $channel
296 * @param string $message
297 * @param array $context
298 */
299 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
300 $time = wfTimestamp( TS_DB );
301 $wiki = wfWikiID();
302 $host = wfHostname();
303 $text = "{$time} {$host} {$wiki}: {$message}\n";
304 return $text;
305 }
306
307 /**
308 * Interpolate placeholders in logging message.
309 *
310 * @param string $message
311 * @param array $context
312 * @return string Interpolated message
313 */
314 public static function interpolate( $message, array $context ) {
315 if ( strpos( $message, '{' ) !== false ) {
316 $replace = array();
317 foreach ( $context as $key => $val ) {
318 $replace['{' . $key . '}'] = self::flatten( $val );
319 }
320 $message = strtr( $message, $replace );
321 }
322 return $message;
323 }
324
325 /**
326 * Convert a logging context element to a string suitable for
327 * interpolation.
328 *
329 * @param mixed $item
330 * @return string
331 */
332 protected static function flatten( $item ) {
333 if ( null === $item ) {
334 return '[Null]';
335 }
336
337 if ( is_bool( $item ) ) {
338 return $item ? 'true' : 'false';
339 }
340
341 if ( is_float( $item ) ) {
342 if ( is_infinite( $item ) ) {
343 return ( $item > 0 ? '' : '-' ) . 'INF';
344 }
345 if ( is_nan( $item ) ) {
346 return 'NaN';
347 }
348 return $item;
349 }
350
351 if ( is_scalar( $item ) ) {
352 return (string)$item;
353 }
354
355 if ( is_array( $item ) ) {
356 return '[Array(' . count( $item ) . ')]';
357 }
358
359 if ( $item instanceof \DateTime ) {
360 return $item->format( 'c' );
361 }
362
363 if ( $item instanceof Exception ) {
364 return '[Exception ' . get_class( $item ) . '( ' .
365 $item->getFile() . ':' . $item->getLine() . ') ' .
366 $item->getMessage() . ']';
367 }
368
369 if ( is_object( $item ) ) {
370 if ( method_exists( $item, '__toString' ) ) {
371 return (string)$item;
372 }
373
374 return '[Object ' . get_class( $item ) . ']';
375 }
376
377 if ( is_resource( $item ) ) {
378 return '[Resource ' . get_resource_type( $item ) . ']';
379 }
380
381 return '[Unknown ' . gettype( $item ) . ']';
382 }
383
384 /**
385 * Select the appropriate log output destination for the given log event.
386 *
387 * If the event context contains 'destination'
388 *
389 * @param string $channel
390 * @param string $message
391 * @param array $context
392 * @return string
393 */
394 protected static function destination( $channel, $message, $context ) {
395 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
396
397 // Default destination is the debug log file as historically used by
398 // the wfDebug function.
399 $destination = $wgDebugLogFile;
400
401 if ( isset( $context['destination'] ) ) {
402 // Use destination explicitly provided in context
403 $destination = $context['destination'];
404
405 } elseif ( $channel === 'wfDebug' ) {
406 $destination = $wgDebugLogFile;
407
408 } elseif ( $channel === 'wfLogDBError' ) {
409 $destination = $wgDBerrorLog;
410
411 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
412 $logConfig = $wgDebugLogGroups[$channel];
413
414 if ( is_array( $logConfig ) ) {
415 $destination = $logConfig['destination'];
416 } else {
417 $destination = strval( $logConfig );
418 }
419 }
420
421 return $destination;
422 }
423
424 /**
425 * Log to a file without getting "file size exceeded" signals.
426 *
427 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
428 * lines to the specified port, prefixed by the specified prefix and a space.
429 *
430 * @param string $text
431 * @param string $file Filename
432 * @throws MWException
433 */
434 public static function emit( $text, $file ) {
435 if ( substr( $file, 0, 4 ) == 'udp:' ) {
436 $transport = UDPTransport::newFromString( $file );
437 $transport->emit( $text );
438 } else {
439 \MediaWiki\suppressWarnings();
440 $exists = file_exists( $file );
441 $size = $exists ? filesize( $file ) : false;
442 if ( !$exists ||
443 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
444 ) {
445 file_put_contents( $file, $text, FILE_APPEND );
446 }
447 \MediaWiki\restoreWarnings();
448 }
449 }
450
451 }