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