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

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