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