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

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 bool Whether to detect infinite logging loops
  151.      *
  152.      * This can be disabled via {@see useLoggingLoopDetection} if you have async handlers that do not play well with this
  153.      */
  154.     private $detectCycles true;
  155.     /**
  156.      * @psalm-param array<callable(array): array> $processors
  157.      *
  158.      * @param string             $name       The logging channel, a simple descriptive name that is attached to all log records
  159.      * @param HandlerInterface[] $handlers   Optional stack of handlers, the first one in the array is called first, etc.
  160.      * @param callable[]         $processors Optional array of processors
  161.      * @param DateTimeZone|null  $timezone   Optional timezone, if not provided date_default_timezone_get() will be used
  162.      */
  163.     public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone null)
  164.     {
  165.         $this->name $name;
  166.         $this->setHandlers($handlers);
  167.         $this->processors $processors;
  168.         $this->timezone $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC');
  169.     }
  170.     public function getName(): string
  171.     {
  172.         return $this->name;
  173.     }
  174.     /**
  175.      * Return a new cloned instance with the name changed
  176.      */
  177.     public function withName(string $name): self
  178.     {
  179.         $new = clone $this;
  180.         $new->name $name;
  181.         return $new;
  182.     }
  183.     /**
  184.      * Pushes a handler on to the stack.
  185.      */
  186.     public function pushHandler(HandlerInterface $handler): self
  187.     {
  188.         array_unshift($this->handlers$handler);
  189.         return $this;
  190.     }
  191.     /**
  192.      * Pops a handler from the stack
  193.      *
  194.      * @throws \LogicException If empty handler stack
  195.      */
  196.     public function popHandler(): HandlerInterface
  197.     {
  198.         if (!$this->handlers) {
  199.             throw new \LogicException('You tried to pop from an empty handler stack.');
  200.         }
  201.         return array_shift($this->handlers);
  202.     }
  203.     /**
  204.      * Set handlers, replacing all existing ones.
  205.      *
  206.      * If a map is passed, keys will be ignored.
  207.      *
  208.      * @param HandlerInterface[] $handlers
  209.      */
  210.     public function setHandlers(array $handlers): self
  211.     {
  212.         $this->handlers = [];
  213.         foreach (array_reverse($handlers) as $handler) {
  214.             $this->pushHandler($handler);
  215.         }
  216.         return $this;
  217.     }
  218.     /**
  219.      * @return HandlerInterface[]
  220.      */
  221.     public function getHandlers(): array
  222.     {
  223.         return $this->handlers;
  224.     }
  225.     /**
  226.      * Adds a processor on to the stack.
  227.      */
  228.     public function pushProcessor(callable $callback): self
  229.     {
  230.         array_unshift($this->processors$callback);
  231.         return $this;
  232.     }
  233.     /**
  234.      * Removes the processor on top of the stack and returns it.
  235.      *
  236.      * @throws \LogicException If empty processor stack
  237.      * @return callable
  238.      */
  239.     public function popProcessor(): callable
  240.     {
  241.         if (!$this->processors) {
  242.             throw new \LogicException('You tried to pop from an empty processor stack.');
  243.         }
  244.         return array_shift($this->processors);
  245.     }
  246.     /**
  247.      * @return callable[]
  248.      */
  249.     public function getProcessors(): array
  250.     {
  251.         return $this->processors;
  252.     }
  253.     /**
  254.      * Control the use of microsecond resolution timestamps in the 'datetime'
  255.      * member of new records.
  256.      *
  257.      * As of PHP7.1 microseconds are always included by the engine, so
  258.      * there is no performance penalty and Monolog 2 enabled microseconds
  259.      * by default. This function lets you disable them though in case you want
  260.      * to suppress microseconds from the output.
  261.      *
  262.      * @param bool $micro True to use microtime() to create timestamps
  263.      */
  264.     public function useMicrosecondTimestamps(bool $micro): self
  265.     {
  266.         $this->microsecondTimestamps $micro;
  267.         return $this;
  268.     }
  269.     public function useLoggingLoopDetection(bool $detectCycles): self
  270.     {
  271.         $this->detectCycles $detectCycles;
  272.         return $this;
  273.     }
  274.     /**
  275.      * Adds a log record.
  276.      *
  277.      * @param  int               $level    The logging level (a Monolog or RFC 5424 level)
  278.      * @param  string            $message  The log message
  279.      * @param  mixed[]           $context  The log context
  280.      * @param  DateTimeImmutable $datetime Optional log date to log into the past or future
  281.      * @return bool              Whether the record has been processed
  282.      *
  283.      * @phpstan-param Level $level
  284.      */
  285.     public function addRecord(int $levelstring $message, array $context = [], DateTimeImmutable $datetime null): bool
  286.     {
  287.         if (isset(self::RFC_5424_LEVELS[$level])) {
  288.             $level self::RFC_5424_LEVELS[$level];
  289.         }
  290.         if ($this->detectCycles) {
  291.             $this->logDepth += 1;
  292.         }
  293.         if ($this->logDepth === 3) {
  294.             $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.');
  295.             return false;
  296.         } elseif ($this->logDepth >= 5) { // log depth 4 is let through so we can log the warning above
  297.             return false;
  298.         }
  299.         try {
  300.             $record null;
  301.             foreach ($this->handlers as $handler) {
  302.                 if (null === $record) {
  303.                     // skip creating the record as long as no handler is going to handle it
  304.                     if (!$handler->isHandling(['level' => $level])) {
  305.                         continue;
  306.                     }
  307.                     $levelName = static::getLevelName($level);
  308.                     $record = [
  309.                         'message' => $message,
  310.                         'context' => $context,
  311.                         'level' => $level,
  312.                         'level_name' => $levelName,
  313.                         'channel' => $this->name,
  314.                         'datetime' => $datetime ?? new DateTimeImmutable($this->microsecondTimestamps$this->timezone),
  315.                         'extra' => [],
  316.                     ];
  317.                     try {
  318.                         foreach ($this->processors as $processor) {
  319.                             $record $processor($record);
  320.                         }
  321.                     } catch (Throwable $e) {
  322.                         $this->handleException($e$record);
  323.                         return true;
  324.                     }
  325.                 }
  326.                 // once the record exists, send it to all handlers as long as the bubbling chain is not interrupted
  327.                 try {
  328.                     if (true === $handler->handle($record)) {
  329.                         break;
  330.                     }
  331.                 } catch (Throwable $e) {
  332.                     $this->handleException($e$record);
  333.                     return true;
  334.                 }
  335.             }
  336.         } finally {
  337.             if ($this->detectCycles) {
  338.                 $this->logDepth--;
  339.             }
  340.         }
  341.         return null !== $record;
  342.     }
  343.     /**
  344.      * Ends a log cycle and frees all resources used by handlers.
  345.      *
  346.      * Closing a Handler means flushing all buffers and freeing any open resources/handles.
  347.      * Handlers that have been closed should be able to accept log records again and re-open
  348.      * themselves on demand, but this may not always be possible depending on implementation.
  349.      *
  350.      * This is useful at the end of a request and will be called automatically on every handler
  351.      * when they get destructed.
  352.      */
  353.     public function close(): void
  354.     {
  355.         foreach ($this->handlers as $handler) {
  356.             $handler->close();
  357.         }
  358.     }
  359.     /**
  360.      * Ends a log cycle and resets all handlers and processors to their initial state.
  361.      *
  362.      * Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
  363.      * state, and getting it back to a state in which it can receive log records again.
  364.      *
  365.      * This is useful in case you want to avoid logs leaking between two requests or jobs when you
  366.      * have a long running process like a worker or an application server serving multiple requests
  367.      * in one process.
  368.      */
  369.     public function reset(): void
  370.     {
  371.         foreach ($this->handlers as $handler) {
  372.             if ($handler instanceof ResettableInterface) {
  373.                 $handler->reset();
  374.             }
  375.         }
  376.         foreach ($this->processors as $processor) {
  377.             if ($processor instanceof ResettableInterface) {
  378.                 $processor->reset();
  379.             }
  380.         }
  381.     }
  382.     /**
  383.      * Gets all supported logging levels.
  384.      *
  385.      * @return array<string, int> Assoc array with human-readable level names => level codes.
  386.      * @phpstan-return array<LevelName, Level>
  387.      */
  388.     public static function getLevels(): array
  389.     {
  390.         return array_flip(static::$levels);
  391.     }
  392.     /**
  393.      * Gets the name of the logging level.
  394.      *
  395.      * @throws \Psr\Log\InvalidArgumentException If level is not defined
  396.      *
  397.      * @phpstan-param  Level     $level
  398.      * @phpstan-return LevelName
  399.      */
  400.     public static function getLevelName(int $level): string
  401.     {
  402.         if (!isset(static::$levels[$level])) {
  403.             throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', 'array_keys(static::$levels)));
  404.         }
  405.         return static::$levels[$level];
  406.     }
  407.     /**
  408.      * Converts PSR-3 levels to Monolog ones if necessary
  409.      *
  410.      * @param  string|int                        $level Level number (monolog) or name (PSR-3)
  411.      * @throws \Psr\Log\InvalidArgumentException If level is not defined
  412.      *
  413.      * @phpstan-param  Level|LevelName|LogLevel::* $level
  414.      * @phpstan-return Level
  415.      */
  416.     public static function toMonologLevel($level): int
  417.     {
  418.         if (is_string($level)) {
  419.             if (is_numeric($level)) {
  420.                 /** @phpstan-ignore-next-line */
  421.                 return intval($level);
  422.             }
  423.             // Contains chars 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($level'abcdefgilmnortuwy''ABCDEFGILMNORTUWY');
  426.             if (defined(__CLASS__.'::'.$upper)) {
  427.                 return constant(__CLASS__ '::' $upper);
  428.             }
  429.             throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', 'array_keys(static::$levels) + static::$levels));
  430.         }
  431.         if (!is_int($level)) {
  432.             throw new InvalidArgumentException('Level "'.var_export($leveltrue).'" is not defined, use one of: '.implode(', 'array_keys(static::$levels) + static::$levels));
  433.         }
  434.         return $level;
  435.     }
  436.     /**
  437.      * Checks whether the Logger has a handler that listens on the given level
  438.      *
  439.      * @phpstan-param Level $level
  440.      */
  441.     public function isHandling(int $level): bool
  442.     {
  443.         $record = [
  444.             'level' => $level,
  445.         ];
  446.         foreach ($this->handlers as $handler) {
  447.             if ($handler->isHandling($record)) {
  448.                 return true;
  449.             }
  450.         }
  451.         return false;
  452.     }
  453.     /**
  454.      * Set a custom exception handler that will be called if adding a new record fails
  455.      *
  456.      * The callable will receive an exception object and the record that failed to be logged
  457.      */
  458.     public function setExceptionHandler(?callable $callback): self
  459.     {
  460.         $this->exceptionHandler $callback;
  461.         return $this;
  462.     }
  463.     public function getExceptionHandler(): ?callable
  464.     {
  465.         return $this->exceptionHandler;
  466.     }
  467.     /**
  468.      * Adds a log record at an arbitrary level.
  469.      *
  470.      * This method allows for compatibility with common interfaces.
  471.      *
  472.      * @param mixed             $level   The log level (a Monolog, PSR-3 or RFC 5424 level)
  473.      * @param string|Stringable $message The log message
  474.      * @param mixed[]           $context The log context
  475.      *
  476.      * @phpstan-param Level|LevelName|LogLevel::* $level
  477.      */
  478.     public function log($level$message, array $context = []): void
  479.     {
  480.         if (!is_int($level) && !is_string($level)) {
  481.             throw new \InvalidArgumentException('$level is expected to be a string or int');
  482.         }
  483.         if (isset(self::RFC_5424_LEVELS[$level])) {
  484.             $level self::RFC_5424_LEVELS[$level];
  485.         }
  486.         $level = static::toMonologLevel($level);
  487.         $this->addRecord($level, (string) $message$context);
  488.     }
  489.     /**
  490.      * Adds a log record at the DEBUG level.
  491.      *
  492.      * This method allows for compatibility with common interfaces.
  493.      *
  494.      * @param string|Stringable $message The log message
  495.      * @param mixed[]           $context The log context
  496.      */
  497.     public function debug($message, array $context = []): void
  498.     {
  499.         $this->addRecord(static::DEBUG, (string) $message$context);
  500.     }
  501.     /**
  502.      * Adds a log record at the INFO level.
  503.      *
  504.      * This method allows for compatibility with common interfaces.
  505.      *
  506.      * @param string|Stringable $message The log message
  507.      * @param mixed[]           $context The log context
  508.      */
  509.     public function info($message, array $context = []): void
  510.     {
  511.         $this->addRecord(static::INFO, (string) $message$context);
  512.     }
  513.     /**
  514.      * Adds a log record at the NOTICE level.
  515.      *
  516.      * This method allows for compatibility with common interfaces.
  517.      *
  518.      * @param string|Stringable $message The log message
  519.      * @param mixed[]           $context The log context
  520.      */
  521.     public function notice($message, array $context = []): void
  522.     {
  523.         $this->addRecord(static::NOTICE, (string) $message$context);
  524.     }
  525.     /**
  526.      * Adds a log record at the WARNING level.
  527.      *
  528.      * This method allows for compatibility with common interfaces.
  529.      *
  530.      * @param string|Stringable $message The log message
  531.      * @param mixed[]           $context The log context
  532.      */
  533.     public function warning($message, array $context = []): void
  534.     {
  535.         $this->addRecord(static::WARNING, (string) $message$context);
  536.     }
  537.     /**
  538.      * Adds a log record at the ERROR level.
  539.      *
  540.      * This method allows for compatibility with common interfaces.
  541.      *
  542.      * @param string|Stringable $message The log message
  543.      * @param mixed[]           $context The log context
  544.      */
  545.     public function error($message, array $context = []): void
  546.     {
  547.         $this->addRecord(static::ERROR, (string) $message$context);
  548.     }
  549.     /**
  550.      * Adds a log record at the CRITICAL level.
  551.      *
  552.      * This method allows for compatibility with common interfaces.
  553.      *
  554.      * @param string|Stringable $message The log message
  555.      * @param mixed[]           $context The log context
  556.      */
  557.     public function critical($message, array $context = []): void
  558.     {
  559.         $this->addRecord(static::CRITICAL, (string) $message$context);
  560.     }
  561.     /**
  562.      * Adds a log record at the ALERT level.
  563.      *
  564.      * This method allows for compatibility with common interfaces.
  565.      *
  566.      * @param string|Stringable $message The log message
  567.      * @param mixed[]           $context The log context
  568.      */
  569.     public function alert($message, array $context = []): void
  570.     {
  571.         $this->addRecord(static::ALERT, (string) $message$context);
  572.     }
  573.     /**
  574.      * Adds a log record at the EMERGENCY level.
  575.      *
  576.      * This method allows for compatibility with common interfaces.
  577.      *
  578.      * @param string|Stringable $message The log message
  579.      * @param mixed[]           $context The log context
  580.      */
  581.     public function emergency($message, array $context = []): void
  582.     {
  583.         $this->addRecord(static::EMERGENCY, (string) $message$context);
  584.     }
  585.     /**
  586.      * Sets the timezone to be used for the timestamp of log records.
  587.      */
  588.     public function setTimezone(DateTimeZone $tz): self
  589.     {
  590.         $this->timezone $tz;
  591.         return $this;
  592.     }
  593.     /**
  594.      * Returns the timezone to be used for the timestamp of log records.
  595.      */
  596.     public function getTimezone(): DateTimeZone
  597.     {
  598.         return $this->timezone;
  599.     }
  600.     /**
  601.      * Delegates exception management to the custom exception handler,
  602.      * or throws the exception if no custom handler is set.
  603.      *
  604.      * @param array $record
  605.      * @phpstan-param Record $record
  606.      */
  607.     protected function handleException(Throwable $e, array $record): void
  608.     {
  609.         if (!$this->exceptionHandler) {
  610.             throw $e;
  611.         }
  612.         ($this->exceptionHandler)($e$record);
  613.     }
  614. }