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