PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/debug/logger/LegacyLogger.php

https://gitlab.com/link233/bootmw
PHP | 454 lines | 235 code | 59 blank | 160 comment | 51 complexity | 48c9965c9d14546bc199524d1febe89a MD5 | raw file
  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. namespace MediaWiki\Logger;
  21. use DateTimeZone;
  22. use Exception;
  23. use MWDebug;
  24. use MWExceptionHandler;
  25. use Psr\Log\AbstractLogger;
  26. use Psr\Log\LogLevel;
  27. use UDPTransport;
  28. /**
  29. * PSR-3 logger that mimics the historic implementation of MediaWiki's
  30. * wfErrorLog logging implementation.
  31. *
  32. * This logger is configured by the following global configuration variables:
  33. * - `$wgDebugLogFile`
  34. * - `$wgDebugLogGroups`
  35. * - `$wgDBerrorLog`
  36. * - `$wgDBerrorLogTZ`
  37. *
  38. * See documentation in DefaultSettings.php for detailed explanations of each
  39. * variable.
  40. *
  41. * @see \MediaWiki\Logger\LoggerFactory
  42. * @since 1.25
  43. * @author Bryan Davis <bd808@wikimedia.org>
  44. * @copyright © 2014 Bryan Davis and Wikimedia Foundation.
  45. */
  46. class LegacyLogger extends AbstractLogger {
  47. /**
  48. * @var string $channel
  49. */
  50. protected $channel;
  51. /**
  52. * Convert \Psr\Log\LogLevel constants into int for sane comparisons
  53. * These are the same values that Monlog uses
  54. *
  55. * @var array $levelMapping
  56. */
  57. protected static $levelMapping = [
  58. LogLevel::DEBUG => 100,
  59. LogLevel::INFO => 200,
  60. LogLevel::NOTICE => 250,
  61. LogLevel::WARNING => 300,
  62. LogLevel::ERROR => 400,
  63. LogLevel::CRITICAL => 500,
  64. LogLevel::ALERT => 550,
  65. LogLevel::EMERGENCY => 600,
  66. ];
  67. /**
  68. * @param string $channel
  69. */
  70. public function __construct( $channel ) {
  71. $this->channel = $channel;
  72. }
  73. /**
  74. * Logs with an arbitrary level.
  75. *
  76. * @param string|int $level
  77. * @param string $message
  78. * @param array $context
  79. */
  80. public function log( $level, $message, array $context = [] ) {
  81. if ( self::shouldEmit( $this->channel, $message, $level, $context ) ) {
  82. $text = self::format( $this->channel, $message, $context );
  83. $destination = self::destination( $this->channel, $message, $context );
  84. self::emit( $text, $destination );
  85. }
  86. if ( !isset( $context['private'] ) || !$context['private'] ) {
  87. // Add to debug toolbar if not marked as "private"
  88. MWDebug::debugMsg( $message, [ 'channel' => $this->channel ] + $context );
  89. }
  90. }
  91. /**
  92. * Determine if the given message should be emitted or not.
  93. *
  94. * @param string $channel
  95. * @param string $message
  96. * @param string|int $level \Psr\Log\LogEvent constant or Monlog level int
  97. * @param array $context
  98. * @return bool True if message should be sent to disk/network, false
  99. * otherwise
  100. */
  101. public static function shouldEmit( $channel, $message, $level, $context ) {
  102. global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
  103. if ( $channel === 'wfLogDBError' ) {
  104. // wfLogDBError messages are emitted if a database log location is
  105. // specfied.
  106. $shouldEmit = (bool)$wgDBerrorLog;
  107. } elseif ( $channel === 'wfErrorLog' ) {
  108. // All messages on the wfErrorLog channel should be emitted.
  109. $shouldEmit = true;
  110. } elseif ( $channel === 'wfDebug' ) {
  111. // wfDebug messages are emitted if a catch all logging file has
  112. // been specified. Checked explicitly so that 'private' flagged
  113. // messages are not discarded by unset $wgDebugLogGroups channel
  114. // handling below.
  115. $shouldEmit = $wgDebugLogFile != '';
  116. } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
  117. $logConfig = $wgDebugLogGroups[$channel];
  118. if ( is_array( $logConfig ) ) {
  119. $shouldEmit = true;
  120. if ( isset( $logConfig['sample'] ) ) {
  121. // Emit randomly with a 1 in 'sample' chance for each message.
  122. $shouldEmit = mt_rand( 1, $logConfig['sample'] ) === 1;
  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. } elseif ( isset( $context['private'] ) && $context['private'] ) {
  135. // Don't emit if the message didn't match previous checks based on
  136. // the channel and the event is marked as private. This check
  137. // discards messages sent via wfDebugLog() with dest == 'private'
  138. // and no explicit wgDebugLogGroups configuration.
  139. $shouldEmit = false;
  140. } else {
  141. // Default return value is the same as the historic wfDebug
  142. // method: emit if $wgDebugLogFile has been set.
  143. $shouldEmit = $wgDebugLogFile != '';
  144. }
  145. return $shouldEmit;
  146. }
  147. /**
  148. * Format a message.
  149. *
  150. * Messages to the 'wfDebug', 'wfLogDBError' and 'wfErrorLog' channels
  151. * receive special fomatting to mimic the historic output of the functions
  152. * of the same name. All other channel values are formatted based on the
  153. * historic output of the `wfDebugLog()` global function.
  154. *
  155. * @param string $channel
  156. * @param string $message
  157. * @param array $context
  158. * @return string
  159. */
  160. public static function format( $channel, $message, $context ) {
  161. global $wgDebugLogGroups, $wgLogExceptionBacktrace;
  162. if ( $channel === 'wfDebug' ) {
  163. $text = self::formatAsWfDebug( $channel, $message, $context );
  164. } elseif ( $channel === 'wfLogDBError' ) {
  165. $text = self::formatAsWfLogDBError( $channel, $message, $context );
  166. } elseif ( $channel === 'wfErrorLog' ) {
  167. $text = "{$message}\n";
  168. } elseif ( $channel === 'profileoutput' ) {
  169. // Legacy wfLogProfilingData formatitng
  170. $forward = '';
  171. if ( isset( $context['forwarded_for'] ) ) {
  172. $forward = " forwarded for {$context['forwarded_for']}";
  173. }
  174. if ( isset( $context['client_ip'] ) ) {
  175. $forward .= " client IP {$context['client_ip']}";
  176. }
  177. if ( isset( $context['from'] ) ) {
  178. $forward .= " from {$context['from']}";
  179. }
  180. if ( $forward ) {
  181. $forward = "\t(proxied via {$context['proxy']}{$forward})";
  182. }
  183. if ( $context['anon'] ) {
  184. $forward .= ' anon';
  185. }
  186. if ( !isset( $context['url'] ) ) {
  187. $context['url'] = 'n/a';
  188. }
  189. $log = sprintf( "%s\t%04.3f\t%s%s\n",
  190. gmdate( 'YmdHis' ), $context['elapsed'], $context['url'], $forward );
  191. $text = self::formatAsWfDebugLog(
  192. $channel, $log . $context['output'], $context );
  193. } elseif ( !isset( $wgDebugLogGroups[$channel] ) ) {
  194. $text = self::formatAsWfDebug(
  195. $channel, "[{$channel}] {$message}", $context );
  196. } else {
  197. // Default formatting is wfDebugLog's historic style
  198. $text = self::formatAsWfDebugLog( $channel, $message, $context );
  199. }
  200. // Append stacktrace of exception if available
  201. if ( $wgLogExceptionBacktrace && isset( $context['exception'] ) ) {
  202. $e = $context['exception'];
  203. $backtrace = false;
  204. if ( $e instanceof Exception ) {
  205. $backtrace = MWExceptionHandler::getRedactedTrace( $e );
  206. } elseif ( is_array( $e ) && isset( $e['trace'] ) ) {
  207. // Exception has already been unpacked as structured data
  208. $backtrace = $e['trace'];
  209. }
  210. if ( $backtrace ) {
  211. $text .= MWExceptionHandler::prettyPrintTrace( $backtrace ) .
  212. "\n";
  213. }
  214. }
  215. return self::interpolate( $text, $context );
  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. * 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. if ( !$cachedTimezone ) {
  249. $cachedTimezone = new DateTimeZone( $wgDBerrorLogTZ );
  250. }
  251. $d = date_create( 'now', $cachedTimezone );
  252. $date = $d->format( 'D M j G:i:s T Y' );
  253. $host = wfHostname();
  254. $wiki = wfWikiID();
  255. $text = "{$date}\t{$host}\t{$wiki}\t{$message}\n";
  256. return $text;
  257. }
  258. /**
  259. * Format a message as `wfDebugLog() would have formatted it.
  260. *
  261. * @param string $channel
  262. * @param string $message
  263. * @param array $context
  264. */
  265. protected static function formatAsWfDebugLog( $channel, $message, $context ) {
  266. $time = wfTimestamp( TS_DB );
  267. $wiki = wfWikiID();
  268. $host = wfHostname();
  269. $text = "{$time} {$host} {$wiki}: {$message}\n";
  270. return $text;
  271. }
  272. /**
  273. * Interpolate placeholders in logging message.
  274. *
  275. * @param string $message
  276. * @param array $context
  277. * @return string Interpolated message
  278. */
  279. public static function interpolate( $message, array $context ) {
  280. if ( strpos( $message, '{' ) !== false ) {
  281. $replace = [];
  282. foreach ( $context as $key => $val ) {
  283. $replace['{' . $key . '}'] = self::flatten( $val );
  284. }
  285. $message = strtr( $message, $replace );
  286. }
  287. return $message;
  288. }
  289. /**
  290. * Convert a logging context element to a string suitable for
  291. * interpolation.
  292. *
  293. * @param mixed $item
  294. * @return string
  295. */
  296. protected static function flatten( $item ) {
  297. if ( null === $item ) {
  298. return '[Null]';
  299. }
  300. if ( is_bool( $item ) ) {
  301. return $item ? 'true' : 'false';
  302. }
  303. if ( is_float( $item ) ) {
  304. if ( is_infinite( $item ) ) {
  305. return ( $item > 0 ? '' : '-' ) . 'INF';
  306. }
  307. if ( is_nan( $item ) ) {
  308. return 'NaN';
  309. }
  310. return $item;
  311. }
  312. if ( is_scalar( $item ) ) {
  313. return (string)$item;
  314. }
  315. if ( is_array( $item ) ) {
  316. return '[Array(' . count( $item ) . ')]';
  317. }
  318. if ( $item instanceof \DateTime ) {
  319. return $item->format( 'c' );
  320. }
  321. if ( $item instanceof Exception ) {
  322. return '[Exception ' . get_class( $item ) . '( ' .
  323. $item->getFile() . ':' . $item->getLine() . ') ' .
  324. $item->getMessage() . ']';
  325. }
  326. if ( is_object( $item ) ) {
  327. if ( method_exists( $item, '__toString' ) ) {
  328. return (string)$item;
  329. }
  330. return '[Object ' . get_class( $item ) . ']';
  331. }
  332. if ( is_resource( $item ) ) {
  333. return '[Resource ' . get_resource_type( $item ) . ']';
  334. }
  335. return '[Unknown ' . gettype( $item ) . ']';
  336. }
  337. /**
  338. * Select the appropriate log output destination for the given log event.
  339. *
  340. * If the event context contains 'destination'
  341. *
  342. * @param string $channel
  343. * @param string $message
  344. * @param array $context
  345. * @return string
  346. */
  347. protected static function destination( $channel, $message, $context ) {
  348. global $wgDebugLogFile, $wgDBerrorLog, $wgDebugLogGroups;
  349. // Default destination is the debug log file as historically used by
  350. // the wfDebug function.
  351. $destination = $wgDebugLogFile;
  352. if ( isset( $context['destination'] ) ) {
  353. // Use destination explicitly provided in context
  354. $destination = $context['destination'];
  355. } elseif ( $channel === 'wfDebug' ) {
  356. $destination = $wgDebugLogFile;
  357. } elseif ( $channel === 'wfLogDBError' ) {
  358. $destination = $wgDBerrorLog;
  359. } elseif ( isset( $wgDebugLogGroups[$channel] ) ) {
  360. $logConfig = $wgDebugLogGroups[$channel];
  361. if ( is_array( $logConfig ) ) {
  362. $destination = $logConfig['destination'];
  363. } else {
  364. $destination = strval( $logConfig );
  365. }
  366. }
  367. return $destination;
  368. }
  369. /**
  370. * Log to a file without getting "file size exceeded" signals.
  371. *
  372. * Can also log to UDP with the syntax udp://host:port/prefix. This will send
  373. * lines to the specified port, prefixed by the specified prefix and a space.
  374. *
  375. * @param string $text
  376. * @param string $file Filename
  377. * @throws MWException
  378. */
  379. public static function emit( $text, $file ) {
  380. if ( substr( $file, 0, 4 ) == 'udp:' ) {
  381. $transport = UDPTransport::newFromString( $file );
  382. $transport->emit( $text );
  383. } else {
  384. \MediaWiki\suppressWarnings();
  385. $exists = file_exists( $file );
  386. $size = $exists ? filesize( $file ) : false;
  387. if ( !$exists ||
  388. ( $size !== false && $size + strlen( $text ) < 0x7fffffff )
  389. ) {
  390. file_put_contents( $file, $text, FILE_APPEND );
  391. }
  392. \MediaWiki\restoreWarnings();
  393. }
  394. }
  395. }