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

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 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.      * @return static
  168.      */
  169.     public function withName(string $name): self
  170.     {
  171.         $new = clone $this;
  172.         $new->name $name;
  173.         return $new;
  174.     }
  175.     /**
  176.      * Pushes a handler on to the stack.
  177.      *
  178.      * @return $this
  179.      */
  180.     public function pushHandler(HandlerInterface $handler): self
  181.     {
  182.         array_unshift($this->handlers$handler);
  183.         return $this;
  184.     }
  185.     /**
  186.      * Pops a handler from the stack
  187.      *
  188.      * @throws \LogicException If empty handler stack
  189.      */
  190.     public function popHandler(): HandlerInterface
  191.     {
  192.         if (=== \count($this->handlers)) {
  193.             throw new \LogicException('You tried to pop from an empty handler stack.');
  194.         }
  195.         return array_shift($this->handlers);
  196.     }
  197.     /**
  198.      * Set handlers, replacing all existing ones.
  199.      *
  200.      * If a map is passed, keys will be ignored.
  201.      *
  202.      * @param list<HandlerInterface> $handlers
  203.      * @return $this
  204.      */
  205.     public function setHandlers(array $handlers): self
  206.     {
  207.         $this->handlers = [];
  208.         foreach (array_reverse($handlers) as $handler) {
  209.             $this->pushHandler($handler);
  210.         }
  211.         return $this;
  212.     }
  213.     /**
  214.      * @return list<HandlerInterface>
  215.      */
  216.     public function getHandlers(): array
  217.     {
  218.         return $this->handlers;
  219.     }
  220.     /**
  221.      * Adds a processor on to the stack.
  222.      *
  223.      * @phpstan-param ProcessorInterface|(callable(LogRecord): LogRecord) $callback
  224.      * @return $this
  225.      */
  226.     public function pushProcessor(ProcessorInterface|callable $callback): self
  227.     {
  228.         array_unshift($this->processors$callback);
  229.         return $this;
  230.     }
  231.     /**
  232.      * Removes the processor on top of the stack and returns it.
  233.      *
  234.      * @phpstan-return ProcessorInterface|(callable(LogRecord): LogRecord)
  235.      * @throws \LogicException If empty processor stack
  236.      */
  237.     public function popProcessor(): callable
  238.     {
  239.         if (=== \count($this->processors)) {
  240.             throw new \LogicException('You tried to pop from an empty processor stack.');
  241.         }
  242.         return array_shift($this->processors);
  243.     }
  244.     /**
  245.      * @return callable[]
  246.      * @phpstan-return array<ProcessorInterface|(callable(LogRecord): LogRecord)>
  247.      */
  248.     public function getProcessors(): array
  249.     {
  250.         return $this->processors;
  251.     }
  252.     /**
  253.      * Control the use of microsecond resolution timestamps in the 'datetime'
  254.      * member of new records.
  255.      *
  256.      * As of PHP7.1 microseconds are always included by the engine, so
  257.      * there is no performance penalty and Monolog 2 enabled microseconds
  258.      * by default. This function lets you disable them though in case you want
  259.      * to suppress microseconds from the output.
  260.      *
  261.      * @param bool $micro True to use microtime() to create timestamps
  262.      * @return $this
  263.      */
  264.     public function useMicrosecondTimestamps(bool $micro): self
  265.     {
  266.         $this->microsecondTimestamps $micro;
  267.         return $this;
  268.     }
  269.     /**
  270.      * @return $this
  271.      */
  272.     public function useLoggingLoopDetection(bool $detectCycles): self
  273.     {
  274.         $this->detectCycles $detectCycles;
  275.         return $this;
  276.     }
  277.     /**
  278.      * Adds a log record.
  279.      *
  280.      * @param  int                    $level    The logging level (a Monolog or RFC 5424 level)
  281.      * @param  string                 $message  The log message
  282.      * @param  mixed[]                $context  The log context
  283.      * @param  DateTimeImmutable|null $datetime Optional log date to log into the past or future
  284.      * @return bool                   Whether the record has been processed
  285.      *
  286.      * @phpstan-param value-of<Level::VALUES>|Level $level
  287.      */
  288.     public function addRecord(int|Level $levelstring $message, array $context = [], DateTimeImmutable|null $datetime null): bool
  289.     {
  290.         if (is_int($level) && isset(self::RFC_5424_LEVELS[$level])) {
  291.             $level self::RFC_5424_LEVELS[$level];
  292.         }
  293.         if ($this->detectCycles) {
  294.             if (null !== ($fiber Fiber::getCurrent())) {
  295.                 $logDepth $this->fiberLogDepth[$fiber] = ($this->fiberLogDepth[$fiber] ?? 0) + 1;
  296.             } else {
  297.                 $logDepth = ++$this->logDepth;
  298.             }
  299.         } else {
  300.             $logDepth 0;
  301.         }
  302.         if ($logDepth === 3) {
  303.             $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.');
  304.             return false;
  305.         } elseif ($logDepth >= 5) { // log depth 4 is let through, so we can log the warning above
  306.             return false;
  307.         }
  308.         try {
  309.             $recordInitialized count($this->processors) === 0;
  310.             $record = new LogRecord(
  311.                 datetime$datetime ?? new DateTimeImmutable($this->microsecondTimestamps$this->timezone),
  312.                 channel$this->name,
  313.                 levelself::toMonologLevel($level),
  314.                 message$message,
  315.                 context$context,
  316.                 extra: [],
  317.             );
  318.             $handled false;
  319.             foreach ($this->handlers as $handler) {
  320.                 if (false === $recordInitialized) {
  321.                     // skip initializing the record as long as no handler is going to handle it
  322.                     if (!$handler->isHandling($record)) {
  323.                         continue;
  324.                     }
  325.                     try {
  326.                         foreach ($this->processors as $processor) {
  327.                             $record $processor($record);
  328.                         }
  329.                         $recordInitialized true;
  330.                     } catch (Throwable $e) {
  331.                         $this->handleException($e$record);
  332.                         return true;
  333.                     }
  334.                 }
  335.                 // once the record is initialized, send it to all handlers as long as the bubbling chain is not interrupted
  336.                 try {
  337.                     $handled true;
  338.                     if (true === $handler->handle(clone $record)) {
  339.                         break;
  340.                     }
  341.                 } catch (Throwable $e) {
  342.                     $this->handleException($e$record);
  343.                     return true;
  344.                 }
  345.             }
  346.             return $handled;
  347.         } finally {
  348.             if ($this->detectCycles) {
  349.                 if (isset($fiber)) {
  350.                     $this->fiberLogDepth[$fiber]--;
  351.                 } else {
  352.                     $this->logDepth--;
  353.                 }
  354.             }
  355.         }
  356.     }
  357.     /**
  358.      * Ends a log cycle and frees all resources used by handlers.
  359.      *
  360.      * Closing a Handler means flushing all buffers and freeing any open resources/handles.
  361.      * Handlers that have been closed should be able to accept log records again and re-open
  362.      * themselves on demand, but this may not always be possible depending on implementation.
  363.      *
  364.      * This is useful at the end of a request and will be called automatically on every handler
  365.      * when they get destructed.
  366.      */
  367.     public function close(): void
  368.     {
  369.         foreach ($this->handlers as $handler) {
  370.             $handler->close();
  371.         }
  372.     }
  373.     /**
  374.      * Ends a log cycle and resets all handlers and processors to their initial state.
  375.      *
  376.      * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
  377.      * state, and getting it back to a state in which it can receive log records again.
  378.      *
  379.      * This is useful in case you want to avoid logs leaking between two requests or jobs when you
  380.      * have a long running process like a worker or an application server serving multiple requests
  381.      * in one process.
  382.      */
  383.     public function reset(): void
  384.     {
  385.         foreach ($this->handlers as $handler) {
  386.             if ($handler instanceof ResettableInterface) {
  387.                 $handler->reset();
  388.             }
  389.         }
  390.         foreach ($this->processors as $processor) {
  391.             if ($processor instanceof ResettableInterface) {
  392.                 $processor->reset();
  393.             }
  394.         }
  395.     }
  396.     /**
  397.      * Gets the name of the logging level as a string.
  398.      *
  399.      * This still returns a string instead of a Level for BC, but new code should not rely on this method.
  400.      *
  401.      * @throws \Psr\Log\InvalidArgumentException If level is not defined
  402.      *
  403.      * @phpstan-param  value-of<Level::VALUES>|Level $level
  404.      * @phpstan-return value-of<Level::NAMES>
  405.      *
  406.      * @deprecated Since 3.0, use {@see toMonologLevel} or {@see \Monolog\Level->getName()} instead
  407.      */
  408.     public static function getLevelName(int|Level $level): string
  409.     {
  410.         return self::toMonologLevel($level)->getName();
  411.     }
  412.     /**
  413.      * Converts PSR-3 levels to Monolog ones if necessary
  414.      *
  415.      * @param  int|string|Level|LogLevel::* $level Level number (monolog) or name (PSR-3)
  416.      * @throws \Psr\Log\InvalidArgumentException      If level is not defined
  417.      *
  418.      * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
  419.      */
  420.     public static function toMonologLevel(string|int|Level $level): Level
  421.     {
  422.         if ($level instanceof Level) {
  423.             return $level;
  424.         }
  425.         if (\is_string($level)) {
  426.             if (\is_numeric($level)) {
  427.                 $levelEnum Level::tryFrom((int) $level);
  428.                 if ($levelEnum === null) {
  429.                     throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', 'Level::NAMES Level::VALUES));
  430.                 }
  431.                 return $levelEnum;
  432.             }
  433.             // Contains first char of all log levels and avoids using strtoupper() which may have
  434.             // strange results depending on locale (for example, "i" will become "İ" in Turkish locale)
  435.             $upper strtr(substr($level01), 'dinweca''DINWECA') . strtolower(substr($level1));
  436.             if (defined(Level::class.'::'.$upper)) {
  437.                 return constant(Level::class . '::' $upper);
  438.             }
  439.             throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', 'Level::NAMES Level::VALUES));
  440.         }
  441.         $levelEnum Level::tryFrom($level);
  442.         if ($levelEnum === null) {
  443.             throw new InvalidArgumentException('Level "'.var_export($leveltrue).'" is not defined, use one of: '.implode(', 'Level::NAMES Level::VALUES));
  444.         }
  445.         return $levelEnum;
  446.     }
  447.     /**
  448.      * Checks whether the Logger has a handler that listens on the given level
  449.      *
  450.      * @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
  451.      */
  452.     public function isHandling(int|string|Level $level): bool
  453.     {
  454.         $record = new LogRecord(
  455.             datetime: new DateTimeImmutable($this->microsecondTimestamps$this->timezone),
  456.             channel$this->name,
  457.             message'',
  458.             levelself::toMonologLevel($level),
  459.         );
  460.         foreach ($this->handlers as $handler) {
  461.             if ($handler->isHandling($record)) {
  462.                 return true;
  463.             }
  464.         }
  465.         return false;
  466.     }
  467.     /**
  468.      * Set a custom exception handler that will be called if adding a new record fails
  469.      *
  470.      * The Closure will receive an exception object and the record that failed to be logged
  471.      *
  472.      * @return $this
  473.      */
  474.     public function setExceptionHandler(Closure|null $callback): self
  475.     {
  476.         $this->exceptionHandler $callback;
  477.         return $this;
  478.     }
  479.     public function getExceptionHandler(): Closure|null
  480.     {
  481.         return $this->exceptionHandler;
  482.     }
  483.     /**
  484.      * Adds a log record at an arbitrary level.
  485.      *
  486.      * This method allows for compatibility with common interfaces.
  487.      *
  488.      * @param mixed             $level   The log level (a Monolog, PSR-3 or RFC 5424 level)
  489.      * @param string|Stringable $message The log message
  490.      * @param mixed[]           $context The log context
  491.      *
  492.      * @phpstan-param Level|LogLevel::* $level
  493.      */
  494.     public function log($levelstring|\Stringable $message, array $context = []): void
  495.     {
  496.         if (!$level instanceof Level) {
  497.             if (!is_string($level) && !is_int($level)) {
  498.                 throw new \InvalidArgumentException('$level is expected to be a string, int or '.Level::class.' instance');
  499.             }
  500.             if (isset(self::RFC_5424_LEVELS[$level])) {
  501.                 $level self::RFC_5424_LEVELS[$level];
  502.             }
  503.             $level = static::toMonologLevel($level);
  504.         }
  505.         $this->addRecord($level, (string) $message$context);
  506.     }
  507.     /**
  508.      * Adds a log record at the DEBUG 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 debug(string|\Stringable $message, array $context = []): void
  516.     {
  517.         $this->addRecord(Level::Debug, (string) $message$context);
  518.     }
  519.     /**
  520.      * Adds a log record at the INFO 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 info(string|\Stringable $message, array $context = []): void
  528.     {
  529.         $this->addRecord(Level::Info, (string) $message$context);
  530.     }
  531.     /**
  532.      * Adds a log record at the NOTICE 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 notice(string|\Stringable $message, array $context = []): void
  540.     {
  541.         $this->addRecord(Level::Notice, (string) $message$context);
  542.     }
  543.     /**
  544.      * Adds a log record at the WARNING 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 warning(string|\Stringable $message, array $context = []): void
  552.     {
  553.         $this->addRecord(Level::Warning, (string) $message$context);
  554.     }
  555.     /**
  556.      * Adds a log record at the ERROR 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 error(string|\Stringable $message, array $context = []): void
  564.     {
  565.         $this->addRecord(Level::Error, (string) $message$context);
  566.     }
  567.     /**
  568.      * Adds a log record at the CRITICAL 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 critical(string|\Stringable $message, array $context = []): void
  576.     {
  577.         $this->addRecord(Level::Critical, (string) $message$context);
  578.     }
  579.     /**
  580.      * Adds a log record at the ALERT 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 alert(string|\Stringable $message, array $context = []): void
  588.     {
  589.         $this->addRecord(Level::Alert, (string) $message$context);
  590.     }
  591.     /**
  592.      * Adds a log record at the EMERGENCY level.
  593.      *
  594.      * This method allows for compatibility with common interfaces.
  595.      *
  596.      * @param string|Stringable $message The log message
  597.      * @param mixed[]           $context The log context
  598.      */
  599.     public function emergency(string|\Stringable $message, array $context = []): void
  600.     {
  601.         $this->addRecord(Level::Emergency, (string) $message$context);
  602.     }
  603.     /**
  604.      * Sets the timezone to be used for the timestamp of log records.
  605.      *
  606.      * @return $this
  607.      */
  608.     public function setTimezone(DateTimeZone $tz): self
  609.     {
  610.         $this->timezone $tz;
  611.         return $this;
  612.     }
  613.     /**
  614.      * Returns the timezone to be used for the timestamp of log records.
  615.      */
  616.     public function getTimezone(): DateTimeZone
  617.     {
  618.         return $this->timezone;
  619.     }
  620.     /**
  621.      * Delegates exception management to the custom exception handler,
  622.      * or throws the exception if no custom handler is set.
  623.      */
  624.     protected function handleException(Throwable $eLogRecord $record): void
  625.     {
  626.         if (null === $this->exceptionHandler) {
  627.             throw $e;
  628.         }
  629.         ($this->exceptionHandler)($e$record);
  630.     }
  631.     /**
  632.      * @return array<string, mixed>
  633.      */
  634.     public function __serialize(): array
  635.     {
  636.         return [
  637.             'name' => $this->name,
  638.             'handlers' => $this->handlers,
  639.             'processors' => $this->processors,
  640.             'microsecondTimestamps' => $this->microsecondTimestamps,
  641.             'timezone' => $this->timezone,
  642.             'exceptionHandler' => $this->exceptionHandler,
  643.             'logDepth' => $this->logDepth,
  644.             'detectCycles' => $this->detectCycles,
  645.         ];
  646.     }
  647.     /**
  648.      * @param array<string, mixed> $data
  649.      */
  650.     public function __unserialize(array $data): void
  651.     {
  652.         foreach (['name''handlers''processors''microsecondTimestamps''timezone''exceptionHandler''logDepth''detectCycles'] as $property) {
  653.             if (isset($data[$property])) {
  654.                 $this->$property $data[$property];
  655.             }
  656.         }
  657.         $this->fiberLogDepth = new \WeakMap();
  658.     }
  659. }