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