Logger.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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<mixed, mixed, mixed, mixed>, int> 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<mixed, mixed, mixed, mixed>, 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. if (\PHP_VERSION_ID >= 80100 && $fiber = \Fiber::getCurrent()) {
  302. // @phpstan-ignore offsetAssign.dimType
  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. $this->fiberLogDepth[$fiber]--;
  358. } else {
  359. $this->logDepth--;
  360. }
  361. }
  362. }
  363. return null !== $record;
  364. }
  365. /**
  366. * Ends a log cycle and frees all resources used by handlers.
  367. *
  368. * Closing a Handler means flushing all buffers and freeing any open resources/handles.
  369. * Handlers that have been closed should be able to accept log records again and re-open
  370. * themselves on demand, but this may not always be possible depending on implementation.
  371. *
  372. * This is useful at the end of a request and will be called automatically on every handler
  373. * when they get destructed.
  374. */
  375. public function close(): void
  376. {
  377. foreach ($this->handlers as $handler) {
  378. $handler->close();
  379. }
  380. }
  381. /**
  382. * Ends a log cycle and resets all handlers and processors to their initial state.
  383. *
  384. * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
  385. * state, and getting it back to a state in which it can receive log records again.
  386. *
  387. * This is useful in case you want to avoid logs leaking between two requests or jobs when you
  388. * have a long running process like a worker or an application server serving multiple requests
  389. * in one process.
  390. */
  391. public function reset(): void
  392. {
  393. foreach ($this->handlers as $handler) {
  394. if ($handler instanceof ResettableInterface) {
  395. $handler->reset();
  396. }
  397. }
  398. foreach ($this->processors as $processor) {
  399. if ($processor instanceof ResettableInterface) {
  400. $processor->reset();
  401. }
  402. }
  403. }
  404. /**
  405. * Gets all supported logging levels.
  406. *
  407. * @return array<string, int> Assoc array with human-readable level names => level codes.
  408. * @phpstan-return array<LevelName, Level>
  409. */
  410. public static function getLevels(): array
  411. {
  412. return array_flip(static::$levels);
  413. }
  414. /**
  415. * Gets the name of the logging level.
  416. *
  417. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  418. *
  419. * @phpstan-param Level $level
  420. * @phpstan-return LevelName
  421. */
  422. public static function getLevelName(int $level): string
  423. {
  424. if (!isset(static::$levels[$level])) {
  425. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
  426. }
  427. return static::$levels[$level];
  428. }
  429. /**
  430. * Converts PSR-3 levels to Monolog ones if necessary
  431. *
  432. * @param string|int $level Level number (monolog) or name (PSR-3)
  433. * @throws \Psr\Log\InvalidArgumentException If level is not defined
  434. *
  435. * @phpstan-param Level|LevelName|LogLevel::* $level
  436. * @phpstan-return Level
  437. */
  438. public static function toMonologLevel($level): int
  439. {
  440. if (is_string($level)) {
  441. if (is_numeric($level)) {
  442. /** @phpstan-ignore-next-line */
  443. return intval($level);
  444. }
  445. // Contains chars of all log levels and avoids using strtoupper() which may have
  446. // strange results depending on locale (for example, "i" will become "İ" in Turkish locale)
  447. $upper = strtr($level, 'abcdefgilmnortuwy', 'ABCDEFGILMNORTUWY');
  448. if (defined(__CLASS__.'::'.$upper)) {
  449. return constant(__CLASS__ . '::' . $upper);
  450. }
  451. throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels));
  452. }
  453. if (!is_int($level)) {
  454. throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels));
  455. }
  456. return $level;
  457. }
  458. /**
  459. * Checks whether the Logger has a handler that listens on the given level
  460. *
  461. * @phpstan-param Level $level
  462. */
  463. public function isHandling(int $level): bool
  464. {
  465. $record = [
  466. 'level' => $level,
  467. ];
  468. foreach ($this->handlers as $handler) {
  469. if ($handler->isHandling($record)) {
  470. return true;
  471. }
  472. }
  473. return false;
  474. }
  475. /**
  476. * Set a custom exception handler that will be called if adding a new record fails
  477. *
  478. * The callable will receive an exception object and the record that failed to be logged
  479. */
  480. public function setExceptionHandler(?callable $callback): self
  481. {
  482. $this->exceptionHandler = $callback;
  483. return $this;
  484. }
  485. public function getExceptionHandler(): ?callable
  486. {
  487. return $this->exceptionHandler;
  488. }
  489. /**
  490. * Adds a log record at an arbitrary level.
  491. *
  492. * This method allows for compatibility with common interfaces.
  493. *
  494. * @param mixed $level The log level (a Monolog, PSR-3 or RFC 5424 level)
  495. * @param string|Stringable $message The log message
  496. * @param mixed[] $context The log context
  497. *
  498. * @phpstan-param Level|LevelName|LogLevel::* $level
  499. */
  500. public function log($level, $message, array $context = []): void
  501. {
  502. if (!is_int($level) && !is_string($level)) {
  503. throw new \InvalidArgumentException('$level is expected to be a string or int');
  504. }
  505. if (isset(self::RFC_5424_LEVELS[$level])) {
  506. $level = self::RFC_5424_LEVELS[$level];
  507. }
  508. $level = static::toMonologLevel($level);
  509. $this->addRecord($level, (string) $message, $context);
  510. }
  511. /**
  512. * Adds a log record at the DEBUG level.
  513. *
  514. * This method allows for compatibility with common interfaces.
  515. *
  516. * @param string|Stringable $message The log message
  517. * @param mixed[] $context The log context
  518. */
  519. public function debug($message, array $context = []): void
  520. {
  521. $this->addRecord(static::DEBUG, (string) $message, $context);
  522. }
  523. /**
  524. * Adds a log record at the INFO level.
  525. *
  526. * This method allows for compatibility with common interfaces.
  527. *
  528. * @param string|Stringable $message The log message
  529. * @param mixed[] $context The log context
  530. */
  531. public function info($message, array $context = []): void
  532. {
  533. $this->addRecord(static::INFO, (string) $message, $context);
  534. }
  535. /**
  536. * Adds a log record at the NOTICE level.
  537. *
  538. * This method allows for compatibility with common interfaces.
  539. *
  540. * @param string|Stringable $message The log message
  541. * @param mixed[] $context The log context
  542. */
  543. public function notice($message, array $context = []): void
  544. {
  545. $this->addRecord(static::NOTICE, (string) $message, $context);
  546. }
  547. /**
  548. * Adds a log record at the WARNING level.
  549. *
  550. * This method allows for compatibility with common interfaces.
  551. *
  552. * @param string|Stringable $message The log message
  553. * @param mixed[] $context The log context
  554. */
  555. public function warning($message, array $context = []): void
  556. {
  557. $this->addRecord(static::WARNING, (string) $message, $context);
  558. }
  559. /**
  560. * Adds a log record at the ERROR level.
  561. *
  562. * This method allows for compatibility with common interfaces.
  563. *
  564. * @param string|Stringable $message The log message
  565. * @param mixed[] $context The log context
  566. */
  567. public function error($message, array $context = []): void
  568. {
  569. $this->addRecord(static::ERROR, (string) $message, $context);
  570. }
  571. /**
  572. * Adds a log record at the CRITICAL level.
  573. *
  574. * This method allows for compatibility with common interfaces.
  575. *
  576. * @param string|Stringable $message The log message
  577. * @param mixed[] $context The log context
  578. */
  579. public function critical($message, array $context = []): void
  580. {
  581. $this->addRecord(static::CRITICAL, (string) $message, $context);
  582. }
  583. /**
  584. * Adds a log record at the ALERT level.
  585. *
  586. * This method allows for compatibility with common interfaces.
  587. *
  588. * @param string|Stringable $message The log message
  589. * @param mixed[] $context The log context
  590. */
  591. public function alert($message, array $context = []): void
  592. {
  593. $this->addRecord(static::ALERT, (string) $message, $context);
  594. }
  595. /**
  596. * Adds a log record at the EMERGENCY level.
  597. *
  598. * This method allows for compatibility with common interfaces.
  599. *
  600. * @param string|Stringable $message The log message
  601. * @param mixed[] $context The log context
  602. */
  603. public function emergency($message, array $context = []): void
  604. {
  605. $this->addRecord(static::EMERGENCY, (string) $message, $context);
  606. }
  607. /**
  608. * Sets the timezone to be used for the timestamp of log records.
  609. */
  610. public function setTimezone(DateTimeZone $tz): self
  611. {
  612. $this->timezone = $tz;
  613. return $this;
  614. }
  615. /**
  616. * Returns the timezone to be used for the timestamp of log records.
  617. */
  618. public function getTimezone(): DateTimeZone
  619. {
  620. return $this->timezone;
  621. }
  622. /**
  623. * Delegates exception management to the custom exception handler,
  624. * or throws the exception if no custom handler is set.
  625. *
  626. * @param array $record
  627. * @phpstan-param Record $record
  628. */
  629. protected function handleException(Throwable $e, array $record): void
  630. {
  631. if (!$this->exceptionHandler) {
  632. throw $e;
  633. }
  634. ($this->exceptionHandler)($e, $record);
  635. }
  636. /**
  637. * @return array<string, mixed>
  638. */
  639. public function __serialize(): array
  640. {
  641. return [
  642. 'name' => $this->name,
  643. 'handlers' => $this->handlers,
  644. 'processors' => $this->processors,
  645. 'microsecondTimestamps' => $this->microsecondTimestamps,
  646. 'timezone' => $this->timezone,
  647. 'exceptionHandler' => $this->exceptionHandler,
  648. 'logDepth' => $this->logDepth,
  649. 'detectCycles' => $this->detectCycles,
  650. ];
  651. }
  652. /**
  653. * @param array<string, mixed> $data
  654. */
  655. public function __unserialize(array $data): void
  656. {
  657. foreach (['name', 'handlers', 'processors', 'microsecondTimestamps', 'timezone', 'exceptionHandler', 'logDepth', 'detectCycles'] as $property) {
  658. if (isset($data[$property])) {
  659. $this->$property = $data[$property];
  660. }
  661. }
  662. if (\PHP_VERSION_ID >= 80100) {
  663. // Local variable for phpstan, see https://github.com/phpstan/phpstan/issues/6732#issuecomment-1111118412
  664. /** @var \WeakMap<\Fiber<mixed, mixed, mixed, mixed>, int> $fiberLogDepth */
  665. $fiberLogDepth = new \WeakMap();
  666. $this->fiberLogDepth = $fiberLogDepth;
  667. }
  668. }
  669. }