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