LegacyLogger.php 14 KB

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