* @param string $name The logging channel, a simple descriptive name that is attached to all log records
* @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
* @param callable[] $processors Optional array of processors
* @param DateTimeZone|null $timezone Optional timezone, if not provided date_default_timezone_get() will be used
*/
public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone = null)
{
$this->name = $name;
$this->setHandlers($handlers);
$this->processors = $processors;
$this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC');
}
public function getName(): string
{
return $this->name;
}
/**
* Return a new cloned instance with the name changed
*/
public function withName(string $name): self
{
$new = clone $this;
$new->name = $name;
return $new;
}
/**
* Pushes a handler on to the stack.
*/
public function pushHandler(HandlerInterface $handler): self
{
array_unshift($this->handlers, $handler);
return $this;
}
/**
* Pops a handler from the stack
*
* @throws \LogicException If empty handler stack
*/
public function popHandler(): HandlerInterface
{
if (!$this->handlers) {
throw new \LogicException('You tried to pop from an empty handler stack.');
}
return array_shift($this->handlers);
}
/**
* Set handlers, replacing all existing ones.
*
* If a map is passed, keys will be ignored.
*
* @param HandlerInterface[] $handlers
*/
public function setHandlers(array $handlers): self
{
$this->handlers = [];
foreach (array_reverse($handlers) as $handler) {
$this->pushHandler($handler);
}
return $this;
}
/**
* @return HandlerInterface[]
*/
public function getHandlers(): array
{
return $this->handlers;
}
/**
* Adds a processor on to the stack.
*/
public function pushProcessor(callable $callback): self
{
array_unshift($this->processors, $callback);
return $this;
}
/**
* Removes the processor on top of the stack and returns it.
*
* @throws \LogicException If empty processor stack
* @return callable
*/
public function popProcessor(): callable
{
if (!$this->processors) {
throw new \LogicException('You tried to pop from an empty processor stack.');
}
return array_shift($this->processors);
}
/**
* @return callable[]
*/
public function getProcessors(): array
{
return $this->processors;
}
/**
* Control the use of microsecond resolution timestamps in the 'datetime'
* member of new records.
*
* As of PHP7.1 microseconds are always included by the engine, so
* there is no performance penalty and Monolog 2 enabled microseconds
* by default. This function lets you disable them though in case you want
* to suppress microseconds from the output.
*
* @param bool $micro True to use microtime() to create timestamps
*/
public function useMicrosecondTimestamps(bool $micro): self
{
$this->microsecondTimestamps = $micro;
return $this;
}
public function useLoggingLoopDetection(bool $detectCycles): self
{
$this->detectCycles = $detectCycles;
return $this;
}
/**
* Adds a log record.
*
* @param int $level The logging level
* @param string $message The log message
* @param mixed[] $context The log context
* @param DateTimeImmutable $datetime Optional log date to log into the past or future
* @return bool Whether the record has been processed
*
* @phpstan-param Level $level
*/
public function addRecord(int $level, string $message, array $context = [], DateTimeImmutable $datetime = null): bool
{
if ($this->detectCycles) {
$this->logDepth += 1;
}
if ($this->logDepth === 3) {
$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.');
return false;
} elseif ($this->logDepth >= 5) { // log depth 4 is let through so we can log the warning above
return false;
}
try {
$record = null;
foreach ($this->handlers as $handler) {
if (null === $record) {
// skip creating the record as long as no handler is going to handle it
if (!$handler->isHandling(['level' => $level])) {
continue;
}
$levelName = static::getLevelName($level);
$record = [
'message' => $message,
'context' => $context,
'level' => $level,
'level_name' => $levelName,
'channel' => $this->name,
'datetime' => $datetime ?? new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
'extra' => [],
];
try {
foreach ($this->processors as $processor) {
$record = $processor($record);
}
} catch (Throwable $e) {
$this->handleException($e, $record);
return true;
}
}
// once the record exists, send it to all handlers as long as the bubbling chain is not interrupted
try {
if (true === $handler->handle($record)) {
break;
}
} catch (Throwable $e) {
$this->handleException($e, $record);
return true;
}
}
} finally {
if ($this->detectCycles) {
$this->logDepth--;
}
}
return null !== $record;
}
/**
* Ends a log cycle and frees all resources used by handlers.
*
* Closing a Handler means flushing all buffers and freeing any open resources/handles.
* Handlers that have been closed should be able to accept log records again and re-open
* themselves on demand, but this may not always be possible depending on implementation.
*
* This is useful at the end of a request and will be called automatically on every handler
* when they get destructed.
*/
public function close(): void
{
foreach ($this->handlers as $handler) {
$handler->close();
}
}
/**
* Ends a log cycle and resets all handlers and processors to their initial state.
*
* Resetting a Handler or a Processor means flushing/cleaning all buffers, resetting internal
* state, and getting it back to a state in which it can receive log records again.
*
* This is useful in case you want to avoid logs leaking between two requests or jobs when you
* have a long running process like a worker or an application server serving multiple requests
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels));
}
if (!is_int($level)) {
throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', array_keys(static::$levels) + static::$levels));
}
return $level;
}
/**
* Checks whether the Logger has a handler that listens on the given level
*
* @phpstan-param Level $level
*/
public function isHandling(int $level): bool
{
$record = [
'level' => $level,
];
foreach ($this->handlers as $handler) {
if ($handler->isHandling($record)) {
return true;
}
}
return false;
}
/**
* Set a custom exception handler that will be called if adding a new record fails
*
* The callable will receive an exception object and the record that failed to be logged
*/
public function setExceptionHandler(?callable $callback): self
{
$this->exceptionHandler = $callback;
return $this;
}
public function getExceptionHandler(): ?callable
{
return $this->exceptionHandler;
}
/**
* Adds a log record at an arbitrary level.
*
* This method allows for compatibility with common interfaces.
*
* @param mixed $level The log level
* @param string|Stringable $message The log message