Merge "Partially revert increased wikitable padding"
[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 MWDebug;
24 use Psr\Log\AbstractLogger;
25 use Psr\Log\LogLevel;
26 use UDPTransport;
27
28 /**
29 * PSR-3 logger that mimics the historic implementation of MediaWiki's
30 * wfErrorLog logging implementation.
31 *
32 * This logger is configured by the following global configuration variables:
33 * - `$wgDebugLogFile`
34 * - `$wgDebugLogGroups`
35 * - `$wgDBerrorLog`
36 * - `$wgDBerrorLogTZ`
37 *
38 * See documentation in DefaultSettings.php for detailed explanations of each
39 * variable.
40 *
41 * @see \MediaWiki\Logger\LoggerFactory
42 * @since 1.25
43 * @author Bryan Davis <bd808@wikimedia.org>
44 * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
45 */
46 class LegacyLogger extends AbstractLogger {
47
48 /**
49 * @var string $channel
50 */
51 protected $channel;
52
53 /**
54 * Convert Psr\Log\LogLevel constants into int for sane comparisons
55 * These are the same values that Monlog uses
56 *
57 * @var array
58 */
59 protected static $levelMapping = array(
60 LogLevel::DEBUG => 100,
61 LogLevel::INFO => 200,
62 LogLevel::NOTICE => 250,
63 LogLevel::WARNING => 300,
64 LogLevel::ERROR => 400,
65 LogLevel::CRITICAL => 500,
66 LogLevel::ALERT => 550,
67 LogLevel::EMERGENCY => 600,
68 );
69
70
71 /**
72 * @param string $channel
73 */
74 public function __construct( $channel ) {
75 $this->channel = $channel;
76 }
77
78 /**
79 * Logs with an arbitrary level.
80 *
81 * @param string|int $level
82 * @param string $message
83 * @param array $context
84 */
85 public function log( $level, $message, array $context = array() ) {
86 if ( self::shouldEmit( $this->channel, $message, $level, $context ) ) {
87 $text = self::format( $this->channel, $message, $context );
88 $destination = self::destination( $this->channel, $message, $context );
89 self::emit( $text, $destination );
90 }
91 // Add to debug toolbar
92 MWDebug::debugMsg( $message, array( 'channel' => $this->channel ) + $context );
93 }
94
95
96 /**
97 * Determine if the given message should be emitted or not.
98 *
99 * @param string $channel
100 * @param string $message
101 * @param string|int $level Psr\Log\LogEvent constant or Monlog level int
102 * @param array $context
103 * @return bool True if message should be sent to disk/network, false
104 * otherwise
105 */
106 public static function shouldEmit( $channel, $message, $level, $context ) {
107 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
108
109 if ( $channel === 'wfLogDBError' ) {
110 // wfLogDBError messages are emitted if a database log location is
111 // specfied.
112 $shouldEmit = (bool)$wgDBerrorLog;
113
114 } elseif ( $channel === 'wfErrorLog' ) {
115 // All messages on the wfErrorLog channel should be emitted.
116 $shouldEmit = true;
117
118 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
119 $logConfig = $wgDebugLogGroups[$channel];
120
121 if ( is_array( $logConfig ) ) {
122 $shouldEmit = true;
123 if ( isset( $logConfig['sample'] ) ) {
124 // Emit randomly with a 1 in 'sample' chance for each message.
125 $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
126 }
127
128 if ( isset( $logConfig['level'] ) ) {
129 if ( is_string( $level ) ) {
130 $level = self::$levelMapping[$level];
131 }
132 $shouldEmit = $level >= self::$levelMapping[$logConfig['level']];
133 }
134 } else {
135 // Emit unless the config value is explictly false.
136 $shouldEmit = $logConfig !== false;
137 }
138
139 } elseif ( isset( $context['private'] ) && $context['private'] ) {
140 // Don't emit if the message didn't match previous checks based on
141 // the channel and the event is marked as private. This check
142 // discards messages sent via wfDebugLog() with dest == 'private'
143 // and no explicit wgDebugLogGroups configuration.
144 $shouldEmit = false;
145 } else {
146 // Default return value is the same as the historic wfDebug
147 // method: emit if $wgDebugLogFile has been set.
148 $shouldEmit = $wgDebugLogFile != '';
149 }
150
151 return $shouldEmit;
152 }
153
154
155 /**
156 * Format a message.
157 *
158 * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
159 * receive special fomatting to mimic the historic output of the functions
160 * of the same name. All other channel values are formatted based on the
161 * historic output of the `wfDebugLog()` global function.
162 *
163 * @param string $channel
164 * @param string $message
165 * @param array $context
166 * @return string
167 */
168 public static function format( $channel, $message, $context ) {
169 global $wgDebugLogGroups;
170
171 if ( $channel === 'wfDebug' ) {
172 $text = self::formatAsWfDebug( $channel, $message, $context );
173
174 } elseif ( $channel === 'wfLogDBError' ) {
175 $text = self::formatAsWfLogDBError( $channel, $message, $context );
176
177 } elseif ( $channel === 'wfErrorLog' ) {
178 $text = "{$message}\n";
179
180 } elseif ( $channel === 'profileoutput' ) {
181 // Legacy wfLogProfilingData formatitng
182 $forward = '';
183 if ( isset( $context['forwarded_for'] )) {
184 $forward = " forwarded for {$context['forwarded_for']}";
185 }
186 if ( isset( $context['client_ip'] ) ) {
187 $forward .= " client IP {$context['client_ip']}";
188 }
189 if ( isset( $context['from'] ) ) {
190 $forward .= " from {$context['from']}";
191 }
192 if ( $forward ) {
193 $forward = "\t(proxied via {$context['proxy']}{$forward})";
194 }
195 if ( $context['anon'] ) {
196 $forward .= ' anon';
197 }
198 if ( !isset( $context['url'] ) ) {
199 $context['url'] = 'n/a';
200 }
201
202 $log = sprintf( "%s\t%04.3f\t%s%s\n",
203 gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
204
205 $text = self::formatAsWfDebugLog(
206 $channel, $log . $context['output'], $context );
207
208 } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
209 $text = self::formatAsWfDebug(
210 $channel, "[{$channel}] {$message}", $context );
211
212 } else {
213 // Default formatting is wfDebugLog's historic style
214 $text = self::formatAsWfDebugLog( $channel, $message, $context );
215 }
216
217 return self::interpolate( $text, $context );
218 }
219
220
221 /**
222 * Format a message as `wfDebug()` would have formatted it.
223 *
224 * @param string $channel
225 * @param string $message
226 * @param array $context
227 * @return string
228 */
229 protected static function formatAsWfDebug( $channel, $message, $context ) {
230 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $message );
231 if ( isset( $context['seconds_elapsed'] ) ) {
232 // Prepend elapsed request time and real memory usage with two
233 // trailing spaces.
234 $text = "{$context['seconds_elapsed']} {$context['memory_used']} {$text}";
235 }
236 if ( isset( $context['prefix'] ) ) {
237 $text = "{$context['prefix']}{$text}";
238 }
239 return "{$text}\n";
240 }
241
242
243 /**
244 * Format a message as `wfLogDBError()` would have formatted it.
245 *
246 * @param string $channel
247 * @param string $message
248 * @param array $context
249 * @return string
250 */
251 protected static function formatAsWfLogDBError( $channel, $message, $context ) {
252 global $wgDBerrorLogTZ;
253 static $cachedTimezone = null;
254
255 if ( $wgDBerrorLogTZ && !$cachedTimezone ) {
256 $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
257 }
258
259 // Workaround for https://bugs.php.net/bug.php?id=52063
260 // Can be removed when min PHP > 5.3.6
261 if ( $cachedTimezone === null ) {
262 $d = date_create( 'now' );
263 } else {
264 $d = date_create( 'now', $cachedTimezone );
265 }
266 $date = $d->format( 'D M j G:i:s T Y' );
267
268 $host = wfHostname();
269 $wiki = wfWikiID();
270
271 $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
272 return $text;
273 }
274
275
276 /**
277 * Format a message as `wfDebugLog() would have formatted it.
278 *
279 * @param string $channel
280 * @param string $message
281 * @param array $context
282 */
283 protected static function formatAsWfDebugLog( $channel, $message, $context ) {
284 $time = wfTimestamp( TS_DB );
285 $wiki = wfWikiID();
286 $host = wfHostname();
287 $text = "{$time} {$host} {$wiki}: {$message}\n";
288 return $text;
289 }
290
291
292 /**
293 * Interpolate placeholders in logging message.
294 *
295 * @param string $message
296 * @param array $context
297 * @return string Interpolated message
298 */
299 public static function interpolate( $message, array $context ) {
300 if ( strpos( $message, '{' ) !== false ) {
301 $replace = array();
302 foreach ( $context as $key => $val ) {
303 $replace['{' . $key . '}'] = $val;
304 }
305 $message = strtr( $message, $replace );
306 }
307 return $message;
308 }
309
310
311 /**
312 * Select the appropriate log output destination for the given log event.
313 *
314 * If the event context contains 'destination'
315 *
316 * @param string $channel
317 * @param string $message
318 * @param array $context
319 * @return string
320 */
321 protected static function destination( $channel, $message, $context ) {
322 global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
323
324 // Default destination is the debug log file as historically used by
325 // the wfDebug function.
326 $destination = $wgDebugLogFile;
327
328 if ( isset( $context['destination'] ) ) {
329 // Use destination explicitly provided in context
330 $destination = $context['destination'];
331
332 } elseif ( $channel === 'wfDebug' ) {
333 $destination = $wgDebugLogFile;
334
335 } elseif ( $channel === 'wfLogDBError' ) {
336 $destination = $wgDBerrorLog;
337
338 } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
339 $logConfig = $wgDebugLogGroups[$channel];
340
341 if ( is_array( $logConfig ) ) {
342 $destination = $logConfig['destination'];
343 } else {
344 $destination = strval( $logConfig );
345 }
346 }
347
348 return $destination;
349 }
350
351
352 /**
353 * Log to a file without getting "file size exceeded" signals.
354 *
355 * Can also log to UDP with the syntax udp://host:port/prefix. This will send
356 * lines to the specified port, prefixed by the specified prefix and a space.
357 *
358 * @param string $text
359 * @param string $file Filename
360 * @throws MWException
361 */
362 public static function emit( $text, $file ) {
363 if ( substr( $file, 0, 4 ) == 'udp:' ) {
364 $transport = UDPTransport::newFromString( $file );
365 $transport->emit( $text );
366 } else {
367 wfSuppressWarnings();
368 $exists = file_exists( $file );
369 $size = $exists ? filesize( $file ) : false;
370 if ( !$exists ||
371 ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
372 ) {
373 file_put_contents( $file, $text, FILE_APPEND );
374 }
375 wfRestoreWarnings();
376 }
377 }
378
379 }