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