vendor/monolog/monolog/src/Monolog/Logger.php line 663

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