Merge "Use new WikiMap::getCurrentWikiDomain() for objectcache and profiler keyspace"
[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 former
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 * @copyright © 2014 Wikimedia Foundation and contributors
47 */
48 class LegacyLogger extends AbstractLogger {
49
50 /**
51 * @var string $channel
52 */
53 protected $channel;
54
55 /**
56 * Convert \Psr\Log\LogLevel constants into int for sane comparisons
57 * These are the same values that Monlog uses
58 *
59 * @var array $levelMapping
60 */
61 protected static $levelMapping = [
62 LogLevel::DEBUG => 100,
63 LogLevel::INFO => 200,
64 LogLevel::NOTICE => 250,
65 LogLevel::WARNING => 300,
66 LogLevel::ERROR => 400,
67 LogLevel::CRITICAL => 500,
68 LogLevel::ALERT => 550,
69 LogLevel::EMERGENCY => 600,
70 ];
71
72 /**
73 * @var array
74 */
75 protected static $dbChannels = [
76 'DBQuery' => true,
77 'DBConnection' => true
78 ];
79
80 /**
81 * @param string $channel
82 */
83 public function __construct( $channel ) {
84 $this->channel = $channel;
85 }
86
87 /**
88 * Logs with an arbitrary level.
89 *
90 * @param string|int $level
91 * @param string $message
92 * @param array $context
93 * @return null
94 */
95 public function log( $level, $message, array $context = [] ) {
96 global $wgDBerrorLog;
97
98 if ( is_string( $level ) ) {
99 $level = self::$levelMapping[$level];
100 }
101 if ( $this->channel === 'DBQuery'
102 && isset( $context['method'] )
103 && isset( $context['master'] )
104 && isset( $context['runtime'] )
105 ) {
106 // Also give the query information to the MWDebug tools
107 $enabled = MWDebug::query(
108 $message,
109 $context['method'],
110 $context['master'],
111 $context['runtime']
112 );
113 if ( $enabled ) {
114 // If we the toolbar was enabled, return early so that we don't
115 // also log the query to the main debug output.
116 return;
117 }
118 }
119
120 // If this is a DB-related error, and the site has $wgDBerrorLog
121 // configured, rewrite the channel as wfLogDBError instead.
122 // Likewise, if the site does not use $wgDBerrorLog, it should
123 // configurable like any other channel via $wgDebugLogGroups
124 // or $wgMWLoggerDefaultSpi.
125 if ( isset( self::$dbChannels[$this->channel] )
126 && $level >= self::$levelMapping[LogLevel::ERROR]
127 && $wgDBerrorLog
128 ) {
129 // Format and write DB errors to the legacy locations
130 $effectiveChannel = 'wfLogDBError';
131 } else {
132 $effectiveChannel = $this->channel;
133 }
134
135 if ( self::shouldEmit( $effectiveChannel, $message, $level, $context ) ) {
136 $text = self::format( $effectiveChannel, $message, $context );
137 $destination = self::destination( $effectiveChannel, $message, $context );
138 self::emit( $text, $destination );
139 }
140 if ( !isset( $context['private'] ) || !$context['private'] ) {
141 // Add to debug toolbar if not marked as "private"
142 MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
143 }
144 }
145
146 /**
147 * Determine if the given message should be emitted or not.
148 *
149 * @param string $channel
150 * @param string $message
151 * @param string|int $level \Psr\Log\LogEvent constant or Monolog level int
152 * @param array $context
153 * @return bool True if message should be sent to disk/network, false
154 * otherwise
155 */
156 public static function shouldEmit( $channel, $message, $level, $context ) {
157 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
158
159 if ( is_string( $level ) ) {
160 $level = self::$levelMapping[$level];
161 }
162
163 if ( $channel === 'wfLogDBError' ) {
164 // wfLogDBError messages are emitted if a database log location is
165 // specfied.
166 $shouldEmit = (bool)$wgDBerrorLog;
167
168 } elseif ( $channel === 'wfDebug' ) {
169 // wfDebug messages are emitted if a catch all logging file has
170 // been specified. Checked explicitly so that 'private' flagged
171 // messages are not discarded by unset $wgDebugLogGroups channel
172 // handling below.
173 $shouldEmit = $wgDebugLogFile != '';
174
175 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
176 $logConfig = $wgDebugLogGroups[$channel];
177
178 if ( is_array( $logConfig ) ) {
179 $shouldEmit = true;
180 if ( isset( $logConfig['sample'] ) ) {
181 // Emit randomly with a 1 in 'sample' chance for each message.
182 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
183 }
184
185 if ( isset( $logConfig['level'] ) ) {
186 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
187 }
188 } else {
189 // Emit unless the config value is explictly false.
190 $shouldEmit = $logConfig !== false;
191 }
192
193 } elseif ( isset( $context['private'] ) && $context['private'] ) {
194 // Don't emit if the message didn't match previous checks based on
195 // the channel and the event is marked as private. This check
196 // discards messages sent via wfDebugLog() with dest == 'private'
197 // and no explicit wgDebugLogGroups configuration.
198 $shouldEmit = false;
199 } else {
200 // Default return value is the same as the historic wfDebug
201 // method: emit if $wgDebugLogFile has been set.
202 $shouldEmit = $wgDebugLogFile != '';
203 }
204
205 return $shouldEmit;
206 }
207
208 /**
209 * Format a message.
210 *
211 * Messages to the 'wfDebug' and 'wfLogDBError' channels receive special formatting to mimic the
212 * historic output of the functions of the same name. All other channel values are formatted
213 * based on the historic output of the `wfDebugLog()` global function.
214 *
215 * @param string $channel
216 * @param string $message
217 * @param array $context
218 * @return string
219 */
220 public static function format( $channel, $message, $context ) {
221 global $wgDebugLogGroups, $wgLogExceptionBacktrace;
222
223 if ( $channel === 'wfDebug' ) {
224 $text = self::formatAsWfDebug( $channel, $message, $context );
225
226 } elseif ( $channel === 'wfLogDBError' ) {
227 $text = self::formatAsWfLogDBError( $channel, $message, $context );
228
229 } elseif ( $channel === 'profileoutput' ) {
230 // Legacy wfLogProfilingData formatitng
231 $forward = '';
232 if ( isset( $context['forwarded_for'] ) ) {
233 $forward = " forwarded for {$context['forwarded_for']}";
234 }
235 if ( isset( $context['client_ip'] ) ) {
236 $forward .= " client IP {$context['client_ip']}";
237 }
238 if ( isset( $context['from'] ) ) {
239 $forward .= " from {$context['from']}";
240 }
241 if ( $forward ) {
242 $forward = "\t(proxied via {$context['proxy']}{$forward})";
243 }
244 if ( $context['anon'] ) {
245 $forward .= ' anon';
246 }
247 if ( !isset( $context['url'] ) ) {
248 $context['url'] = 'n/a';
249 }
250
251 $log = sprintf( "%s\t%04.3f\t%s%s\n",
252 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
253
254 $text = self::formatAsWfDebugLog(
255 $channel, $log . $context['output'], $context );
256
257 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
258 $text = self::formatAsWfDebug(
259 $channel, "[{$channel}] {$message}", $context );
260
261 } else {
262 // Default formatting is wfDebugLog's historic style
263 $text = self::formatAsWfDebugLog( $channel, $message, $context );
264 }
265
266 // Append stacktrace of exception if available
267 if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
268 $e = $context['exception'];
269 $backtrace = false;
270
271 if ( $e instanceof Exception ) {
272 $backtrace = MWExceptionHandler::getRedactedTrace( $e );
273
274 } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
275 // Exception has already been unpacked as structured data
276 $backtrace = $e['trace'];
277 }
278
279 if ( $backtrace ) {
280 $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
281 "\n";
282 }
283 }
284
285 return self::interpolate( $text, $context );
286 }
287
288 /**
289 * Format a message as `wfDebug()` would have formatted it.
290 *
291 * @param string $channel
292 * @param string $message
293 * @param array $context
294 * @return string
295 */
296 protected static function formatAsWfDebug( $channel, $message, $context ) {
297 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
298 if ( isset( $context['seconds_elapsed'] ) ) {
299 // Prepend elapsed request time and real memory usage with two
300 // trailing spaces.
301 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
302 }
303 if ( isset( $context['prefix'] ) ) {
304 $text = "{$context['prefix']}{$text}";
305 }
306 return "{$text}\n";
307 }
308
309 /**
310 * Format a message as `wfLogDBError()` would have formatted it.
311 *
312 * @param string $channel
313 * @param string $message
314 * @param array $context
315 * @return string
316 */
317 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
318 global $wgDBerrorLogTZ;
319 static $cachedTimezone = null;
320
321 if ( !$cachedTimezone ) {
322 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
323 }
324
325 $d = date_create( 'now', $cachedTimezone );
326 $date = $d->format( 'D M j G:i:s T Y' );
327
328 $host = wfHostname();
329 $wiki = wfWikiID();
330
331 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
332 return $text;
333 }
334
335 /**
336 * Format a message as `wfDebugLog() would have formatted it.
337 *
338 * @param string $channel
339 * @param string $message
340 * @param array $context
341 * @return string
342 */
343 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
344 $time = wfTimestamp( TS_DB );
345 $wiki = wfWikiID();
346 $host = wfHostname();
347 $text = "{$time} {$host} {$wiki}: {$message}\n";
348 return $text;
349 }
350
351 /**
352 * Interpolate placeholders in logging message.
353 *
354 * @param string $message
355 * @param array $context
356 * @return string Interpolated message
357 */
358 public static function interpolate( $message, array $context ) {
359 if ( strpos( $message, '{' ) !== false ) {
360 $replace = [];
361 foreach ( $context as $key => $val ) {
362 $replace['{' . $key . '}'] = self::flatten( $val );
363 }
364 $message = strtr( $message, $replace );
365 }
366 return $message;
367 }
368
369 /**
370 * Convert a logging context element to a string suitable for
371 * interpolation.
372 *
373 * @param mixed $item
374 * @return string
375 */
376 protected static function flatten( $item ) {
377 if ( null === $item ) {
378 return '[Null]';
379 }
380
381 if ( is_bool( $item ) ) {
382 return $item ? 'true' : 'false';
383 }
384
385 if ( is_float( $item ) ) {
386 if ( is_infinite( $item ) ) {
387 return ( $item > 0 ? '' : '-' ) . 'INF';
388 }
389 if ( is_nan( $item ) ) {
390 return 'NaN';
391 }
392 return (string)$item;
393 }
394
395 if ( is_scalar( $item ) ) {
396 return (string)$item;
397 }
398
399 if ( is_array( $item ) ) {
400 return '[Array(' . count( $item ) . ')]';
401 }
402
403 if ( $item instanceof \DateTime ) {
404 return $item->format( 'c' );
405 }
406
407 if ( $item instanceof Exception ) {
408 return '[Exception ' . get_class( $item ) . '( ' .
409 $item->getFile() . ':' . $item->getLine() . ') ' .
410 $item->getMessage() . ']';
411 }
412
413 if ( is_object( $item ) ) {
414 if ( method_exists( $item, '__toString' ) ) {
415 return (string)$item;
416 }
417
418 return '[Object ' . get_class( $item ) . ']';
419 }
420
421 if ( is_resource( $item ) ) {
422 return '[Resource ' . get_resource_type( $item ) . ']';
423 }
424
425 return '[Unknown ' . gettype( $item ) . ']';
426 }
427
428 /**
429 * Select the appropriate log output destination for the given log event.
430 *
431 * If the event context contains 'destination'
432 *
433 * @param string $channel
434 * @param string $message
435 * @param array $context
436 * @return string
437 */
438 protected static function destination( $channel, $message, $context ) {
439 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
440
441 // Default destination is the debug log file as historically used by
442 // the wfDebug function.
443 $destination = $wgDebugLogFile;
444
445 if ( isset( $context['destination'] ) ) {
446 // Use destination explicitly provided in context
447 $destination = $context['destination'];
448
449 } elseif ( $channel === 'wfDebug' ) {
450 $destination = $wgDebugLogFile;
451
452 } elseif ( $channel === 'wfLogDBError' ) {
453 $destination = $wgDBerrorLog;
454
455 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
456 $logConfig = $wgDebugLogGroups[$channel];
457
458 if ( is_array( $logConfig ) ) {
459 $destination = $logConfig['destination'];
460 } else {
461 $destination = strval( $logConfig );
462 }
463 }
464
465 return $destination;
466 }
467
468 /**
469 * Log to a file without getting "file size exceeded" signals.
470 *
471 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
472 * lines to the specified port, prefixed by the specified prefix and a space.
473 *
474 * @param string $text
475 * @param string $file Filename
476 */
477 public static function emit( $text, $file ) {
478 if ( substr( $file, 0, 4 ) == 'udp:' ) {
479 $transport = UDPTransport::newFromString( $file );
480 $transport->emit( $text );
481 } else {
482 \Wikimedia\suppressWarnings();
483 $exists = file_exists( $file );
484 $size = $exists ? filesize( $file ) : false;
485 if ( !$exists ||
486 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
487 ) {
488 file_put_contents( $file, $text, FILE_APPEND );
489 }
490 \Wikimedia\restoreWarnings();
491 }
492 }
493
494 }