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