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