summaryrefslogtreecommitdiff
path: root/includes/debug/logger/LegacyLogger.php
blob: 0f4c6484066a6e124c0f3a9571fb4425587ac31b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
<?php
/**
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @file
 */

namespace MediaWiki\Logger;

use DateTimeZone;
use Exception;
use MWDebug;
use MWExceptionHandler;
use Psr\Log\AbstractLogger;
use Psr\Log\LogLevel;
use UDPTransport;

/**
 * PSR-3 logger that mimics the historic implementation of MediaWiki's
 * wfErrorLog logging implementation.
 *
 * This logger is configured by the following global configuration variables:
 * - `$wgDebugLogFile`
 * - `$wgDebugLogGroups`
 * - `$wgDBerrorLog`
 * - `$wgDBerrorLogTZ`
 *
 * See documentation in DefaultSettings.php for detailed explanations of each
 * variable.
 *
 * @see \\MediaWiki\\Logger\\LoggerFactory
 * @since 1.25
 * @author Bryan Davis <bd808@wikimedia.org>
 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
 */
class LegacyLogger extends AbstractLogger {

	/**
	 * @var string $channel
	 */
	protected $channel;

	/**
	 * Convert Psr\\Log\\LogLevel constants into int for sane comparisons
	 * These are the same values that Monlog uses
	 *
	 * @var array $levelMapping
	 */
	protected static $levelMapping = array(
		LogLevel::DEBUG => 100,
		LogLevel::INFO => 200,
		LogLevel::NOTICE => 250,
		LogLevel::WARNING => 300,
		LogLevel::ERROR => 400,
		LogLevel::CRITICAL => 500,
		LogLevel::ALERT => 550,
		LogLevel::EMERGENCY => 600,
	);


	/**
	 * @param string $channel
	 */
	public function __construct( $channel ) {
		$this->channel = $channel;
	}

	/**
	 * Logs with an arbitrary level.
	 *
	 * @param string|int $level
	 * @param string $message
	 * @param array $context
	 */
	public function log( $level, $message, array $context = array() ) {
		if ( self::shouldEmit( $this->channel, $message, $level, $context ) ) {
			$text = self::format( $this->channel, $message, $context );
			$destination = self::destination( $this->channel, $message, $context );
			self::emit( $text, $destination );
		}
		// Add to debug toolbar
		MWDebug::debugMsg( $message, array( 'channel' => $this->channel ) + $context );
	}


	/**
	 * Determine if the given message should be emitted or not.
	 *
	 * @param string $channel
	 * @param string $message
	 * @param string|int $level Psr\\Log\\LogEvent constant or Monlog level int
	 * @param array $context
	 * @return bool True if message should be sent to disk/network, false
	 * otherwise
	 */
	public static function shouldEmit( $channel, $message, $level, $context ) {
		global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;

		if ( $channel === 'wfLogDBError' ) {
			// wfLogDBError messages are emitted if a database log location is
			// specfied.
			$shouldEmit = (bool)$wgDBerrorLog;

		} elseif ( $channel === 'wfErrorLog' ) {
			// All messages on the wfErrorLog channel should be emitted.
			$shouldEmit = true;

		} elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
			$logConfig = $wgDebugLogGroups[$channel];

			if ( is_array( $logConfig ) ) {
				$shouldEmit = true;
				if ( isset( $logConfig['sample'] ) ) {
					// Emit randomly with a 1 in 'sample' chance for each message.
					$shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
				}

				if ( isset( $logConfig['level'] ) ) {
					if ( is_string( $level ) ) {
						$level = self::$levelMapping[$level];
					}
					$shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
				}
			} else {
				// Emit unless the config value is explictly false.
				$shouldEmit = $logConfig !== false;
			}

		} elseif ( isset( $context['private'] ) && $context['private'] ) {
			// Don't emit if the message didn't match previous checks based on
			// the channel and the event is marked as private. This check
			// discards messages sent via wfDebugLog() with dest == 'private'
			// and no explicit wgDebugLogGroups configuration.
			$shouldEmit = false;
		} else {
			// Default return value is the same as the historic wfDebug
			// method: emit if $wgDebugLogFile has been set.
			$shouldEmit = $wgDebugLogFile != '';
		}

		return $shouldEmit;
	}


	/**
	 * Format a message.
	 *
	 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
	 * receive special fomatting to mimic the historic output of the functions
	 * of the same name. All other channel values are formatted based on the
	 * historic output of the `wfDebugLog()` global function.
	 *
	 * @param string $channel
	 * @param string $message
	 * @param array $context
	 * @return string
	 */
	public static function format( $channel, $message, $context ) {
		global $wgDebugLogGroups, $wgLogExceptionBacktrace;

		if ( $channel === 'wfDebug' ) {
			$text = self::formatAsWfDebug( $channel, $message, $context );

		} elseif ( $channel === 'wfLogDBError' ) {
			$text = self::formatAsWfLogDBError( $channel, $message, $context );

		} elseif ( $channel === 'wfErrorLog' ) {
			$text = "{$message}\n";

		} elseif ( $channel === 'profileoutput' ) {
			// Legacy wfLogProfilingData formatitng
			$forward = '';
			if ( isset( $context['forwarded_for'] ) ) {
				$forward = " forwarded for {$context['forwarded_for']}";
			}
			if ( isset( $context['client_ip'] ) ) {
				$forward .= " client IP {$context['client_ip']}";
			}
			if ( isset( $context['from'] ) ) {
				$forward .= " from {$context['from']}";
			}
			if ( $forward ) {
				$forward = "\t(proxied via {$context['proxy']}{$forward})";
			}
			if ( $context['anon'] ) {
				$forward .= ' anon';
			}
			if ( !isset( $context['url'] ) ) {
				$context['url'] = 'n/a';
			}

			$log = sprintf( "%s\t%04.3f\t%s%s\n",
				gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );

			$text = self::formatAsWfDebugLog(
				$channel, $log . $context['output'], $context );

		} elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
			$text = self::formatAsWfDebug(
				$channel, "[{$channel}] {$message}", $context );

		} else {
			// Default formatting is wfDebugLog's historic style
			$text = self::formatAsWfDebugLog( $channel, $message, $context );
		}

		// Append stacktrace of exception if available
		if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
			$e = $context['exception'];
			$backtrace = false;

			if ( $e instanceof Exception ) {
				$backtrace = MWExceptionHandler::getRedactedTrace( $e );

			} elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
				// Exception has already been unpacked as structured data
				$backtrace = $e['trace'];
			}

			if ( $backtrace ) {
				$text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
					"\n";
			}
		}

		return self::interpolate( $text, $context );
	}


	/**
	 * Format a message as `wfDebug()` would have formatted it.
	 *
	 * @param string $channel
	 * @param string $message
	 * @param array $context
	 * @return string
	 */
	protected static function formatAsWfDebug( $channel, $message, $context ) {
		$text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
		if ( isset( $context['seconds_elapsed'] ) ) {
			// Prepend elapsed request time and real memory usage with two
			// trailing spaces.
			$text = "{$context['seconds_elapsed']} {$context['memory_used']}  {$text}";
		}
		if ( isset( $context['prefix'] ) ) {
			$text = "{$context['prefix']}{$text}";
		}
		return "{$text}\n";
	}


	/**
	 * Format a message as `wfLogDBError()` would have formatted it.
	 *
	 * @param string $channel
	 * @param string $message
	 * @param array $context
	 * @return string
	 */
	protected static function formatAsWfLogDBError( $channel, $message, $context ) {
		global $wgDBerrorLogTZ;
		static $cachedTimezone = null;

		if ( !$cachedTimezone ) {
			$cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
		}

		// Workaround for https://bugs.php.net/bug.php?id=52063
		// Can be removed when min PHP > 5.3.6
		if ( $cachedTimezone === null ) {
			$d = date_create( 'now' );
		} else {
			$d = date_create( 'now', $cachedTimezone );
		}
		$date = $d->format( 'D M j G:i:s T Y' );

		$host = wfHostname();
		$wiki = wfWikiID();

		$text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
		return $text;
	}


	/**
	 * Format a message as `wfDebugLog() would have formatted it.
	 *
	 * @param string $channel
	 * @param string $message
	 * @param array $context
	 */
	protected static function formatAsWfDebugLog( $channel, $message, $context ) {
		$time = wfTimestamp( TS_DB );
		$wiki = wfWikiID();
		$host = wfHostname();
		$text = "{$time} {$host} {$wiki}: {$message}\n";
		return $text;
	}


	/**
	 * Interpolate placeholders in logging message.
	 *
	 * @param string $message
	 * @param array $context
	 * @return string Interpolated message
	 */
	public static function interpolate( $message, array $context ) {
		if ( strpos( $message, '{' ) !== false ) {
			$replace = array();
			foreach ( $context as $key => $val ) {
				$replace['{' . $key . '}'] = self::flatten( $val );
			}
			$message = strtr( $message, $replace );
		}
		return $message;
	}


	/**
	 * Convert a logging context element to a string suitable for
	 * interpolation.
	 *
	 * @param mixed $item
	 * @return string
	 */
	protected static function flatten( $item ) {
		if ( null === $item ) {
			return '[Null]';
		}

		if ( is_bool( $item ) ) {
			return $item ? 'true' : 'false';
		}

		if ( is_float( $item ) ) {
			if ( is_infinite( $item ) ) {
				return ( $item > 0 ? '' : '-' ) . 'INF';
			}
			if ( is_nan( $item ) ) {
				return 'NaN';
			}
			return $item;
		}

		if ( is_scalar( $item ) ) {
			return (string) $item;
		}

		if ( is_array( $item ) ) {
			return '[Array(' . count( $item ) . ')]';
		}

		if ( $item instanceof \DateTime ) {
			return $item->format( 'c' );
		}

		if ( $item instanceof Exception ) {
			return '[Exception ' . get_class( $item ) . '( ' .
				$item->getFile() . ':' . $item->getLine() . ') ' .
				$item->getMessage() . ']';
		}

		if ( is_object( $item ) ) {
			if ( method_exists( $item, '__toString' ) ) {
				return (string) $item;
			}

			return '[Object ' . get_class( $item ) . ']';
		}

		if ( is_resource( $item ) ) {
			return '[Resource ' . get_resource_type( $item ) . ']';
		}

		return '[Unknown ' . gettype( $item ) . ']';
	}


	/**
	 * Select the appropriate log output destination for the given log event.
	 *
	 * If the event context contains 'destination'
	 *
	 * @param string $channel
	 * @param string $message
	 * @param array $context
	 * @return string
	 */
	protected static function destination( $channel, $message, $context ) {
		global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;

		// Default destination is the debug log file as historically used by
		// the wfDebug function.
		$destination = $wgDebugLogFile;

		if ( isset( $context['destination'] ) ) {
			// Use destination explicitly provided in context
			$destination = $context['destination'];

		} elseif ( $channel === 'wfDebug' ) {
			$destination = $wgDebugLogFile;

		} elseif ( $channel === 'wfLogDBError' ) {
			$destination = $wgDBerrorLog;

		} elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
			$logConfig = $wgDebugLogGroups[$channel];

			if ( is_array( $logConfig ) ) {
				$destination = $logConfig['destination'];
			} else {
				$destination = strval( $logConfig );
			}
		}

		return $destination;
	}


	/**
	* Log to a file without getting "file size exceeded" signals.
	*
	* Can also log to UDP with the syntax udp://host:port/prefix. This will send
	* lines to the specified port, prefixed by the specified prefix and a space.
	*
	* @param string $text
	* @param string $file Filename
	* @throws MWException
	*/
	public static function emit( $text, $file ) {
		if ( substr( $file, 0, 4 ) == 'udp:' ) {
			$transport = UDPTransport::newFromString( $file );
			$transport->emit( $text );
		} else {
			\MediaWiki\suppressWarnings();
			$exists = file_exists( $file );
			$size = $exists ? filesize( $file ) : false;
			if ( !$exists ||
				( $size !== false && $size + strlen( $text ) < 0x7fffffff )
			) {
				file_put_contents( $file, $text, FILE_APPEND );
			}
			\MediaWiki\restoreWarnings();
		}
	}

}