Exclude debug log events marked "private" from MWDebug
[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 if ( !isset( $context['private'] ) || !$context['private'] ) {
94 // Add to debug toolbar if not marked as "private"
95 MWDebug::debugMsg( $message, array( '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 // Workaround for https://bugs.php.net/bug.php?id=52063
286 // Can be removed when min PHP > 5.3.6
287 if ( $cachedTimezone === null ) {
288 $d = date_create( 'now' );
289 } else {
290 $d = date_create( 'now', $cachedTimezone );
291 }
292 $date = $d->format( 'D M j G:i:s T Y' );
293
294 $host = wfHostname();
295 $wiki = wfWikiID();
296
297 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
298 return $text;
299 }
300
301 /**
302 * Format a message as `wfDebugLog() would have formatted it.
303 *
304 * @param string $channel
305 * @param string $message
306 * @param array $context
307 */
308 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
309 $time = wfTimestamp( TS_DB );
310 $wiki = wfWikiID();
311 $host = wfHostname();
312 $text = "{$time} {$host} {$wiki}: {$message}\n";
313 return $text;
314 }
315
316 /**
317 * Interpolate placeholders in logging message.
318 *
319 * @param string $message
320 * @param array $context
321 * @return string Interpolated message
322 */
323 public static function interpolate( $message, array $context ) {
324 if ( strpos( $message, '{' ) !== false ) {
325 $replace = array();
326 foreach ( $context as $key => $val ) {
327 $replace['{' . $key . '}'] = self::flatten( $val );
328 }
329 $message = strtr( $message, $replace );
330 }
331 return $message;
332 }
333
334 /**
335 * Convert a logging context element to a string suitable for
336 * interpolation.
337 *
338 * @param mixed $item
339 * @return string
340 */
341 protected static function flatten( $item ) {
342 if ( null === $item ) {
343 return '[Null]';
344 }
345
346 if ( is_bool( $item ) ) {
347 return $item ? 'true' : 'false';
348 }
349
350 if ( is_float( $item ) ) {
351 if ( is_infinite( $item ) ) {
352 return ( $item > 0 ? '' : '-' ) . 'INF';
353 }
354 if ( is_nan( $item ) ) {
355 return 'NaN';
356 }
357 return $item;
358 }
359
360 if ( is_scalar( $item ) ) {
361 return (string)$item;
362 }
363
364 if ( is_array( $item ) ) {
365 return '[Array(' . count( $item ) . ')]';
366 }
367
368 if ( $item instanceof \DateTime ) {
369 return $item->format( 'c' );
370 }
371
372 if ( $item instanceof Exception ) {
373 return '[Exception ' . get_class( $item ) . '( ' .
374 $item->getFile() . ':' . $item->getLine() . ') ' .
375 $item->getMessage() . ']';
376 }
377
378 if ( is_object( $item ) ) {
379 if ( method_exists( $item, '__toString' ) ) {
380 return (string)$item;
381 }
382
383 return '[Object ' . get_class( $item ) . ']';
384 }
385
386 if ( is_resource( $item ) ) {
387 return '[Resource ' . get_resource_type( $item ) . ']';
388 }
389
390 return '[Unknown ' . gettype( $item ) . ']';
391 }
392
393 /**
394 * Select the appropriate log output destination for the given log event.
395 *
396 * If the event context contains 'destination'
397 *
398 * @param string $channel
399 * @param string $message
400 * @param array $context
401 * @return string
402 */
403 protected static function destination( $channel, $message, $context ) {
404 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
405
406 // Default destination is the debug log file as historically used by
407 // the wfDebug function.
408 $destination = $wgDebugLogFile;
409
410 if ( isset( $context['destination'] ) ) {
411 // Use destination explicitly provided in context
412 $destination = $context['destination'];
413
414 } elseif ( $channel === 'wfDebug' ) {
415 $destination = $wgDebugLogFile;
416
417 } elseif ( $channel === 'wfLogDBError' ) {
418 $destination = $wgDBerrorLog;
419
420 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
421 $logConfig = $wgDebugLogGroups[$channel];
422
423 if ( is_array( $logConfig ) ) {
424 $destination = $logConfig['destination'];
425 } else {
426 $destination = strval( $logConfig );
427 }
428 }
429
430 return $destination;
431 }
432
433 /**
434 * Log to a file without getting "file size exceeded" signals.
435 *
436 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
437 * lines to the specified port, prefixed by the specified prefix and a space.
438 *
439 * @param string $text
440 * @param string $file Filename
441 * @throws MWException
442 */
443 public static function emit( $text, $file ) {
444 if ( substr( $file, 0, 4 ) == 'udp:' ) {
445 $transport = UDPTransport::newFromString( $file );
446 $transport->emit( $text );
447 } else {
448 \MediaWiki\suppressWarnings();
449 $exists = file_exists( $file );
450 $size = $exists ? filesize( $file ) : false;
451 if ( !$exists ||
452 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
453 ) {
454 file_put_contents( $file, $text, FILE_APPEND );
455 }
456 \MediaWiki\restoreWarnings();
457 }
458 }
459
460 }