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