2
0

Logger.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog;
  11. use DateTimeZone;
  12. use Monolog\Handler\HandlerInterface;
  13. use Psr\Log\LoggerInterface;
  14. use Psr\Log\InvalidArgumentException;
  15. use Psr\Log\LogLevel;
  16. use Throwable;
  17. use Stringable;
  18. /**
  19. * Monolog log channel
  20. *
  21. * It contains a stack of Handlers and a stack of Processors,
  22. * and uses them to store records that are added to it.
  23. *
  24. * @author Jordi Boggiano <j.boggiano@seld.be>
  25. *
  26. * @phpstan-type Level Logger::DEBUG|Logger::INFO|Logger::NOTICE|Logger::WARNING|Logger::ERROR|Logger::CRITICAL|Logger::ALERT|Logger::EMERGENCY
  27. * @phpstan-type LevelName 'DEBUG'|'INFO'|'NOTICE'|'WARNING'|'ERROR'|'CRITICAL'|'ALERT'|'EMERGENCY'
  28. * @phpstan-type Record array{message: string, context: mixed[], level: Level, level_name: LevelName, channel: string, datetime: \DateTimeImmutable, extra: mixed[]}
  29. */
  30. class Logger implements LoggerInterface, ResettableInterface
  31. {
  32. /**
  33. * Detailed debug information
  34. */
  35. public const DEBUG = 100;
  36. /**
  37. * Interesting events
  38. *
  39. * Examples: User logs in, SQL logs.
  40. */
  41. public const INFO = 200;
  42. /**
  43. * Uncommon events
  44. */
  45. public const NOTICE = 250;
  46. /**
  47. * Exceptional occurrences that are not errors
  48. *
  49. * Examples: Use of deprecated APIs, poor use of an API,
  50. * undesirable things that are not necessarily wrong.
  51. */
  52. public const WARNING = 300;
  53. /**
  54. * Runtime errors
  55. */
  56. public const ERROR = 400;
  57. /**
  58. * Critical conditions
  59. *
  60. * Example: Application component unavailable, unexpected exception.
  61. */
  62. public const CRITICAL = 500;
  63. /**
  64. * Action must be taken immediately
  65. *
  66. * Example: Entire website down, database unavailable, etc.
  67. * This should trigger the SMS alerts and wake you up.
  68. */
  69. public const ALERT = 550;
  70. /**
  71. * Urgent alert.
  72. */
  73. public const EMERGENCY = 600;
  74. /**
  75. * Monolog API version
  76. *
  77. * This is only bumped when API breaks are done and should
  78. * follow the major version of the library
  79. *
  80. * @var int
  81. */
  82. public const API = 2;
  83. /**
  84. * This is a static variable and not a constant to serve as an extension point for custom levels
  85. *
  86. * @var array<int, string> $levels Logging levels with the levels as key
  87. *
  88. * @phpstan-var array<Level, LevelName> $levels Logging levels with the levels as key
  89. */
  90. protected static $levels = [
  91. self::DEBUG => 'DEBUG',
  92. self::INFO => 'INFO',
  93. self::NOTICE => 'NOTICE',
  94. self::WARNING => 'WARNING',
  95. self::ERROR => 'ERROR',
  96. self::CRITICAL => 'CRITICAL',
  97. self::ALERT => 'ALERT',
  98. self::EMERGENCY => 'EMERGENCY',
  99. ];
  100. /**
  101. * Mapping between levels numbers defined in RFC 5424 and Monolog ones
  102. *
  103. * @phpstan-var array<int, Level> $rfc_5424_levels
  104. */
  105. private const RFC_5424_LEVELS = [
  106. 7 => self::DEBUG,
  107. 6 => self::INFO,
  108. 5 => self::NOTICE,
  109. 4 => self::WARNING,
  110. 3 => self::ERROR,
  111. 2 => self::CRITICAL,
  112. 1 => self::ALERT,
  113. 0 => self::EMERGENCY,
  114. ];
  115. /**
  116. * @var string
  117. */
  118. protected $name;
  119. /**
  120. * The handler stack
  121. *
  122. * @var HandlerInterface[]
  123. */
  124. protected $handlers;
  125. /**
  126. * Processors that will process all log records
  127. *
  128. * To process records of a single handler instead, add the processor on that specific handler
  129. *
  130. * @var callable[]
  131. */
  132. protected $processors;
  133. /**
  134. * @var bool
  135. */
  136. protected $microsecondTimestamps = true;
  137. /**
  138. * @var DateTimeZone
  139. */
  140. protected $timezone;
  141. /**
  142. * @var callable|null
  143. */
  144. protected $exceptionHandler;
  145. /**
  146. * @var int Keeps track of depth to prevent infinite logging loops
  147. */
  148. private $logDepth = 0;
  149. /**
  150. * @var \WeakMap<\Fiber, int>|null Keeps track of depth inside fibers to prevent infinite logging loops
  151. */
  152. private $fiberLogDepth;
  153. /**
  154. * @var bool Whether to detect infinite logging loops
  155. *
  156. * This can be disabled via {@see useLoggingLoopDetection} if you have async handlers that do not play well with this
  157. */
  158. private $detectCycles = true;
  159. /**
  160. * @psalm-param array<callable(array): array> $processors
  161. *
  162. * @param string $name The logging channel, a simple descriptive name that is attached to all log records
  163. * @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
  164. * @param callable[] $processors Optional array of processors
  165. * @param DateTimeZone|null $timezone Optional timezone, if not provided date_default_timezone_get() will be used
  166. */
  167. public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone = null)
  168. {
  169. $this->name = $name;
  170. $this->setHandlers($handlers);
  171. $this->processors = $processors;
  172. $this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC');
  173. if (\PHP_VERSION_ID >= 80100) {
  174. // Local variable for phpstan, see https://github.com/phpstan/phpstan/issues/6732#issuecomment-1111118412
  175. /** @var \WeakMap<\Fiber, int> $fiberLogDepth */
  176. $fiberLogDepth = new \WeakMap();
  177. $this->fiberLogDepth = $fiberLogDepth;
  178. }
  179. }
  180. public function getName(): string
  181. {
  182. return $this->name;
  183. }
  184. /**
  185. * Return a new cloned instance with the name changed
  186. */
  187. public function withName(string $name): self
  188. {
  189. $new = clone $this;
  190. $new->name = $name;
  191. return $new;
  192. }
  193. /**
  194. * Pushes a handler on to the stack.
  195. */
  196. public function pushHandler(HandlerInterface $handler): self
  197. {
  198. array_unshift($this->handlers, $handler);
  199. return $this;
  200. }
  201. /**
  202. * Pops a handler from the stack
  203. *
  204. * @throws \LogicException If empty handler stack
  205. */
  206. public function popHandler(): HandlerInterface
  207. {
  208. if (!$this->handlers) {
  209. throw new \LogicException('You tried to pop from an empty handler stack.');
  210. }
  211. return array_shift($this->handlers);
  212. }
  213. /**
  214. * Set handlers, replacing all existing ones.
  215. *
  216. * If a map is passed, keys will be ignored.
  217. *
  218. * @param HandlerInterface[] $handlers
  219. */
  220. public function setHandlers(array $handlers): self
  221. {
  222. $this->handlers = [];
  223. foreach (array_reverse($handlers) as $handler) {
  224. $this->pushHandler($handler);
  225. }
  226. return $this;
  227. }
  228. /**
  229. * @return HandlerInterface[]
  230. */
  231. public function getHandlers(): array
  232. {
  233. return $this->handlers;
  234. }
  235. /**
  236. * Adds a processor on to the stack.
  237. */
  238. public function pushProcessor(callable $callback): self
  239. {
  240. array_unshift($this->processors, $callback);
  241. return $this;
  242. }
  243. /**
  244. * Removes the processor on top of the stack and returns it.
  245. *
  246. * @throws \LogicException If empty processor stack
  247. * @return callable
  248. */
  249. public function popProcessor(): callable
  250. {
  251. if (!$this->processors) {
  252. throw new \LogicException('You tried to pop from an empty processor stack.');
  253. }
  254. return array_shift($this->processors);
  255. }
  256. /**
  257. * @return callable[]
  258. */
  259. public function getProcessors(): array
  260. {
  261. return $this->processors;
  262. }
  263. /**
  264. * Control the use of microsecond resolution timestamps in the 'datetime'
  265. * member of new records.
  266. *
  267. * As of PHP7.1 microseconds are always included by the engine, so
  268. * there is no performance penalty and Monolog 2 enabled microseconds
  269. * by default. This function lets you disable them though in case you want
  270. * to suppress microseconds from the output.
  271. *
  272. * @param bool $micro True to use microtime() to create timestamps
  273. */
  274. public function useMicrosecondTimestamps(bool $micro): self
  275. {
  276. $this->microsecondTimestamps = $micro;
  277. return $this;
  278. }
  279. public function useLoggingLoopDetection(bool $detectCycles): self
  280. {
  281. $this->detectCycles = $detectCycles;
  282. return $this;
  283. }
  284. /**
  285. * Adds a log record.
  286. *
  287. * @param int $level The logging level (a Monolog or RFC 5424 level)
  288. * @param string $message The log message
  289. * @param mixed[] $context The log context
  290. * @param DateTimeImmutable $datetime Optional log date to log into the past or future
  291. * @return bool Whether the record has been processed
  292. *
  293. * @phpstan-param Level $level
  294. */
  295. public function addRecord(int $level, string $message, array $context = [], DateTimeImmutable $datetime = null): bool
  296. {
  297. if (isset(self::RFC_5424_LEVELS[$level])) {
  298. $level = self::RFC_5424_LEVELS[$level];
  299. }
  300. if ($this->detectCycles) {
  301. // @phpstan-ignore-next-line
  302. if (\PHP_VERSION_ID >= 80100 && $fiber = \Fiber::getCurrent()) {
  303. $this->fiberLogDepth[$fiber] = $this->fiberLogDepth[$fiber] ?? 0;
  304. $logDepth = ++$this->fiberLogDepth[$fiber];
  305. } else {
  306. $logDepth = ++$this->logDepth;
  307. }
  308. } else {
  309. $logDepth = 0;
  310. }
  311. if ($logDepth === 3) {
  312. $this->warning('A possible infinite logging loop was detected and aborted. It appears some of your handler code is triggering logging, see the previous log record for a hint as to what may be the cause.');
  313. return false;
  314. } elseif ($logDepth >= 5) { // log depth 4 is let through, so we can log the warning above
  315. return false;
  316. }
  317. try {
  318. $record = null;
  319. foreach ($this->handlers as $handler) {
  320. if (null === $record) {
  321. // skip creating the record as long as no handler is going to handle it
  322. if (!$handler->isHandling(['level' => $level])) {
  323. continue;
  324. }
  325. $levelName = static::getLevelName($level);
  326. $record = [
  327. 'message' => $message,
  328. 'context' => $context,
  329. 'level' => $level,
  330. 'level_name' => $levelName,
  331. 'channel' => $this->name,
  332. 'datetime' => $datetime ?? new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
  333. 'extra' => [],
  334. ];
  335. try {
  336. foreach ($this->processors as $processor) {
  337. $record = $processor($record);
  338. }
  339. } catch (Throwable $e) {
  340. $this->handleException($e, $record);
  341. return true;
  342. }
  343. }
  344. // once the record exists, send it to all handlers as long as the bubbling chain is not interrupted
  345. try {
  346. if (true === $handler->handle($record)) {
  347. break;
  348. }
  349. } catch (Throwable $e) {
  350. $this->handleException($e, $record);
  351. return true;
  352. }
  353. }
  354. } finally {
  355. if ($this->detectCycles) {
  356. if (isset($fiber)) {
  357. // @phpstan-ignore-next-line
  358. $this->fiberLogDepth[$fiber]--;
  359. } else {
  360. $this->logDepth--;
  361. }
  362. }
  363. }
  364. return null !== $record;
  365. }
  366. /**
  367. * Ends a log cycle and frees all resources used by handlers.
  368. *
  369. * Closing a Handler means flushing all buffers and freeing any open resources/handles.
  370. * Handlers that have been closed should be able to accept log records again and re-open
  371. * themselves on demand, but this may not always be possible depending on implementation.
  372. *
  373. * This is useful at the end of a request and will be called automatically on every handler
  374. * when they get destructed.
  375. */
  376. public function close(): void
  377. {
  378. foreach ($this->handlers as $handler) {
  379. $handler->close();
  380. }
  381. }
  382. /**
  383. * Ends a log cycle and resets all handlers and processors to their initial state.
  384. *
  385. * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
  386. * state, and getting it back to a state in which it can receive log records again.
  387. *
  388. * This is useful in case you want to avoid logs leaking between two requests or jobs when you
  389. * have a long running process like a worker or an application server serving multiple requests
  390. * in one process.
  391. */
  392. public function reset(): void
  393. {
  394. foreach ($this->handlers as $handler) {
  395. if ($handler instanceof ResettableInterface) {
  396. $handler->reset();
  397. }
  398. }
  399. foreach ($this->processors as $processor) {
  400. if ($processor instanceof ResettableInterface) {
  401. $processor->reset();
  402. }
  403. }
  404. }
  405. /**
  406. * Gets all supported logging levels.
  407. *
  408. * @return array<string, int> Assoc array with human-readable level names => level codes.
  409. * @phpstan-return array<LevelName, Level>
  410. */
  411. public static function getLevels(): array
  412. {
  413. return array_flip(static::$levels);
  414. }
  415. /**
  416. * Gets the name of the logging level.
  417. *
  418. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  419. *
  420. * @phpstan-param Level $level
  421. * @phpstan-return LevelName
  422. */
  423. public static function getLevelName(int $level): string
  424. {
  425. if (!isset(static::$levels[$level])) {
  426. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  427. }
  428. return static::$levels[$level];
  429. }
  430. /**
  431. * Converts PSR-3 levels to Monolog ones if necessary
  432. *
  433. * @param string|int $level Level number (monolog) or name (PSR-3)
  434. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  435. *
  436. * @phpstan-param Level|LevelName|LogLevel::* $level
  437. * @phpstan-return Level
  438. */
  439. public static function toMonologLevel($level): int
  440. {
  441. if (is_string($level)) {
  442. if (is_numeric($level)) {
  443. /** @phpstan-ignore-next-line */
  444. return intval($level);
  445. }
  446. // Contains chars of all log levels and avoids using strtoupper() which may have
  447. // strange results depending on locale (for example, "i" will become "İ" in Turkish locale)
  448. $upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY');
  449. if (defined(__CLASS__.'::'.$upper)) {
  450. return constant(__CLASS__ . '::' . $upper);
  451. }
  452. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels));
  453. }
  454. if (!is_int($level)) {
  455. throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels));
  456. }
  457. return $level;
  458. }
  459. /**
  460. * Checks whether the Logger has a handler that listens on the given level
  461. *
  462. * @phpstan-param Level $level
  463. */
  464. public function isHandling(int $level): bool
  465. {
  466. $record = [
  467. 'level' => $level,
  468. ];
  469. foreach ($this->handlers as $handler) {
  470. if ($handler->isHandling($record)) {
  471. return true;
  472. }
  473. }
  474. return false;
  475. }
  476. /**
  477. * Set a custom exception handler that will be called if adding a new record fails
  478. *
  479. * The callable will receive an exception object and the record that failed to be logged
  480. */
  481. public function setExceptionHandler(?callable $callback): self
  482. {
  483. $this->exceptionHandler = $callback;
  484. return $this;
  485. }
  486. public function getExceptionHandler(): ?callable
  487. {
  488. return $this->exceptionHandler;
  489. }
  490. /**
  491. * Adds a log record at an arbitrary level.
  492. *
  493. * This method allows for compatibility with common interfaces.
  494. *
  495. * @param mixed $level The log level (a Monolog, PSR-3 or RFC 5424 level)
  496. * @param string|Stringable $message The log message
  497. * @param mixed[] $context The log context
  498. *
  499. * @phpstan-param Level|LevelName|LogLevel::* $level
  500. */
  501. public function log($level, $message, array $context = []): void
  502. {
  503. if (!is_int($level) && !is_string($level)) {
  504. throw new \InvalidArgumentException('$level is expected to be a string or int');
  505. }
  506. if (isset(self::RFC_5424_LEVELS[$level])) {
  507. $level = self::RFC_5424_LEVELS[$level];
  508. }
  509. $level = static::toMonologLevel($level);
  510. $this->addRecord($level, (string) $message, $context);
  511. }
  512. /**
  513. * Adds a log record at the DEBUG level.
  514. *
  515. * This method allows for compatibility with common interfaces.
  516. *
  517. * @param string|Stringable $message The log message
  518. * @param mixed[] $context The log context
  519. */
  520. public function debug($message, array $context = []): void
  521. {
  522. $this->addRecord(static::DEBUG, (string) $message, $context);
  523. }
  524. /**
  525. * Adds a log record at the INFO level.
  526. *
  527. * This method allows for compatibility with common interfaces.
  528. *
  529. * @param string|Stringable $message The log message
  530. * @param mixed[] $context The log context
  531. */
  532. public function info($message, array $context = []): void
  533. {
  534. $this->addRecord(static::INFO, (string) $message, $context);
  535. }
  536. /**
  537. * Adds a log record at the NOTICE level.
  538. *
  539. * This method allows for compatibility with common interfaces.
  540. *
  541. * @param string|Stringable $message The log message
  542. * @param mixed[] $context The log context
  543. */
  544. public function notice($message, array $context = []): void
  545. {
  546. $this->addRecord(static::NOTICE, (string) $message, $context);
  547. }
  548. /**
  549. * Adds a log record at the WARNING level.
  550. *
  551. * This method allows for compatibility with common interfaces.
  552. *
  553. * @param string|Stringable $message The log message
  554. * @param mixed[] $context The log context
  555. */
  556. public function warning($message, array $context = []): void
  557. {
  558. $this->addRecord(static::WARNING, (string) $message, $context);
  559. }
  560. /**
  561. * Adds a log record at the ERROR level.
  562. *
  563. * This method allows for compatibility with common interfaces.
  564. *
  565. * @param string|Stringable $message The log message
  566. * @param mixed[] $context The log context
  567. */
  568. public function error($message, array $context = []): void
  569. {
  570. $this->addRecord(static::ERROR, (string) $message, $context);
  571. }
  572. /**
  573. * Adds a log record at the CRITICAL level.
  574. *
  575. * This method allows for compatibility with common interfaces.
  576. *
  577. * @param string|Stringable $message The log message
  578. * @param mixed[] $context The log context
  579. */
  580. public function critical($message, array $context = []): void
  581. {
  582. $this->addRecord(static::CRITICAL, (string) $message, $context);
  583. }
  584. /**
  585. * Adds a log record at the ALERT level.
  586. *
  587. * This method allows for compatibility with common interfaces.
  588. *
  589. * @param string|Stringable $message The log message
  590. * @param mixed[] $context The log context
  591. */
  592. public function alert($message, array $context = []): void
  593. {
  594. $this->addRecord(static::ALERT, (string) $message, $context);
  595. }
  596. /**
  597. * Adds a log record at the EMERGENCY level.
  598. *
  599. * This method allows for compatibility with common interfaces.
  600. *
  601. * @param string|Stringable $message The log message
  602. * @param mixed[] $context The log context
  603. */
  604. public function emergency($message, array $context = []): void
  605. {
  606. $this->addRecord(static::EMERGENCY, (string) $message, $context);
  607. }
  608. /**
  609. * Sets the timezone to be used for the timestamp of log records.
  610. */
  611. public function setTimezone(DateTimeZone $tz): self
  612. {
  613. $this->timezone = $tz;
  614. return $this;
  615. }
  616. /**
  617. * Returns the timezone to be used for the timestamp of log records.
  618. */
  619. public function getTimezone(): DateTimeZone
  620. {
  621. return $this->timezone;
  622. }
  623. /**
  624. * Delegates exception management to the custom exception handler,
  625. * or throws the exception if no custom handler is set.
  626. *
  627. * @param array $record
  628. * @phpstan-param Record $record
  629. */
  630. protected function handleException(Throwable $e, array $record): void
  631. {
  632. if (!$this->exceptionHandler) {
  633. throw $e;
  634. }
  635. ($this->exceptionHandler)($e, $record);
  636. }
  637. }