Shuu12121/CodeModernBERT-Crow-v3-len1024
Fill-Mask • 0.1B • Updated
• 58
repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
flarum/flarum | https://github.com/flarum/flarum/blob/cc4acfc61fb0f2cf0225de4e7a713a40bffaca69/site.php | site.php | <?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
/*
|-------------------------------------------------------------------------------
| Load the autoloader
|-------------------------------------------------------------------------------
|
| First, let's include the autoloader, which is generated automatically by
| Composer (PHP's package manager) after installing our dependencies.
| From now on, all classes in our dependencies will be usable without
| explicitly loading any files.
|
*/
require __DIR__.'/vendor/autoload.php';
/*
|-------------------------------------------------------------------------------
| Configure the site
|-------------------------------------------------------------------------------
|
| A Flarum site represents your local installation of Flarum. It can be
| configured with a bunch of paths:
|
| - The *base path* is Flarum's root directory and contains important files
| such as config.php and extend.php.
| - The *public path* is the directory that serves as document root for the
| web server. Files in this place are accessible to the public internet.
| This is where assets such as JavaScript files or CSS stylesheets need to
| be stored in a default install.
| - The *storage path* is a place for Flarum to store files it generates during
| runtime. This could be caches, session data or other temporary files.
|
| The fully configured site instance is returned to the including script, which
| then uses it to boot up the Flarum application and e.g. accept web requests.
|
*/
return Flarum\Foundation\Site::fromPaths([
'base' => __DIR__,
'public' => __DIR__.'/public',
'storage' => __DIR__.'/storage',
]);
| php | MIT | cc4acfc61fb0f2cf0225de4e7a713a40bffaca69 | 2026-01-04T15:02:34.473828Z | false |
flarum/flarum | https://github.com/flarum/flarum/blob/cc4acfc61fb0f2cf0225de4e7a713a40bffaca69/extend.php | extend.php | <?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
use Flarum\Extend;
return [
// Register extenders here to customize your forum!
];
| php | MIT | cc4acfc61fb0f2cf0225de4e7a713a40bffaca69 | 2026-01-04T15:02:34.473828Z | false |
flarum/flarum | https://github.com/flarum/flarum/blob/cc4acfc61fb0f2cf0225de4e7a713a40bffaca69/public/index.php | public/index.php | <?php
/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/
$site = require '../site.php';
/*
|-------------------------------------------------------------------------------
| Accept incoming HTTP requests
|-------------------------------------------------------------------------------
|
| Every HTTP request pointed to the web server that cannot be served by simply
| responding with one of the files in the "public" directory will be sent to
| this file. Now is the time to boot up Flarum's internal HTTP server, which
| will try its best to interpret the request and return the appropriate
| response, which could be a JSON document (for API responses) or a lot of HTML.
|
*/
$server = new Flarum\Http\Server($site);
$server->listen();
| php | MIT | cc4acfc61fb0f2cf0225de4e7a713a40bffaca69 | 2026-01-04T15:02:34.473828Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/.php-cs-fixer.php | .php-cs-fixer.php | <?php
$header = <<<EOF
This file is part of the Monolog package.
(c) Jordi Boggiano <j.boggiano@seld.be>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;
$finder = PhpCsFixer\Finder::create()
->files()
->name('*.php')
->exclude('Fixtures')
->in(__DIR__.'/src')
->in(__DIR__.'/tests')
;
$config = new PhpCsFixer\Config();
return $config->setRules(array(
'@PSR2' => true,
// some rules disabled as long as 1.x branch is maintained
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => [
'default' => null,
],
'blank_line_before_statement' => ['statements' => ['continue', 'declare', 'return', 'throw', 'try']],
'cast_spaces' => ['space' => 'single'],
'header_comment' => ['header' => $header],
'include' => true,
'class_attributes_separation' => array('elements' => array('method' => 'one', 'trait_import' => 'none')),
'native_function_invocation' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
'no_empty_statement' => true,
'no_extra_blank_lines' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_superfluous_phpdoc_tags' => ['allow_mixed' => true],
'no_trailing_comma_in_singleline_array' => true,
'no_unused_imports' => true,
'no_whitespace_in_blank_line' => true,
'object_operator_without_whitespace' => true,
'phpdoc_align' => true,
'phpdoc_indent' => true,
'phpdoc_no_access' => true,
'phpdoc_no_package' => true,
'phpdoc_order' => true,
//'phpdoc_scalar' => true,
'phpdoc_trim' => true,
//'phpdoc_types' => true,
'psr_autoloading' => ['dir' => 'src'],
'declare_strict_types' => true,
'single_blank_line_before_namespace' => true,
'standardize_not_equals' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline' => true,
))
->setUsingCache(true)
->setRiskyAllowed(true)
->setFinder($finder)
;
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/phpstan-ignore-by-php-version.neon.php | phpstan-ignore-by-php-version.neon.php | <?php declare(strict_types = 1);
$includes = [];
if (PHP_VERSION_ID >= 80200) {
$includes[] = __DIR__ . '/phpstan-baseline-8.2.neon';
}
$config['includes'] = $includes;
return $config;
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/JsonSerializableDateTimeImmutable.php | src/Monolog/JsonSerializableDateTimeImmutable.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
use DateTimeZone;
/**
* Overrides default json encoding of date time objects
*
* @author Menno Holtkamp
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class JsonSerializableDateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable
{
private bool $useMicroseconds;
public function __construct(bool $useMicroseconds, ?DateTimeZone $timezone = null)
{
$this->useMicroseconds = $useMicroseconds;
// if you like to use a custom time to pass to Logger::addRecord directly,
// call modify() or setTimestamp() on this instance to change the date after creating it
parent::__construct('now', $timezone);
}
public function jsonSerialize(): string
{
if ($this->useMicroseconds) {
return $this->format('Y-m-d\TH:i:s.uP');
}
return $this->format('Y-m-d\TH:i:sP');
}
public function __toString(): string
{
return $this->jsonSerialize();
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/LogRecord.php | src/Monolog/LogRecord.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
use ArrayAccess;
/**
* Monolog log record
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @template-implements ArrayAccess<'message'|'level'|'context'|'level_name'|'channel'|'datetime'|'extra'|'formatted', int|string|\DateTimeImmutable|array<mixed>>
*/
class LogRecord implements ArrayAccess
{
private const MODIFIABLE_FIELDS = [
'extra' => true,
'formatted' => true,
];
public function __construct(
public readonly \DateTimeImmutable $datetime,
public readonly string $channel,
public readonly Level $level,
public readonly string $message,
/** @var array<mixed> */
public readonly array $context = [],
/** @var array<mixed> */
public array $extra = [],
public mixed $formatted = null,
) {
}
public function offsetSet(mixed $offset, mixed $value): void
{
if ($offset === 'extra') {
if (!\is_array($value)) {
throw new \InvalidArgumentException('extra must be an array');
}
$this->extra = $value;
return;
}
if ($offset === 'formatted') {
$this->formatted = $value;
return;
}
throw new \LogicException('Unsupported operation: setting '.$offset);
}
public function offsetExists(mixed $offset): bool
{
if ($offset === 'level_name') {
return true;
}
return isset($this->{$offset});
}
public function offsetUnset(mixed $offset): void
{
throw new \LogicException('Unsupported operation');
}
public function &offsetGet(mixed $offset): mixed
{
// handle special cases for the level enum
if ($offset === 'level_name') {
// avoid returning readonly props by ref as this is illegal
$copy = $this->level->getName();
return $copy;
}
if ($offset === 'level') {
// avoid returning readonly props by ref as this is illegal
$copy = $this->level->value;
return $copy;
}
if (isset(self::MODIFIABLE_FIELDS[$offset])) {
return $this->{$offset};
}
// avoid returning readonly props by ref as this is illegal
$copy = $this->{$offset};
return $copy;
}
/**
* @phpstan-return array{message: string, context: mixed[], level: value-of<Level::VALUES>, level_name: value-of<Level::NAMES>, channel: string, datetime: \DateTimeImmutable, extra: mixed[]}
*/
public function toArray(): array
{
return [
'message' => $this->message,
'context' => $this->context,
'level' => $this->level->value,
'level_name' => $this->level->getName(),
'channel' => $this->channel,
'datetime' => $this->datetime,
'extra' => $this->extra,
];
}
public function with(mixed ...$args): self
{
foreach (['message', 'context', 'level', 'channel', 'datetime', 'extra'] as $prop) {
$args[$prop] ??= $this->{$prop};
}
return new self(...$args);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Registry.php | src/Monolog/Registry.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
use InvalidArgumentException;
/**
* Monolog log registry
*
* Allows to get `Logger` instances in the global scope
* via static method calls on this class.
*
* <code>
* $application = new Monolog\Logger('application');
* $api = new Monolog\Logger('api');
*
* Monolog\Registry::addLogger($application);
* Monolog\Registry::addLogger($api);
*
* function testLogger()
* {
* Monolog\Registry::api()->error('Sent to $api Logger instance');
* Monolog\Registry::application()->error('Sent to $application Logger instance');
* }
* </code>
*
* @author Tomas Tatarko <tomas@tatarko.sk>
*/
class Registry
{
/**
* List of all loggers in the registry (by named indexes)
*
* @var Logger[]
*/
private static array $loggers = [];
/**
* Adds new logging channel to the registry
*
* @param Logger $logger Instance of the logging channel
* @param string|null $name Name of the logging channel ($logger->getName() by default)
* @param bool $overwrite Overwrite instance in the registry if the given name already exists?
* @throws \InvalidArgumentException If $overwrite set to false and named Logger instance already exists
*/
public static function addLogger(Logger $logger, ?string $name = null, bool $overwrite = false): void
{
$name = $name ?? $logger->getName();
if (isset(self::$loggers[$name]) && !$overwrite) {
throw new InvalidArgumentException('Logger with the given name already exists');
}
self::$loggers[$name] = $logger;
}
/**
* Checks if such logging channel exists by name or instance
*
* @param string|Logger $logger Name or logger instance
*/
public static function hasLogger($logger): bool
{
if ($logger instanceof Logger) {
$index = array_search($logger, self::$loggers, true);
return false !== $index;
}
return isset(self::$loggers[$logger]);
}
/**
* Removes instance from registry by name or instance
*
* @param string|Logger $logger Name or logger instance
*/
public static function removeLogger($logger): void
{
if ($logger instanceof Logger) {
if (false !== ($idx = array_search($logger, self::$loggers, true))) {
unset(self::$loggers[$idx]);
}
} else {
unset(self::$loggers[$logger]);
}
}
/**
* Clears the registry
*/
public static function clear(): void
{
self::$loggers = [];
}
/**
* Gets Logger instance from the registry
*
* @param string $name Name of the requested Logger instance
* @throws \InvalidArgumentException If named Logger instance is not in the registry
*/
public static function getInstance(string $name): Logger
{
if (!isset(self::$loggers[$name])) {
throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name));
}
return self::$loggers[$name];
}
/**
* Gets Logger instance from the registry via static method call
*
* @param string $name Name of the requested Logger instance
* @param mixed[] $arguments Arguments passed to static method call
* @throws \InvalidArgumentException If named Logger instance is not in the registry
* @return Logger Requested instance of Logger
*/
public static function __callStatic(string $name, array $arguments): Logger
{
return self::getInstance($name);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Level.php | src/Monolog/Level.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
use Psr\Log\LogLevel;
/**
* Represents the log levels
*
* Monolog supports the logging levels described by RFC 5424 {@see https://datatracker.ietf.org/doc/html/rfc5424}
* but due to BC the severity values used internally are not 0-7.
*
* To get the level name/value out of a Level there are several options:
*
* - Use ->getName() to get the standard Monolog name which is full uppercased (e.g. "DEBUG")
* - Use ->toPsrLogLevel() to get the standard PSR-3 name which is full lowercased (e.g. "debug")
* - Use ->toRFC5424Level() to get the standard RFC 5424 value (e.g. 7 for debug, 0 for emergency)
* - Use ->name to get the enum case's name which is capitalized (e.g. "Debug")
*
* To get the internal value for filtering, if the includes/isLowerThan/isHigherThan methods are
* not enough, you can use ->value to get the enum case's integer value.
*/
enum Level: int
{
/**
* Detailed debug information
*/
case Debug = 100;
/**
* Interesting events
*
* Examples: User logs in, SQL logs.
*/
case Info = 200;
/**
* Uncommon events
*/
case Notice = 250;
/**
* Exceptional occurrences that are not errors
*
* Examples: Use of deprecated APIs, poor use of an API,
* undesirable things that are not necessarily wrong.
*/
case Warning = 300;
/**
* Runtime errors
*/
case Error = 400;
/**
* Critical conditions
*
* Example: Application component unavailable, unexpected exception.
*/
case Critical = 500;
/**
* Action must be taken immediately
*
* Example: Entire website down, database unavailable, etc.
* This should trigger the SMS alerts and wake you up.
*/
case Alert = 550;
/**
* Urgent alert.
*/
case Emergency = 600;
/**
* @param value-of<self::NAMES>|LogLevel::*|'Debug'|'Info'|'Notice'|'Warning'|'Error'|'Critical'|'Alert'|'Emergency' $name
* @return static
*/
public static function fromName(string $name): self
{
return match (strtolower($name)) {
'debug' => self::Debug,
'info' => self::Info,
'notice' => self::Notice,
'warning' => self::Warning,
'error' => self::Error,
'critical' => self::Critical,
'alert' => self::Alert,
'emergency' => self::Emergency,
};
}
/**
* @param value-of<self::VALUES> $value
* @return static
*/
public static function fromValue(int $value): self
{
return self::from($value);
}
/**
* Returns true if the passed $level is higher or equal to $this
*/
public function includes(Level $level): bool
{
return $this->value <= $level->value;
}
public function isHigherThan(Level $level): bool
{
return $this->value > $level->value;
}
public function isLowerThan(Level $level): bool
{
return $this->value < $level->value;
}
/**
* Returns the monolog standardized all-capitals name of the level
*
* Use this instead of $level->name which returns the enum case name (e.g. Debug vs DEBUG if you use getName())
*
* @return value-of<self::NAMES>
*/
public function getName(): string
{
return match ($this) {
self::Debug => 'DEBUG',
self::Info => 'INFO',
self::Notice => 'NOTICE',
self::Warning => 'WARNING',
self::Error => 'ERROR',
self::Critical => 'CRITICAL',
self::Alert => 'ALERT',
self::Emergency => 'EMERGENCY',
};
}
/**
* Returns the PSR-3 level matching this instance
*
* @phpstan-return \Psr\Log\LogLevel::*
*/
public function toPsrLogLevel(): string
{
return match ($this) {
self::Debug => LogLevel::DEBUG,
self::Info => LogLevel::INFO,
self::Notice => LogLevel::NOTICE,
self::Warning => LogLevel::WARNING,
self::Error => LogLevel::ERROR,
self::Critical => LogLevel::CRITICAL,
self::Alert => LogLevel::ALERT,
self::Emergency => LogLevel::EMERGENCY,
};
}
/**
* Returns the RFC 5424 level matching this instance
*
* @phpstan-return int<0, 7>
*/
public function toRFC5424Level(): int
{
return match ($this) {
self::Debug => 7,
self::Info => 6,
self::Notice => 5,
self::Warning => 4,
self::Error => 3,
self::Critical => 2,
self::Alert => 1,
self::Emergency => 0,
};
}
public const VALUES = [
100,
200,
250,
300,
400,
500,
550,
600,
];
public const NAMES = [
'DEBUG',
'INFO',
'NOTICE',
'WARNING',
'ERROR',
'CRITICAL',
'ALERT',
'EMERGENCY',
];
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/DateTimeImmutable.php | src/Monolog/DateTimeImmutable.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
class_alias(JsonSerializableDateTimeImmutable::class, 'Monolog\DateTimeImmutable');
// @phpstan-ignore-next-line
if (false) {
/**
* @deprecated Use \Monolog\JsonSerializableDateTimeImmutable instead.
*/
class DateTimeImmutable extends JsonSerializableDateTimeImmutable
{
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/ErrorHandler.php | src/Monolog/ErrorHandler.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
use Closure;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
/**
* Monolog error handler
*
* A facility to enable logging of runtime errors, exceptions and fatal errors.
*
* Quick setup: <code>ErrorHandler::register($logger);</code>
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ErrorHandler
{
private Closure|null $previousExceptionHandler = null;
/** @var array<class-string, LogLevel::*> an array of class name to LogLevel::* constant mapping */
private array $uncaughtExceptionLevelMap = [];
/** @var Closure|true|null */
private Closure|bool|null $previousErrorHandler = null;
/** @var array<int, LogLevel::*> an array of E_* constant to LogLevel::* constant mapping */
private array $errorLevelMap = [];
private bool $handleOnlyReportedErrors = true;
private bool $hasFatalErrorHandler = false;
private string $fatalLevel = LogLevel::ALERT;
private string|null $reservedMemory = null;
/** @var ?array{type: int, message: string, file: string, line: int, trace: mixed} */
private array|null $lastFatalData = null;
private const FATAL_ERRORS = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
public function __construct(
private LoggerInterface $logger
) {
}
/**
* Registers a new ErrorHandler for a given Logger
*
* By default it will handle errors, exceptions and fatal errors
*
* @param array<int, LogLevel::*>|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling
* @param array<class-string, LogLevel::*>|false $exceptionLevelMap an array of class name to LogLevel::* constant mapping, or false to disable exception handling
* @param LogLevel::*|null|false $fatalLevel a LogLevel::* constant, null to use the default LogLevel::ALERT or false to disable fatal error handling
* @return static
*/
public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null): self
{
/** @phpstan-ignore-next-line */
$handler = new static($logger);
if ($errorLevelMap !== false) {
$handler->registerErrorHandler($errorLevelMap);
}
if ($exceptionLevelMap !== false) {
$handler->registerExceptionHandler($exceptionLevelMap);
}
if ($fatalLevel !== false) {
$handler->registerFatalHandler($fatalLevel);
}
return $handler;
}
/**
* @param array<class-string, LogLevel::*> $levelMap an array of class name to LogLevel::* constant mapping
* @return $this
*/
public function registerExceptionHandler(array $levelMap = [], bool $callPrevious = true): self
{
$prev = set_exception_handler(function (\Throwable $e): void {
$this->handleException($e);
});
$this->uncaughtExceptionLevelMap = $levelMap;
foreach ($this->defaultExceptionLevelMap() as $class => $level) {
if (!isset($this->uncaughtExceptionLevelMap[$class])) {
$this->uncaughtExceptionLevelMap[$class] = $level;
}
}
if ($callPrevious && null !== $prev) {
$this->previousExceptionHandler = $prev(...);
}
return $this;
}
/**
* @param array<int, LogLevel::*> $levelMap an array of E_* constant to LogLevel::* constant mapping
* @return $this
*/
public function registerErrorHandler(array $levelMap = [], bool $callPrevious = true, int $errorTypes = -1, bool $handleOnlyReportedErrors = true): self
{
$prev = set_error_handler($this->handleError(...), $errorTypes);
$this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
if ($callPrevious) {
$this->previousErrorHandler = $prev !== null ? $prev(...) : true;
} else {
$this->previousErrorHandler = null;
}
$this->handleOnlyReportedErrors = $handleOnlyReportedErrors;
return $this;
}
/**
* @param LogLevel::*|null $level a LogLevel::* constant, null to use the default LogLevel::ALERT
* @param int $reservedMemorySize Amount of KBs to reserve in memory so that it can be freed when handling fatal errors giving Monolog some room in memory to get its job done
* @return $this
*/
public function registerFatalHandler($level = null, int $reservedMemorySize = 20): self
{
register_shutdown_function($this->handleFatalError(...));
$this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
$this->fatalLevel = null === $level ? LogLevel::ALERT : $level;
$this->hasFatalErrorHandler = true;
return $this;
}
/**
* @return array<class-string, LogLevel::*>
*/
protected function defaultExceptionLevelMap(): array
{
return [
'ParseError' => LogLevel::CRITICAL,
'Throwable' => LogLevel::ERROR,
];
}
/**
* @return array<int, LogLevel::*>
*/
protected function defaultErrorLevelMap(): array
{
return [
E_ERROR => LogLevel::CRITICAL,
E_WARNING => LogLevel::WARNING,
E_PARSE => LogLevel::ALERT,
E_NOTICE => LogLevel::NOTICE,
E_CORE_ERROR => LogLevel::CRITICAL,
E_CORE_WARNING => LogLevel::WARNING,
E_COMPILE_ERROR => LogLevel::ALERT,
E_COMPILE_WARNING => LogLevel::WARNING,
E_USER_ERROR => LogLevel::ERROR,
E_USER_WARNING => LogLevel::WARNING,
E_USER_NOTICE => LogLevel::NOTICE,
2048 => LogLevel::NOTICE, // E_STRICT
E_RECOVERABLE_ERROR => LogLevel::ERROR,
E_DEPRECATED => LogLevel::NOTICE,
E_USER_DEPRECATED => LogLevel::NOTICE,
];
}
private function handleException(\Throwable $e): never
{
$level = LogLevel::ERROR;
foreach ($this->uncaughtExceptionLevelMap as $class => $candidate) {
if ($e instanceof $class) {
$level = $candidate;
break;
}
}
$this->logger->log(
$level,
sprintf('Uncaught Exception %s: "%s" at %s line %s', Utils::getClass($e), $e->getMessage(), $e->getFile(), $e->getLine()),
['exception' => $e]
);
if (null !== $this->previousExceptionHandler) {
($this->previousExceptionHandler)($e);
}
if (!headers_sent() && \in_array(strtolower((string) \ini_get('display_errors')), ['0', '', 'false', 'off', 'none', 'no'], true)) {
http_response_code(500);
}
exit(255);
}
private function handleError(int $code, string $message, string $file = '', int $line = 0): bool
{
if ($this->handleOnlyReportedErrors && 0 === (error_reporting() & $code)) {
return false;
}
// fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries
if (!$this->hasFatalErrorHandler || !\in_array($code, self::FATAL_ERRORS, true)) {
$level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL;
$this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]);
} else {
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
array_shift($trace); // Exclude handleError from trace
$this->lastFatalData = ['type' => $code, 'message' => $message, 'file' => $file, 'line' => $line, 'trace' => $trace];
}
if ($this->previousErrorHandler === true) {
return false;
}
if ($this->previousErrorHandler instanceof Closure) {
return (bool) ($this->previousErrorHandler)($code, $message, $file, $line);
}
return true;
}
/**
* @private
*/
public function handleFatalError(): void
{
$this->reservedMemory = '';
if (\is_array($this->lastFatalData)) {
$lastError = $this->lastFatalData;
} else {
$lastError = error_get_last();
}
if (\is_array($lastError) && \in_array($lastError['type'], self::FATAL_ERRORS, true)) {
$trace = $lastError['trace'] ?? null;
$this->logger->log(
$this->fatalLevel,
'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'],
['code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'], 'trace' => $trace]
);
if ($this->logger instanceof Logger) {
foreach ($this->logger->getHandlers() as $handler) {
$handler->close();
}
}
}
}
private static function codeToString(int $code): string
{
return match ($code) {
E_ERROR => 'E_ERROR',
E_WARNING => 'E_WARNING',
E_PARSE => 'E_PARSE',
E_NOTICE => 'E_NOTICE',
E_CORE_ERROR => 'E_CORE_ERROR',
E_CORE_WARNING => 'E_CORE_WARNING',
E_COMPILE_ERROR => 'E_COMPILE_ERROR',
E_COMPILE_WARNING => 'E_COMPILE_WARNING',
E_USER_ERROR => 'E_USER_ERROR',
E_USER_WARNING => 'E_USER_WARNING',
E_USER_NOTICE => 'E_USER_NOTICE',
2048 => 'E_STRICT',
E_RECOVERABLE_ERROR => 'E_RECOVERABLE_ERROR',
E_DEPRECATED => 'E_DEPRECATED',
E_USER_DEPRECATED => 'E_USER_DEPRECATED',
default => 'Unknown PHP error',
};
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/SignalHandler.php | src/Monolog/SignalHandler.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use ReflectionExtension;
/**
* Monolog POSIX signal handler
*
* @author Robert Gust-Bardon <robert@gust-bardon.org>
*/
class SignalHandler
{
private LoggerInterface $logger;
/** @var array<int, callable|string|int> SIG_DFL, SIG_IGN or previous callable */
private array $previousSignalHandler = [];
/** @var array<int, \Psr\Log\LogLevel::*> */
private array $signalLevelMap = [];
/** @var array<int, bool> */
private array $signalRestartSyscalls = [];
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @param int|string|Level $level Level or level name
* @return $this
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
*/
public function registerSignalHandler(int $signo, int|string|Level $level = LogLevel::CRITICAL, bool $callPrevious = true, bool $restartSyscalls = true, ?bool $async = true): self
{
if (!\extension_loaded('pcntl') || !\function_exists('pcntl_signal')) {
return $this;
}
$level = Logger::toMonologLevel($level)->toPsrLogLevel();
if ($callPrevious) {
$handler = pcntl_signal_get_handler($signo);
$this->previousSignalHandler[$signo] = $handler;
} else {
unset($this->previousSignalHandler[$signo]);
}
$this->signalLevelMap[$signo] = $level;
$this->signalRestartSyscalls[$signo] = $restartSyscalls;
if ($async !== null) {
pcntl_async_signals($async);
}
pcntl_signal($signo, [$this, 'handleSignal'], $restartSyscalls);
return $this;
}
/**
* @param mixed $siginfo
*/
public function handleSignal(int $signo, $siginfo = null): void
{
/** @var array<int, string> $signals */
static $signals = [];
if (\count($signals) === 0 && \extension_loaded('pcntl')) {
$pcntl = new ReflectionExtension('pcntl');
foreach ($pcntl->getConstants() as $name => $value) {
if (substr($name, 0, 3) === 'SIG' && $name[3] !== '_' && \is_int($value)) {
$signals[$value] = $name;
}
}
}
$level = $this->signalLevelMap[$signo] ?? LogLevel::CRITICAL;
$signal = $signals[$signo] ?? $signo;
$context = $siginfo ?? [];
$this->logger->log($level, sprintf('Program received signal %s', $signal), $context);
if (!isset($this->previousSignalHandler[$signo])) {
return;
}
if ($this->previousSignalHandler[$signo] === SIG_DFL) {
if (\extension_loaded('pcntl') && \function_exists('pcntl_signal') && \function_exists('pcntl_sigprocmask') && \function_exists('pcntl_signal_dispatch')
&& \extension_loaded('posix') && \function_exists('posix_getpid') && \function_exists('posix_kill')
) {
$restartSyscalls = $this->signalRestartSyscalls[$signo] ?? true;
pcntl_signal($signo, SIG_DFL, $restartSyscalls);
pcntl_sigprocmask(SIG_UNBLOCK, [$signo], $oldset);
posix_kill(posix_getpid(), $signo);
pcntl_signal_dispatch();
pcntl_sigprocmask(SIG_SETMASK, $oldset);
pcntl_signal($signo, [$this, 'handleSignal'], $restartSyscalls);
}
} elseif (\is_callable($this->previousSignalHandler[$signo])) {
$this->previousSignalHandler[$signo]($signo, $siginfo);
}
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Utils.php | src/Monolog/Utils.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
final class Utils
{
const DEFAULT_JSON_FLAGS = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE | JSON_PARTIAL_OUTPUT_ON_ERROR;
public static function getClass(object $object): string
{
$class = \get_class($object);
if (false === ($pos = strpos($class, "@anonymous\0"))) {
return $class;
}
if (false === ($parent = get_parent_class($class))) {
return substr($class, 0, $pos + 10);
}
return $parent . '@anonymous';
}
public static function substr(string $string, int $start, ?int $length = null): string
{
if (\extension_loaded('mbstring')) {
return mb_strcut($string, $start, $length);
}
return substr($string, $start, (null === $length) ? \strlen($string) : $length);
}
/**
* Makes sure if a relative path is passed in it is turned into an absolute path
*
* @param string $streamUrl stream URL or path without protocol
*/
public static function canonicalizePath(string $streamUrl): string
{
$prefix = '';
if ('file://' === substr($streamUrl, 0, 7)) {
$streamUrl = substr($streamUrl, 7);
$prefix = 'file://';
}
// other type of stream, not supported
if (false !== strpos($streamUrl, '://')) {
return $streamUrl;
}
// already absolute
if (substr($streamUrl, 0, 1) === '/' || substr($streamUrl, 1, 1) === ':' || substr($streamUrl, 0, 2) === '\\\\') {
return $prefix.$streamUrl;
}
$streamUrl = getcwd() . '/' . $streamUrl;
return $prefix.$streamUrl;
}
/**
* Return the JSON representation of a value
*
* @param mixed $data
* @param int $encodeFlags flags to pass to json encode, defaults to DEFAULT_JSON_FLAGS
* @param bool $ignoreErrors whether to ignore encoding errors or to throw on error, when ignored and the encoding fails, "null" is returned which is valid json for null
* @throws \RuntimeException if encoding fails and errors are not ignored
* @return string when errors are ignored and the encoding fails, "null" is returned which is valid json for null
*/
public static function jsonEncode($data, ?int $encodeFlags = null, bool $ignoreErrors = false): string
{
if (null === $encodeFlags) {
$encodeFlags = self::DEFAULT_JSON_FLAGS;
}
if ($ignoreErrors) {
$json = @json_encode($data, $encodeFlags);
if (false === $json) {
return 'null';
}
return $json;
}
$json = json_encode($data, $encodeFlags);
if (false === $json) {
$json = self::handleJsonError(json_last_error(), $data);
}
return $json;
}
/**
* Handle a json_encode failure.
*
* If the failure is due to invalid string encoding, try to clean the
* input and encode again. If the second encoding attempt fails, the
* initial error is not encoding related or the input can't be cleaned then
* raise a descriptive exception.
*
* @param int $code return code of json_last_error function
* @param mixed $data data that was meant to be encoded
* @param int $encodeFlags flags to pass to json encode, defaults to JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION
* @throws \RuntimeException if failure can't be corrected
* @return string JSON encoded data after error correction
*/
public static function handleJsonError(int $code, $data, ?int $encodeFlags = null): string
{
if ($code !== JSON_ERROR_UTF8) {
self::throwEncodeError($code, $data);
}
if (\is_string($data)) {
self::detectAndCleanUtf8($data);
} elseif (\is_array($data)) {
array_walk_recursive($data, ['Monolog\Utils', 'detectAndCleanUtf8']);
} else {
self::throwEncodeError($code, $data);
}
if (null === $encodeFlags) {
$encodeFlags = self::DEFAULT_JSON_FLAGS;
}
$json = json_encode($data, $encodeFlags);
if ($json === false) {
self::throwEncodeError(json_last_error(), $data);
}
return $json;
}
/**
* Throws an exception according to a given code with a customized message
*
* @param int $code return code of json_last_error function
* @param mixed $data data that was meant to be encoded
* @throws \RuntimeException
*/
private static function throwEncodeError(int $code, $data): never
{
$msg = match ($code) {
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
default => 'Unknown error',
};
throw new \RuntimeException('JSON encoding failed: '.$msg.'. Encoding: '.var_export($data, true));
}
/**
* Detect invalid UTF-8 string characters and convert to valid UTF-8.
*
* Valid UTF-8 input will be left unmodified, but strings containing
* invalid UTF-8 codepoints will be reencoded as UTF-8 with an assumed
* original encoding of ISO-8859-15. This conversion may result in
* incorrect output if the actual encoding was not ISO-8859-15, but it
* will be clean UTF-8 output and will not rely on expensive and fragile
* detection algorithms.
*
* Function converts the input in place in the passed variable so that it
* can be used as a callback for array_walk_recursive.
*
* @param mixed $data Input to check and convert if needed, passed by ref
*/
private static function detectAndCleanUtf8(&$data): void
{
if (\is_string($data) && preg_match('//u', $data) !== 1) {
$data = preg_replace_callback(
'/[\x80-\xFF]+/',
function (array $m): string {
return \function_exists('mb_convert_encoding')
? mb_convert_encoding($m[0], 'UTF-8', 'ISO-8859-1')
: (\function_exists('utf8_encode') ? utf8_encode($m[0]) : '');
},
$data
);
if (!\is_string($data)) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Failed to preg_replace_callback: ' . $pcreErrorCode . ' / ' . preg_last_error_msg());
}
$data = str_replace(
['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'],
['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'],
$data
);
}
}
/**
* Converts a string with a valid 'memory_limit' format, to bytes.
*
* @param string|false $val
* @return int|false Returns an integer representing bytes. Returns FALSE in case of error.
*/
public static function expandIniShorthandBytes($val)
{
if (!\is_string($val)) {
return false;
}
// support -1
if ((int) $val < 0) {
return (int) $val;
}
if (!(bool) preg_match('/^\s*(?<val>\d+)(?:\.\d+)?\s*(?<unit>[gmk]?)\s*$/i', $val, $match)) {
return false;
}
$val = (int) $match['val'];
switch (strtolower($match['unit'])) {
case 'g':
$val *= 1024;
// no break
case 'm':
$val *= 1024;
// no break
case 'k':
$val *= 1024;
}
return $val;
}
public static function getRecordMessageForException(LogRecord $record): string
{
$context = '';
$extra = '';
try {
if (\count($record->context) > 0) {
$context = "\nContext: " . json_encode($record->context, JSON_THROW_ON_ERROR);
}
if (\count($record->extra) > 0) {
$extra = "\nExtra: " . json_encode($record->extra, JSON_THROW_ON_ERROR);
}
} catch (\Throwable $e) {
// noop
}
return "\nThe exception occurred while attempting to log: " . $record->message . $context . $extra;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/ResettableInterface.php | src/Monolog/ResettableInterface.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
/**
* Handler or Processor implementing this interface will be reset when Logger::reset() is called.
*
* Resetting ends a log cycle gets them back 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
* in one process.
*
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
interface ResettableInterface
{
public function reset(): void;
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Logger.php | src/Monolog/Logger.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog;
use Closure;
use DateTimeZone;
use Fiber;
use Monolog\Handler\HandlerInterface;
use Monolog\Processor\ProcessorInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LogLevel;
use Throwable;
use Stringable;
use WeakMap;
/**
* Monolog log channel
*
* It contains a stack of Handlers and a stack of Processors,
* and uses them to store records that are added to it.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @final
*/
class Logger implements LoggerInterface, ResettableInterface
{
/**
* Detailed debug information
*
* @deprecated Use \Monolog\Level::Debug
*/
public const DEBUG = 100;
/**
* Interesting events
*
* Examples: User logs in, SQL logs.
*
* @deprecated Use \Monolog\Level::Info
*/
public const INFO = 200;
/**
* Uncommon events
*
* @deprecated Use \Monolog\Level::Notice
*/
public const NOTICE = 250;
/**
* Exceptional occurrences that are not errors
*
* Examples: Use of deprecated APIs, poor use of an API,
* undesirable things that are not necessarily wrong.
*
* @deprecated Use \Monolog\Level::Warning
*/
public const WARNING = 300;
/**
* Runtime errors
*
* @deprecated Use \Monolog\Level::Error
*/
public const ERROR = 400;
/**
* Critical conditions
*
* Example: Application component unavailable, unexpected exception.
*
* @deprecated Use \Monolog\Level::Critical
*/
public const CRITICAL = 500;
/**
* Action must be taken immediately
*
* Example: Entire website down, database unavailable, etc.
* This should trigger the SMS alerts and wake you up.
*
* @deprecated Use \Monolog\Level::Alert
*/
public const ALERT = 550;
/**
* Urgent alert.
*
* @deprecated Use \Monolog\Level::Emergency
*/
public const EMERGENCY = 600;
/**
* Monolog API version
*
* This is only bumped when API breaks are done and should
* follow the major version of the library
*/
public const API = 3;
/**
* Mapping between levels numbers defined in RFC 5424 and Monolog ones
*
* @phpstan-var array<int, Level> $rfc_5424_levels
*/
private const RFC_5424_LEVELS = [
7 => Level::Debug,
6 => Level::Info,
5 => Level::Notice,
4 => Level::Warning,
3 => Level::Error,
2 => Level::Critical,
1 => Level::Alert,
0 => Level::Emergency,
];
protected string $name;
/**
* The handler stack
*
* @var list<HandlerInterface>
*/
protected array $handlers;
/**
* Processors that will process all log records
*
* To process records of a single handler instead, add the processor on that specific handler
*
* @var array<(callable(LogRecord): LogRecord)|ProcessorInterface>
*/
protected array $processors;
protected bool $microsecondTimestamps = true;
protected DateTimeZone $timezone;
protected Closure|null $exceptionHandler = null;
/**
* Keeps track of depth to prevent infinite logging loops
*/
private int $logDepth = 0;
/**
* @var WeakMap<Fiber<mixed, mixed, mixed, mixed>, int> Keeps track of depth inside fibers to prevent infinite logging loops
*/
private WeakMap $fiberLogDepth;
/**
* Whether to detect infinite logging loops
* This can be disabled via {@see useLoggingLoopDetection} if you have async handlers that do not play well with this
*/
private bool $detectCycles = true;
/**
* @param string $name The logging channel, a simple descriptive name that is attached to all log records
* @param list<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
*
* @phpstan-param array<(callable(LogRecord): LogRecord)|ProcessorInterface> $processors
*/
public function __construct(string $name, array $handlers = [], array $processors = [], DateTimeZone|null $timezone = null)
{
$this->name = $name;
$this->setHandlers($handlers);
$this->processors = $processors;
$this->timezone = $timezone ?? new DateTimeZone(date_default_timezone_get());
$this->fiberLogDepth = new \WeakMap();
}
public function getName(): string
{
return $this->name;
}
/**
* Return a new cloned instance with the name changed
*
* @return static
*/
public function withName(string $name): self
{
$new = clone $this;
$new->name = $name;
return $new;
}
/**
* Pushes a handler on to the stack.
*
* @return $this
*/
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 (0 === \count($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 list<HandlerInterface> $handlers
* @return $this
*/
public function setHandlers(array $handlers): self
{
$this->handlers = [];
foreach (array_reverse($handlers) as $handler) {
$this->pushHandler($handler);
}
return $this;
}
/**
* @return list<HandlerInterface>
*/
public function getHandlers(): array
{
return $this->handlers;
}
/**
* Adds a processor on to the stack.
*
* @phpstan-param ProcessorInterface|(callable(LogRecord): LogRecord) $callback
* @return $this
*/
public function pushProcessor(ProcessorInterface|callable $callback): self
{
array_unshift($this->processors, $callback);
return $this;
}
/**
* Removes the processor on top of the stack and returns it.
*
* @phpstan-return ProcessorInterface|(callable(LogRecord): LogRecord)
* @throws \LogicException If empty processor stack
*/
public function popProcessor(): callable
{
if (0 === \count($this->processors)) {
throw new \LogicException('You tried to pop from an empty processor stack.');
}
return array_shift($this->processors);
}
/**
* @return callable[]
* @phpstan-return array<ProcessorInterface|(callable(LogRecord): LogRecord)>
*/
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
* @return $this
*/
public function useMicrosecondTimestamps(bool $micro): self
{
$this->microsecondTimestamps = $micro;
return $this;
}
/**
* @return $this
*/
public function useLoggingLoopDetection(bool $detectCycles): self
{
$this->detectCycles = $detectCycles;
return $this;
}
/**
* Adds a log record.
*
* @param int $level The logging level (a Monolog or RFC 5424 level)
* @param string $message The log message
* @param mixed[] $context The log context
* @param JsonSerializableDateTimeImmutable|null $datetime Optional log date to log into the past or future
*
* @return bool Whether the record has been processed
*
* @phpstan-param value-of<Level::VALUES>|Level $level
*/
public function addRecord(int|Level $level, string $message, array $context = [], JsonSerializableDateTimeImmutable|null $datetime = null): bool
{
if (\is_int($level) && isset(self::RFC_5424_LEVELS[$level])) {
$level = self::RFC_5424_LEVELS[$level];
}
if ($this->detectCycles) {
if (null !== ($fiber = Fiber::getCurrent())) {
$logDepth = $this->fiberLogDepth[$fiber] = ($this->fiberLogDepth[$fiber] ?? 0) + 1;
} else {
$logDepth = ++$this->logDepth;
}
} else {
$logDepth = 0;
}
if ($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 ($logDepth >= 5) { // log depth 4 is let through, so we can log the warning above
return false;
}
try {
$recordInitialized = \count($this->processors) === 0;
$record = new LogRecord(
datetime: $datetime ?? new JsonSerializableDateTimeImmutable($this->microsecondTimestamps, $this->timezone),
channel: $this->name,
level: self::toMonologLevel($level),
message: $message,
context: $context,
extra: [],
);
$handled = false;
foreach ($this->handlers as $handler) {
if (false === $recordInitialized) {
// skip initializing the record as long as no handler is going to handle it
if (!$handler->isHandling($record)) {
continue;
}
try {
foreach ($this->processors as $processor) {
$record = $processor($record);
}
$recordInitialized = true;
} catch (Throwable $e) {
$this->handleException($e, $record);
return true;
}
}
// once the record is initialized, send it to all handlers as long as the bubbling chain is not interrupted
try {
$handled = true;
if (true === $handler->handle(clone $record)) {
break;
}
} catch (Throwable $e) {
$this->handleException($e, $record);
return true;
}
}
return $handled;
} finally {
if ($this->detectCycles) {
if (isset($fiber)) {
$this->fiberLogDepth[$fiber]--;
} else {
$this->logDepth--;
}
}
}
}
/**
* 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
* in one process.
*/
public function reset(): void
{
foreach ($this->handlers as $handler) {
if ($handler instanceof ResettableInterface) {
$handler->reset();
}
}
foreach ($this->processors as $processor) {
if ($processor instanceof ResettableInterface) {
$processor->reset();
}
}
}
/**
* Gets the name of the logging level as a string.
*
* This still returns a string instead of a Level for BC, but new code should not rely on this method.
*
* @throws \Psr\Log\InvalidArgumentException If level is not defined
*
* @phpstan-param value-of<Level::VALUES>|Level $level
* @phpstan-return value-of<Level::NAMES>
*
* @deprecated Since 3.0, use {@see toMonologLevel} or {@see \Monolog\Level->getName()} instead
*/
public static function getLevelName(int|Level $level): string
{
return self::toMonologLevel($level)->getName();
}
/**
* Converts PSR-3 levels to Monolog ones if necessary
*
* @param int|string|Level|LogLevel::* $level Level number (monolog) or name (PSR-3)
* @throws \Psr\Log\InvalidArgumentException If level is not defined
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
*/
public static function toMonologLevel(string|int|Level $level): Level
{
if ($level instanceof Level) {
return $level;
}
if (\is_string($level)) {
if (is_numeric($level)) {
$levelEnum = Level::tryFrom((int) $level);
if ($levelEnum === null) {
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES));
}
return $levelEnum;
}
// Contains first char of all log levels and avoids using strtoupper() which may have
// strange results depending on locale (for example, "i" will become "İ" in Turkish locale)
$upper = strtr(substr($level, 0, 1), 'dinweca', 'DINWECA') . strtolower(substr($level, 1));
if (\defined(Level::class.'::'.$upper)) {
return \constant(Level::class . '::' . $upper);
}
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES));
}
$levelEnum = Level::tryFrom($level);
if ($levelEnum === null) {
throw new InvalidArgumentException('Level "'.var_export($level, true).'" is not defined, use one of: '.implode(', ', Level::NAMES + Level::VALUES));
}
return $levelEnum;
}
/**
* Checks whether the Logger has a handler that listens on the given level
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
*/
public function isHandling(int|string|Level $level): bool
{
$record = new LogRecord(
datetime: new JsonSerializableDateTimeImmutable($this->microsecondTimestamps, $this->timezone),
channel: $this->name,
message: '',
level: self::toMonologLevel($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 Closure will receive an exception object and the record that failed to be logged
*
* @return $this
*/
public function setExceptionHandler(Closure|null $callback): self
{
$this->exceptionHandler = $callback;
return $this;
}
public function getExceptionHandler(): Closure|null
{
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 (a Monolog, PSR-3 or RFC 5424 level)
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*
* @phpstan-param Level|LogLevel::* $level
*/
public function log($level, string|\Stringable $message, array $context = []): void
{
if (!$level instanceof Level) {
if (!\is_string($level) && !\is_int($level)) {
throw new \InvalidArgumentException('$level is expected to be a string, int or '.Level::class.' instance');
}
if (isset(self::RFC_5424_LEVELS[$level])) {
$level = self::RFC_5424_LEVELS[$level];
}
$level = static::toMonologLevel($level);
}
$this->addRecord($level, (string) $message, $context);
}
/**
* Adds a log record at the DEBUG level.
*
* This method allows for compatibility with common interfaces.
*
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*/
public function debug(string|\Stringable $message, array $context = []): void
{
$this->addRecord(Level::Debug, (string) $message, $context);
}
/**
* Adds a log record at the INFO level.
*
* This method allows for compatibility with common interfaces.
*
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*/
public function info(string|\Stringable $message, array $context = []): void
{
$this->addRecord(Level::Info, (string) $message, $context);
}
/**
* Adds a log record at the NOTICE level.
*
* This method allows for compatibility with common interfaces.
*
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*/
public function notice(string|\Stringable $message, array $context = []): void
{
$this->addRecord(Level::Notice, (string) $message, $context);
}
/**
* Adds a log record at the WARNING level.
*
* This method allows for compatibility with common interfaces.
*
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*/
public function warning(string|\Stringable $message, array $context = []): void
{
$this->addRecord(Level::Warning, (string) $message, $context);
}
/**
* Adds a log record at the ERROR level.
*
* This method allows for compatibility with common interfaces.
*
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*/
public function error(string|\Stringable $message, array $context = []): void
{
$this->addRecord(Level::Error, (string) $message, $context);
}
/**
* Adds a log record at the CRITICAL level.
*
* This method allows for compatibility with common interfaces.
*
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*/
public function critical(string|\Stringable $message, array $context = []): void
{
$this->addRecord(Level::Critical, (string) $message, $context);
}
/**
* Adds a log record at the ALERT level.
*
* This method allows for compatibility with common interfaces.
*
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*/
public function alert(string|\Stringable $message, array $context = []): void
{
$this->addRecord(Level::Alert, (string) $message, $context);
}
/**
* Adds a log record at the EMERGENCY level.
*
* This method allows for compatibility with common interfaces.
*
* @param string|Stringable $message The log message
* @param mixed[] $context The log context
*/
public function emergency(string|\Stringable $message, array $context = []): void
{
$this->addRecord(Level::Emergency, (string) $message, $context);
}
/**
* Sets the timezone to be used for the timestamp of log records.
*
* @return $this
*/
public function setTimezone(DateTimeZone $tz): self
{
$this->timezone = $tz;
return $this;
}
/**
* Returns the timezone to be used for the timestamp of log records.
*/
public function getTimezone(): DateTimeZone
{
return $this->timezone;
}
/**
* Delegates exception management to the custom exception handler,
* or throws the exception if no custom handler is set.
*/
protected function handleException(Throwable $e, LogRecord $record): void
{
if (null === $this->exceptionHandler) {
throw $e;
}
($this->exceptionHandler)($e, $record);
}
/**
* @return array<string, mixed>
*/
public function __serialize(): array
{
return [
'name' => $this->name,
'handlers' => $this->handlers,
'processors' => $this->processors,
'microsecondTimestamps' => $this->microsecondTimestamps,
'timezone' => $this->timezone,
'exceptionHandler' => $this->exceptionHandler,
'logDepth' => $this->logDepth,
'detectCycles' => $this->detectCycles,
];
}
/**
* @param array<string, mixed> $data
*/
public function __unserialize(array $data): void
{
foreach (['name', 'handlers', 'processors', 'microsecondTimestamps', 'timezone', 'exceptionHandler', 'logDepth', 'detectCycles'] as $property) {
if (isset($data[$property])) {
$this->$property = $data[$property];
}
}
$this->fiberLogDepth = new \WeakMap();
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/ProcessIdProcessor.php | src/Monolog/Processor/ProcessIdProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\LogRecord;
/**
* Adds value of getmypid into records
*
* @author Andreas Hörnicke
*/
class ProcessIdProcessor implements ProcessorInterface
{
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
$record->extra['process_id'] = getmypid();
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/HostnameProcessor.php | src/Monolog/Processor/HostnameProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\LogRecord;
/**
* Injects value of gethostname in all records
*/
class HostnameProcessor implements ProcessorInterface
{
private static string $host;
public function __construct()
{
self::$host = (string) gethostname();
}
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
$record->extra['hostname'] = self::$host;
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/IntrospectionProcessor.php | src/Monolog/Processor/IntrospectionProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\Level;
use Monolog\Logger;
use Psr\Log\LogLevel;
use Monolog\LogRecord;
/**
* Injects line/file:class/function where the log message came from
*
* Warning: This only works if the handler processes the logs directly.
* If you put the processor on a handler that is behind a FingersCrossedHandler
* for example, the processor will only be called once the trigger level is reached,
* and all the log records will have the same file/line/.. data from the call that
* triggered the FingersCrossedHandler.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class IntrospectionProcessor implements ProcessorInterface
{
protected Level $level;
/** @var string[] */
protected array $skipClassesPartials;
protected int $skipStackFramesCount;
protected const SKIP_FUNCTIONS = [
'call_user_func',
'call_user_func_array',
];
protected const SKIP_CLASSES = [
'Monolog\\',
];
/**
* @param string|int|Level $level The minimum logging level at which this Processor will be triggered
* @param string[] $skipClassesPartials
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
*/
public function __construct(int|string|Level $level = Level::Debug, array $skipClassesPartials = [], int $skipStackFramesCount = 0)
{
$this->level = Logger::toMonologLevel($level);
$this->skipClassesPartials = array_merge(static::SKIP_CLASSES, $skipClassesPartials);
$this->skipStackFramesCount = $skipStackFramesCount;
}
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
// return if the level is not high enough
if ($record->level->isLowerThan($this->level)) {
return $record;
}
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
// skip first since it's always the current method
array_shift($trace);
// the call_user_func call is also skipped
array_shift($trace);
$i = 0;
while ($this->isTraceClassOrSkippedFunction($trace, $i)) {
if (isset($trace[$i]['class'])) {
foreach ($this->skipClassesPartials as $part) {
if (strpos($trace[$i]['class'], $part) !== false) {
$i++;
continue 2;
}
}
} elseif (\in_array($trace[$i]['function'], self::SKIP_FUNCTIONS, true)) {
$i++;
continue;
}
break;
}
$i += $this->skipStackFramesCount;
// we should have the call source now
$record->extra = array_merge(
$record->extra,
[
'file' => $trace[$i - 1]['file'] ?? null,
'line' => $trace[$i - 1]['line'] ?? null,
'class' => $trace[$i]['class'] ?? null,
'callType' => $trace[$i]['type'] ?? null,
'function' => $trace[$i]['function'] ?? null,
]
);
return $record;
}
/**
* @param array<mixed> $trace
*/
private function isTraceClassOrSkippedFunction(array $trace, int $index): bool
{
if (!isset($trace[$index])) {
return false;
}
return isset($trace[$index]['class']) || \in_array($trace[$index]['function'], self::SKIP_FUNCTIONS, true);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/LoadAverageProcessor.php | src/Monolog/Processor/LoadAverageProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\LogRecord;
/**
* Injects sys_getloadavg in all records @see https://www.php.net/manual/en/function.sys-getloadavg.php
*
* @author Johan Vlaar <johan.vlaar.1994@gmail.com>
*/
class LoadAverageProcessor implements ProcessorInterface
{
public const LOAD_1_MINUTE = 0;
public const LOAD_5_MINUTE = 1;
public const LOAD_15_MINUTE = 2;
private const AVAILABLE_LOAD = [
self::LOAD_1_MINUTE,
self::LOAD_5_MINUTE,
self::LOAD_15_MINUTE,
];
/**
* @var int
*/
protected $avgSystemLoad;
/**
* @param self::LOAD_* $avgSystemLoad
*/
public function __construct(int $avgSystemLoad = self::LOAD_1_MINUTE)
{
if (!\in_array($avgSystemLoad, self::AVAILABLE_LOAD, true)) {
throw new \InvalidArgumentException(sprintf('Invalid average system load: `%s`', $avgSystemLoad));
}
$this->avgSystemLoad = $avgSystemLoad;
}
/**
* {@inheritDoc}
*/
public function __invoke(LogRecord $record): LogRecord
{
if (!\function_exists('sys_getloadavg')) {
return $record;
}
$usage = sys_getloadavg();
if (false === $usage) {
return $record;
}
$record->extra['load_average'] = $usage[$this->avgSystemLoad];
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/MemoryPeakUsageProcessor.php | src/Monolog/Processor/MemoryPeakUsageProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\LogRecord;
/**
* Injects memory_get_peak_usage in all records
*
* @see Monolog\Processor\MemoryProcessor::__construct() for options
* @author Rob Jensen
*/
class MemoryPeakUsageProcessor extends MemoryProcessor
{
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
$usage = memory_get_peak_usage($this->realUsage);
if ($this->useFormatting) {
$usage = $this->formatBytes($usage);
}
$record->extra['memory_peak_usage'] = $usage;
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/WebProcessor.php | src/Monolog/Processor/WebProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use ArrayAccess;
use Monolog\LogRecord;
/**
* Injects url/method and remote IP of the current web request in all records
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class WebProcessor implements ProcessorInterface
{
/**
* @var array<string, mixed>|ArrayAccess<string, mixed>
*/
protected array|ArrayAccess $serverData;
/**
* Default fields
*
* Array is structured as [key in record.extra => key in $serverData]
*
* @var array<string, string>
*/
protected array $extraFields = [
'url' => 'REQUEST_URI',
'ip' => 'REMOTE_ADDR',
'http_method' => 'REQUEST_METHOD',
'server' => 'SERVER_NAME',
'referrer' => 'HTTP_REFERER',
'user_agent' => 'HTTP_USER_AGENT',
];
/**
* @param array<string, mixed>|ArrayAccess<string, mixed>|null $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data
* @param array<string, string>|array<string>|null $extraFields Field names and the related key inside $serverData to be added (or just a list of field names to use the default configured $serverData mapping). If not provided it defaults to: [url, ip, http_method, server, referrer] + unique_id if present in server data
*/
public function __construct(array|ArrayAccess|null $serverData = null, array|null $extraFields = null)
{
if (null === $serverData) {
$this->serverData = &$_SERVER;
} else {
$this->serverData = $serverData;
}
$defaultEnabled = ['url', 'ip', 'http_method', 'server', 'referrer'];
if (isset($this->serverData['UNIQUE_ID'])) {
$this->extraFields['unique_id'] = 'UNIQUE_ID';
$defaultEnabled[] = 'unique_id';
}
if (null === $extraFields) {
$extraFields = $defaultEnabled;
}
if (isset($extraFields[0])) {
foreach (array_keys($this->extraFields) as $fieldName) {
if (!\in_array($fieldName, $extraFields, true)) {
unset($this->extraFields[$fieldName]);
}
}
} else {
$this->extraFields = $extraFields;
}
}
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
// skip processing if for some reason request data
// is not present (CLI or wonky SAPIs)
if (!isset($this->serverData['REQUEST_URI'])) {
return $record;
}
$record->extra = $this->appendExtraFields($record->extra);
return $record;
}
/**
* @return $this
*/
public function addExtraField(string $extraName, string $serverName): self
{
$this->extraFields[$extraName] = $serverName;
return $this;
}
/**
* @param mixed[] $extra
* @return mixed[]
*/
private function appendExtraFields(array $extra): array
{
foreach ($this->extraFields as $extraName => $serverName) {
$extra[$extraName] = $this->serverData[$serverName] ?? null;
}
return $extra;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/GitProcessor.php | src/Monolog/Processor/GitProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\Level;
use Monolog\Logger;
use Psr\Log\LogLevel;
use Monolog\LogRecord;
/**
* Injects Git branch and Git commit SHA in all records
*
* @author Nick Otter
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class GitProcessor implements ProcessorInterface
{
private Level $level;
/** @var array{branch: string, commit: string}|array<never>|null */
private static $cache = null;
/**
* @param int|string|Level|LogLevel::* $level The minimum logging level at which this Processor will be triggered
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
*/
public function __construct(int|string|Level $level = Level::Debug)
{
$this->level = Logger::toMonologLevel($level);
}
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
// return if the level is not high enough
if ($record->level->isLowerThan($this->level)) {
return $record;
}
$record->extra['git'] = self::getGitInfo();
return $record;
}
/**
* @return array{branch: string, commit: string}|array<never>
*/
private static function getGitInfo(): array
{
if (self::$cache !== null) {
return self::$cache;
}
$branches = shell_exec('git branch -v --no-abbrev');
if (\is_string($branches) && 1 === preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) {
return self::$cache = [
'branch' => $matches[1],
'commit' => $matches[2],
];
}
return self::$cache = [];
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/ProcessorInterface.php | src/Monolog/Processor/ProcessorInterface.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\LogRecord;
/**
* An optional interface to allow labelling Monolog processors.
*
* @author Nicolas Grekas <p@tchwork.com>
*/
interface ProcessorInterface
{
/**
* @return LogRecord The processed record
*/
public function __invoke(LogRecord $record);
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/MemoryProcessor.php | src/Monolog/Processor/MemoryProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
/**
* Some methods that are common for all memory processors
*
* @author Rob Jensen
*/
abstract class MemoryProcessor implements ProcessorInterface
{
/**
* @var bool If true, get the real size of memory allocated from system. Else, only the memory used by emalloc() is reported.
*/
protected bool $realUsage;
/**
* @var bool If true, then format memory size to human readable string (MB, KB, B depending on size)
*/
protected bool $useFormatting;
/**
* @param bool $realUsage Set this to true to get the real size of memory allocated from system.
* @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size)
*/
public function __construct(bool $realUsage = true, bool $useFormatting = true)
{
$this->realUsage = $realUsage;
$this->useFormatting = $useFormatting;
}
/**
* Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is
*
* @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as int
*/
protected function formatBytes(int $bytes)
{
if (!$this->useFormatting) {
return $bytes;
}
if ($bytes > 1024 * 1024) {
return round($bytes / 1024 / 1024, 2).' MB';
} elseif ($bytes > 1024) {
return round($bytes / 1024, 2).' KB';
}
return $bytes . ' B';
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/MemoryUsageProcessor.php | src/Monolog/Processor/MemoryUsageProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\LogRecord;
/**
* Injects memory_get_usage in all records
*
* @see Monolog\Processor\MemoryProcessor::__construct() for options
* @author Rob Jensen
*/
class MemoryUsageProcessor extends MemoryProcessor
{
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
$usage = memory_get_usage($this->realUsage);
if ($this->useFormatting) {
$usage = $this->formatBytes($usage);
}
$record->extra['memory_usage'] = $usage;
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/ClosureContextProcessor.php | src/Monolog/Processor/ClosureContextProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\LogRecord;
/**
* Generates a context from a Closure if the Closure is the only value
* in the context
*
* It helps reduce the performance impact of debug logs if they do
* need to create lots of context information. If this processor is added
* on the correct handler the context data will only be generated
* when the logs are actually logged to that handler, which is useful when
* using FingersCrossedHandler or other filtering handlers to conditionally
* log records.
*/
class ClosureContextProcessor implements ProcessorInterface
{
public function __invoke(LogRecord $record): LogRecord
{
$context = $record->context;
if (isset($context[0]) && 1 === \count($context) && $context[0] instanceof \Closure) {
try {
$context = $context[0]();
} catch (\Throwable $e) {
$context = [
'error_on_context_generation' => $e->getMessage(),
'exception' => $e,
];
}
if (!\is_array($context)) {
$context = [$context];
}
$record = $record->with(context: $context);
}
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/UidProcessor.php | src/Monolog/Processor/UidProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\ResettableInterface;
use Monolog\LogRecord;
/**
* Adds a unique identifier into records
*
* @author Simon Mönch <sm@webfactory.de>
*/
class UidProcessor implements ProcessorInterface, ResettableInterface
{
/** @var non-empty-string */
private string $uid;
/**
* @param int<1, 32> $length
*/
public function __construct(int $length = 7)
{
if ($length > 32 || $length < 1) {
throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
}
$this->uid = $this->generateUid($length);
}
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
$record->extra['uid'] = $this->uid;
return $record;
}
public function getUid(): string
{
return $this->uid;
}
public function reset(): void
{
$this->uid = $this->generateUid(\strlen($this->uid));
}
/**
* @param positive-int $length
* @return non-empty-string
*/
private function generateUid(int $length): string
{
return substr(bin2hex(random_bytes((int) ceil($length / 2))), 0, $length);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/MercurialProcessor.php | src/Monolog/Processor/MercurialProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\Level;
use Monolog\Logger;
use Psr\Log\LogLevel;
use Monolog\LogRecord;
/**
* Injects Hg branch and Hg revision number in all records
*
* @author Jonathan A. Schweder <jonathanschweder@gmail.com>
*/
class MercurialProcessor implements ProcessorInterface
{
private Level $level;
/** @var array{branch: string, revision: string}|array<never>|null */
private static $cache = null;
/**
* @param int|string|Level $level The minimum logging level at which this Processor will be triggered
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
*/
public function __construct(int|string|Level $level = Level::Debug)
{
$this->level = Logger::toMonologLevel($level);
}
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
// return if the level is not high enough
if ($record->level->isLowerThan($this->level)) {
return $record;
}
$record->extra['hg'] = self::getMercurialInfo();
return $record;
}
/**
* @return array{branch: string, revision: string}|array<never>
*/
private static function getMercurialInfo(): array
{
if (self::$cache !== null) {
return self::$cache;
}
$result = explode(' ', trim((string) shell_exec('hg id -nb')));
if (\count($result) >= 3) {
return self::$cache = [
'branch' => $result[1],
'revision' => $result[2],
];
}
if (\count($result) === 2) {
return self::$cache = [
'branch' => $result[1],
'revision' => $result[0],
];
}
return self::$cache = [];
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/PsrLogMessageProcessor.php | src/Monolog/Processor/PsrLogMessageProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\Utils;
use Monolog\LogRecord;
/**
* Processes a record's message according to PSR-3 rules
*
* It replaces {foo} with the value from $context['foo']
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class PsrLogMessageProcessor implements ProcessorInterface
{
public const SIMPLE_DATE = "Y-m-d\TH:i:s.uP";
private ?string $dateFormat;
private bool $removeUsedContextFields;
/**
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
* @param bool $removeUsedContextFields If set to true the fields interpolated into message gets unset
*/
public function __construct(?string $dateFormat = null, bool $removeUsedContextFields = false)
{
$this->dateFormat = $dateFormat;
$this->removeUsedContextFields = $removeUsedContextFields;
}
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
if (false === strpos($record->message, '{')) {
return $record;
}
$replacements = [];
$context = $record->context;
foreach ($context as $key => $val) {
$placeholder = '{' . $key . '}';
if (strpos($record->message, $placeholder) === false) {
continue;
}
if (null === $val || \is_scalar($val) || (\is_object($val) && method_exists($val, "__toString"))) {
$replacements[$placeholder] = $val;
} elseif ($val instanceof \DateTimeInterface) {
if (null === $this->dateFormat && $val instanceof \Monolog\JsonSerializableDateTimeImmutable) {
// handle monolog dates using __toString if no specific dateFormat was asked for
// so that it follows the useMicroseconds flag
$replacements[$placeholder] = (string) $val;
} else {
$replacements[$placeholder] = $val->format($this->dateFormat ?? static::SIMPLE_DATE);
}
} elseif ($val instanceof \UnitEnum) {
$replacements[$placeholder] = $val instanceof \BackedEnum ? $val->value : $val->name;
} elseif (\is_object($val)) {
$replacements[$placeholder] = '[object '.Utils::getClass($val).']';
} elseif (\is_array($val)) {
$replacements[$placeholder] = 'array'.Utils::jsonEncode($val, null, true);
} else {
$replacements[$placeholder] = '['.\gettype($val).']';
}
if ($this->removeUsedContextFields) {
unset($context[$key]);
}
}
return $record->with(message: strtr($record->message, $replacements), context: $context);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Processor/TagProcessor.php | src/Monolog/Processor/TagProcessor.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Processor;
use Monolog\LogRecord;
/**
* Adds a tags array into record
*
* @author Martijn Riemers
*/
class TagProcessor implements ProcessorInterface
{
/** @var string[] */
private array $tags;
/**
* @param string[] $tags
*/
public function __construct(array $tags = [])
{
$this->setTags($tags);
}
/**
* @param string[] $tags
* @return $this
*/
public function addTags(array $tags = []): self
{
$this->tags = array_merge($this->tags, $tags);
return $this;
}
/**
* @param string[] $tags
* @return $this
*/
public function setTags(array $tags = []): self
{
$this->tags = $tags;
return $this;
}
/**
* @inheritDoc
*/
public function __invoke(LogRecord $record): LogRecord
{
$record->extra['tags'] = $this->tags;
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/WildfireFormatter.php | src/Monolog/Formatter/WildfireFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\LogRecord;
/**
* Serializes a log message according to Wildfire's header requirements
*
* @author Eric Clemmons (@ericclemmons) <eric@uxdriven.com>
* @author Christophe Coevoet <stof@notk.org>
* @author Kirill chEbba Chebunin <iam@chebba.org>
*/
class WildfireFormatter extends NormalizerFormatter
{
/**
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
*/
public function __construct(?string $dateFormat = null)
{
parent::__construct($dateFormat);
// http headers do not like non-ISO-8559-1 characters
$this->removeJsonEncodeOption(JSON_UNESCAPED_UNICODE);
}
/**
* Translates Monolog log levels to Wildfire levels.
*
* @return 'LOG'|'INFO'|'WARN'|'ERROR'
*/
private function toWildfireLevel(Level $level): string
{
return match ($level) {
Level::Debug => 'LOG',
Level::Info => 'INFO',
Level::Notice => 'INFO',
Level::Warning => 'WARN',
Level::Error => 'ERROR',
Level::Critical => 'ERROR',
Level::Alert => 'ERROR',
Level::Emergency => 'ERROR',
};
}
/**
* @inheritDoc
*/
public function format(LogRecord $record): string
{
// Retrieve the line and file if set and remove them from the formatted extra
$file = $line = '';
if (isset($record->extra['file'])) {
$file = $record->extra['file'];
unset($record->extra['file']);
}
if (isset($record->extra['line'])) {
$line = $record->extra['line'];
unset($record->extra['line']);
}
$message = ['message' => $record->message];
$handleError = false;
if (\count($record->context) > 0) {
$message['context'] = $this->normalize($record->context);
$handleError = true;
}
if (\count($record->extra) > 0) {
$message['extra'] = $this->normalize($record->extra);
$handleError = true;
}
if (\count($message) === 1) {
$message = reset($message);
}
if (is_array($message) && isset($message['context']) && \is_array($message['context']) && isset($message['context']['table'])) {
$type = 'TABLE';
$label = $record->channel .': '. $record->message;
$message = $message['context']['table'];
} else {
$type = $this->toWildfireLevel($record->level);
$label = $record->channel;
}
// Create JSON object describing the appearance of the message in the console
$json = $this->toJson([
[
'Type' => $type,
'File' => $file,
'Line' => $line,
'Label' => $label,
],
$message,
], $handleError);
// The message itself is a serialization of the above JSON object + it's length
return sprintf(
'%d|%s|',
\strlen($json),
$json
);
}
/**
* @inheritDoc
*
* @phpstan-return never
*/
public function formatBatch(array $records)
{
throw new \BadMethodCallException('Batch formatting does not make sense for the WildfireFormatter');
}
/**
* @inheritDoc
*
* @return null|scalar|array<mixed[]|scalar|null>|object
*/
protected function normalize(mixed $data, int $depth = 0): mixed
{
if (\is_object($data) && !$data instanceof \DateTimeInterface) {
return $data;
}
return parent::normalize($data, $depth);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/ScalarFormatter.php | src/Monolog/Formatter/ScalarFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\LogRecord;
/**
* Formats data into an associative array of scalar (+ null) values.
* Objects and arrays will be JSON encoded.
*
* @author Andrew Lawson <adlawson@gmail.com>
*/
class ScalarFormatter extends NormalizerFormatter
{
/**
* @inheritDoc
*
* @phpstan-return array<string, scalar|null> $record
*/
public function format(LogRecord $record): array
{
$result = [];
foreach ($record->toArray() as $key => $value) {
$result[$key] = $this->toScalar($value);
}
return $result;
}
protected function toScalar(mixed $value): string|int|float|bool|null
{
$normalized = $this->normalize($value);
if (\is_array($normalized)) {
return $this->toJson($normalized, true);
}
return $normalized;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/MongoDBFormatter.php | src/Monolog/Formatter/MongoDBFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use MongoDB\BSON\Type;
use MongoDB\BSON\UTCDateTime;
use Monolog\Utils;
use Monolog\LogRecord;
/**
* Formats a record for use with the MongoDBHandler.
*
* @author Florian Plattner <me@florianplattner.de>
*/
class MongoDBFormatter implements FormatterInterface
{
private bool $exceptionTraceAsString;
private int $maxNestingLevel;
/**
* @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record->context is 2
* @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings
*/
public function __construct(int $maxNestingLevel = 3, bool $exceptionTraceAsString = true)
{
$this->maxNestingLevel = max($maxNestingLevel, 0);
$this->exceptionTraceAsString = $exceptionTraceAsString;
}
/**
* @inheritDoc
*
* @return mixed[]
*/
public function format(LogRecord $record): array
{
/** @var mixed[] $res */
$res = $this->formatArray($record->toArray());
return $res;
}
/**
* @inheritDoc
*
* @return array<mixed[]>
*/
public function formatBatch(array $records): array
{
$formatted = [];
foreach ($records as $key => $record) {
$formatted[$key] = $this->format($record);
}
return $formatted;
}
/**
* @param mixed[] $array
* @return mixed[]|string Array except when max nesting level is reached then a string "[...]"
*/
protected function formatArray(array $array, int $nestingLevel = 0)
{
if ($this->maxNestingLevel > 0 && $nestingLevel > $this->maxNestingLevel) {
return '[...]';
}
foreach ($array as $name => $value) {
if ($value instanceof \DateTimeInterface) {
$array[$name] = $this->formatDate($value, $nestingLevel + 1);
} elseif ($value instanceof \Throwable) {
$array[$name] = $this->formatException($value, $nestingLevel + 1);
} elseif (\is_array($value)) {
$array[$name] = $this->formatArray($value, $nestingLevel + 1);
} elseif (\is_object($value) && !$value instanceof Type) {
$array[$name] = $this->formatObject($value, $nestingLevel + 1);
}
}
return $array;
}
/**
* @param mixed $value
* @return mixed[]|string
*/
protected function formatObject($value, int $nestingLevel)
{
$objectVars = get_object_vars($value);
$objectVars['class'] = Utils::getClass($value);
return $this->formatArray($objectVars, $nestingLevel);
}
/**
* @return mixed[]|string
*/
protected function formatException(\Throwable $exception, int $nestingLevel)
{
$formattedException = [
'class' => Utils::getClass($exception),
'message' => $exception->getMessage(),
'code' => (int) $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(),
];
if ($this->exceptionTraceAsString === true) {
$formattedException['trace'] = $exception->getTraceAsString();
} else {
$formattedException['trace'] = $exception->getTrace();
}
return $this->formatArray($formattedException, $nestingLevel);
}
protected function formatDate(\DateTimeInterface $value, int $nestingLevel): UTCDateTime
{
return new UTCDateTime((int) floor(((float) $value->format('U.u')) * 1000));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/ElasticsearchFormatter.php | src/Monolog/Formatter/ElasticsearchFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use DateTimeInterface;
use Monolog\LogRecord;
/**
* Format a log message into an Elasticsearch record
*
* @author Avtandil Kikabidze <akalongman@gmail.com>
*/
class ElasticsearchFormatter extends NormalizerFormatter
{
/**
* @var string Elasticsearch index name
*/
protected string $index;
/**
* @var string Elasticsearch record type
*/
protected string $type;
/**
* @param string $index Elasticsearch index name
* @param string $type Elasticsearch record type
*/
public function __construct(string $index, string $type)
{
// Elasticsearch requires an ISO 8601 format date with optional millisecond precision.
parent::__construct(DateTimeInterface::ATOM);
$this->index = $index;
$this->type = $type;
}
/**
* @inheritDoc
*/
public function format(LogRecord $record)
{
$record = parent::format($record);
return $this->getDocument($record);
}
/**
* Getter index
*/
public function getIndex(): string
{
return $this->index;
}
/**
* Getter type
*/
public function getType(): string
{
return $this->type;
}
/**
* Convert a log message into an Elasticsearch record
*
* @param mixed[] $record Log message
* @return mixed[]
*/
protected function getDocument(array $record): array
{
$record['_index'] = $this->index;
$record['_type'] = $this->type;
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/ChromePHPFormatter.php | src/Monolog/Formatter/ChromePHPFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\LogRecord;
/**
* Formats a log message according to the ChromePHP array format
*
* @author Christophe Coevoet <stof@notk.org>
*/
class ChromePHPFormatter implements FormatterInterface
{
/**
* Translates Monolog log levels to Wildfire levels.
*
* @return 'log'|'info'|'warn'|'error'
*/
private function toWildfireLevel(Level $level): string
{
return match ($level) {
Level::Debug => 'log',
Level::Info => 'info',
Level::Notice => 'info',
Level::Warning => 'warn',
Level::Error => 'error',
Level::Critical => 'error',
Level::Alert => 'error',
Level::Emergency => 'error',
};
}
/**
* @inheritDoc
*/
public function format(LogRecord $record)
{
// Retrieve the line and file if set and remove them from the formatted extra
$backtrace = 'unknown';
if (isset($record->extra['file'], $record->extra['line'])) {
$backtrace = $record->extra['file'].' : '.$record->extra['line'];
unset($record->extra['file'], $record->extra['line']);
}
$message = ['message' => $record->message];
if (\count($record->context) > 0) {
$message['context'] = $record->context;
}
if (\count($record->extra) > 0) {
$message['extra'] = $record->extra;
}
if (\count($message) === 1) {
$message = reset($message);
}
return [
$record->channel,
$message,
$backtrace,
$this->toWildfireLevel($record->level),
];
}
/**
* @inheritDoc
*/
public function formatBatch(array $records)
{
$formatted = [];
foreach ($records as $record) {
$formatted[] = $this->format($record);
}
return $formatted;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/LineFormatter.php | src/Monolog/Formatter/LineFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Closure;
use Monolog\Utils;
use Monolog\LogRecord;
/**
* Formats incoming records into a one-line string
*
* This is especially useful for logging to files
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Christophe Coevoet <stof@notk.org>
*/
class LineFormatter extends NormalizerFormatter
{
public const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n";
protected string $format;
protected bool $allowInlineLineBreaks;
protected bool $ignoreEmptyContextAndExtra;
protected bool $includeStacktraces;
protected ?int $maxLevelNameLength = null;
protected string $indentStacktraces = '';
protected Closure|null $stacktracesParser = null;
protected string $basePath = '';
/**
* @param string|null $format The format of the message
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
* @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries
*/
public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false)
{
$this->format = $format === null ? static::SIMPLE_FORMAT : $format;
$this->allowInlineLineBreaks = $allowInlineLineBreaks;
$this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra;
$this->includeStacktraces($includeStacktraces);
parent::__construct($dateFormat);
}
/**
* Setting a base path will hide the base path from exception and stack trace file names to shorten them
* @return $this
*/
public function setBasePath(string $path = ''): self
{
if ($path !== '') {
$path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
$this->basePath = $path;
return $this;
}
/**
* @return $this
*/
public function includeStacktraces(bool $include = true, ?Closure $parser = null): self
{
$this->includeStacktraces = $include;
if ($this->includeStacktraces) {
$this->allowInlineLineBreaks = true;
$this->stacktracesParser = $parser;
}
return $this;
}
/**
* Indent stack traces to separate them a bit from the main log record messages
*
* @param string $indent The string used to indent, for example " "
* @return $this
*/
public function indentStacktraces(string $indent): self
{
$this->indentStacktraces = $indent;
return $this;
}
/**
* @return $this
*/
public function allowInlineLineBreaks(bool $allow = true): self
{
$this->allowInlineLineBreaks = $allow;
return $this;
}
/**
* @return $this
*/
public function ignoreEmptyContextAndExtra(bool $ignore = true): self
{
$this->ignoreEmptyContextAndExtra = $ignore;
return $this;
}
/**
* Allows cutting the level name to get fixed-length levels like INF for INFO, ERR for ERROR if you set this to 3 for example
*
* @param int|null $maxLevelNameLength Maximum characters for the level name. Set null for infinite length (default)
* @return $this
*/
public function setMaxLevelNameLength(?int $maxLevelNameLength = null): self
{
$this->maxLevelNameLength = $maxLevelNameLength;
return $this;
}
/**
* @inheritDoc
*/
public function format(LogRecord $record): string
{
$vars = parent::format($record);
if ($this->maxLevelNameLength !== null) {
$vars['level_name'] = substr($vars['level_name'], 0, $this->maxLevelNameLength);
}
$output = $this->format;
foreach ($vars['extra'] as $var => $val) {
if (false !== strpos($output, '%extra.'.$var.'%')) {
$output = str_replace('%extra.'.$var.'%', $this->stringify($val), $output);
unset($vars['extra'][$var]);
}
}
foreach ($vars['context'] as $var => $val) {
if (false !== strpos($output, '%context.'.$var.'%')) {
$output = str_replace('%context.'.$var.'%', $this->stringify($val), $output);
unset($vars['context'][$var]);
}
}
if ($this->ignoreEmptyContextAndExtra) {
if (\count($vars['context']) === 0) {
unset($vars['context']);
$output = str_replace('%context%', '', $output);
}
if (\count($vars['extra']) === 0) {
unset($vars['extra']);
$output = str_replace('%extra%', '', $output);
}
}
foreach ($vars as $var => $val) {
if (false !== strpos($output, '%'.$var.'%')) {
$output = str_replace('%'.$var.'%', $this->stringify($val), $output);
}
}
// remove leftover %extra.xxx% and %context.xxx% if any
if (false !== strpos($output, '%')) {
$output = preg_replace('/%(?:extra|context)\..+?%/', '', $output);
if (null === $output) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . preg_last_error_msg());
}
}
return $output;
}
public function formatBatch(array $records): string
{
$message = '';
foreach ($records as $record) {
$message .= $this->format($record);
}
return $message;
}
/**
* @param mixed $value
*/
public function stringify($value): string
{
return $this->replaceNewlines($this->convertToString($value));
}
protected function normalizeException(\Throwable $e, int $depth = 0): string
{
$str = $this->formatException($e);
$previous = $e->getPrevious();
while ($previous instanceof \Throwable) {
$depth++;
if ($depth > $this->maxNormalizeDepth) {
$str .= "\n[previous exception] Over " . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
break;
}
$str .= "\n[previous exception] " . $this->formatException($previous);
$previous = $previous->getPrevious();
}
return $str;
}
/**
* @param mixed $data
*/
protected function convertToString($data): string
{
if (null === $data || \is_bool($data)) {
return var_export($data, true);
}
if (\is_scalar($data)) {
return (string) $data;
}
return $this->toJson($data, true);
}
protected function replaceNewlines(string $str): string
{
if ($this->allowInlineLineBreaks) {
if (0 === strpos($str, '{') || 0 === strpos($str, '[')) {
$str = preg_replace('/(?<!\\\\)\\\\[rn]/', "\n", $str);
if (null === $str) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Failed to run preg_replace: ' . $pcreErrorCode . ' / ' . preg_last_error_msg());
}
}
return $str;
}
return str_replace(["\r\n", "\r", "\n"], ' ', $str);
}
private function formatException(\Throwable $e): string
{
$str = '[object] (' . Utils::getClass($e) . '(code: ' . $e->getCode();
if ($e instanceof \SoapFault) {
if (isset($e->faultcode)) {
$str .= ' faultcode: ' . $e->faultcode;
}
if (isset($e->faultactor)) {
$str .= ' faultactor: ' . $e->faultactor;
}
if (isset($e->detail)) {
if (\is_string($e->detail)) {
$str .= ' detail: ' . $e->detail;
} elseif (\is_object($e->detail) || \is_array($e->detail)) {
$str .= ' detail: ' . $this->toJson($e->detail, true);
}
}
}
$file = $e->getFile();
if ($this->basePath !== '') {
$file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file);
}
$str .= '): ' . $e->getMessage() . ' at ' . strtr((string) $file, DIRECTORY_SEPARATOR, '/') . ':' . $e->getLine() . ')';
if ($this->includeStacktraces) {
$str .= $this->stacktracesParser($e);
}
return $str;
}
private function stacktracesParser(\Throwable $e): string
{
$trace = $e->getTraceAsString();
if ($this->basePath !== '') {
$trace = preg_replace('{^(#\d+ )' . preg_quote($this->basePath) . '}m', '$1', $trace) ?? $trace;
}
if ($this->stacktracesParser !== null) {
$trace = $this->stacktracesParserCustom($trace);
}
if ($this->indentStacktraces !== '') {
$trace = str_replace("\n", "\n{$this->indentStacktraces}", $trace);
}
if (trim($trace) === '') {
return '';
}
return "\n{$this->indentStacktraces}[stacktrace]\n{$this->indentStacktraces}" . strtr($trace, DIRECTORY_SEPARATOR, '/') . "\n";
}
private function stacktracesParserCustom(string $trace): string
{
return implode("\n", array_filter(array_map($this->stacktracesParser, explode("\n", $trace)), fn ($line) => is_string($line) && trim($line) !== ''));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/SyslogFormatter.php | src/Monolog/Formatter/SyslogFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\LogRecord;
/**
* Serializes a log message according to RFC 5424
*
* @author Dalibor Karlović <dalibor.karlovic@sigwin.hr>
* @author Renat Gabdullin <renatobyj@gmail.com>
*/
class SyslogFormatter extends LineFormatter
{
private const SYSLOG_FACILITY_USER = 1;
private const FORMAT = "<%extra.priority%>1 %datetime% %extra.hostname% %extra.app-name% %extra.procid% %channel% %extra.structured-data% %level_name%: %message% %context% %extra%\n";
private const NILVALUE = '-';
private string $hostname;
private int $procid;
public function __construct(private string $applicationName = self::NILVALUE)
{
parent::__construct(self::FORMAT, 'Y-m-d\TH:i:s.uP', true, true);
$this->hostname = (string) gethostname();
$this->procid = (int) getmypid();
}
public function format(LogRecord $record): string
{
$record->extra = $this->formatExtra($record);
return parent::format($record);
}
/**
* @return array<string, mixed>
*/
private function formatExtra(LogRecord $record): array
{
$extra = $record->extra;
$extra['app-name'] = $this->applicationName;
$extra['hostname'] = $this->hostname;
$extra['procid'] = $this->procid;
$extra['priority'] = self::calculatePriority($record->level);
$extra['structured-data'] = self::NILVALUE;
return $extra;
}
private static function calculatePriority(Level $level): int
{
return (self::SYSLOG_FACILITY_USER * 8) + $level->toRFC5424Level();
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/FluentdFormatter.php | src/Monolog/Formatter/FluentdFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\Utils;
use Monolog\LogRecord;
/**
* Class FluentdFormatter
*
* Serializes a log message to Fluentd unix socket protocol
*
* Fluentd config:
*
* <source>
* type unix
* path /var/run/td-agent/td-agent.sock
* </source>
*
* Monolog setup:
*
* $logger = new Monolog\Logger('fluent.tag');
* $fluentHandler = new Monolog\Handler\SocketHandler('unix:///var/run/td-agent/td-agent.sock');
* $fluentHandler->setFormatter(new Monolog\Formatter\FluentdFormatter());
* $logger->pushHandler($fluentHandler);
*
* @author Andrius Putna <fordnox@gmail.com>
*/
class FluentdFormatter implements FormatterInterface
{
/**
* @var bool $levelTag should message level be a part of the fluentd tag
*/
protected bool $levelTag = false;
public function __construct(bool $levelTag = false)
{
$this->levelTag = $levelTag;
}
public function isUsingLevelsInTag(): bool
{
return $this->levelTag;
}
public function format(LogRecord $record): string
{
$tag = $record->channel;
if ($this->levelTag) {
$tag .= '.' . $record->level->toPsrLogLevel();
}
$message = [
'message' => $record->message,
'context' => $record->context,
'extra' => $record->extra,
];
if (!$this->levelTag) {
$message['level'] = $record->level->value;
$message['level_name'] = $record->level->getName();
}
return Utils::jsonEncode([$tag, $record->datetime->getTimestamp(), $message]);
}
public function formatBatch(array $records): string
{
$message = '';
foreach ($records as $record) {
$message .= $this->format($record);
}
return $message;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/GoogleCloudLoggingFormatter.php | src/Monolog/Formatter/GoogleCloudLoggingFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use DateTimeInterface;
use Monolog\LogRecord;
/**
* Encodes message information into JSON in a format compatible with Cloud logging.
*
* @see https://cloud.google.com/logging/docs/structured-logging
* @see https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
*
* @author Luís Cobucci <lcobucci@gmail.com>
*/
class GoogleCloudLoggingFormatter extends JsonFormatter
{
protected function normalizeRecord(LogRecord $record): array
{
$normalized = parent::normalizeRecord($record);
// Re-key level for GCP logging
$normalized['severity'] = $normalized['level_name'];
$normalized['time'] = $record->datetime->format(DateTimeInterface::RFC3339_EXTENDED);
// Remove keys that are not used by GCP
unset($normalized['level'], $normalized['level_name'], $normalized['datetime']);
return $normalized;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/LogmaticFormatter.php | src/Monolog/Formatter/LogmaticFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\LogRecord;
/**
* Encodes message information into JSON in a format compatible with Logmatic.
*
* @author Julien Breux <julien.breux@gmail.com>
*/
class LogmaticFormatter extends JsonFormatter
{
protected const MARKERS = ["sourcecode", "php"];
protected string $hostname = '';
protected string $appName = '';
/**
* @return $this
*/
public function setHostname(string $hostname): self
{
$this->hostname = $hostname;
return $this;
}
/**
* @return $this
*/
public function setAppName(string $appName): self
{
$this->appName = $appName;
return $this;
}
/**
* Appends the 'hostname' and 'appname' parameter for indexing by Logmatic.
*
* @see http://doc.logmatic.io/docs/basics-to-send-data
* @see \Monolog\Formatter\JsonFormatter::format()
*/
public function normalizeRecord(LogRecord $record): array
{
$record = parent::normalizeRecord($record);
if ($this->hostname !== '') {
$record["hostname"] = $this->hostname;
}
if ($this->appName !== '') {
$record["appname"] = $this->appName;
}
$record["@marker"] = static::MARKERS;
return $record;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/FlowdockFormatter.php | src/Monolog/Formatter/FlowdockFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\LogRecord;
/**
* formats the record to be used in the FlowdockHandler
*
* @author Dominik Liebler <liebler.dominik@gmail.com>
* @deprecated Since 2.9.0 and 3.3.0, Flowdock was shutdown we will thus drop this handler in Monolog 4
*/
class FlowdockFormatter implements FormatterInterface
{
private string $source;
private string $sourceEmail;
public function __construct(string $source, string $sourceEmail)
{
$this->source = $source;
$this->sourceEmail = $sourceEmail;
}
/**
* @inheritDoc
*
* @return mixed[]
*/
public function format(LogRecord $record): array
{
$tags = [
'#logs',
'#' . $record->level->toPsrLogLevel(),
'#' . $record->channel,
];
foreach ($record->extra as $value) {
$tags[] = '#' . $value;
}
$subject = sprintf(
'in %s: %s - %s',
$this->source,
$record->level->getName(),
$this->getShortMessage($record->message)
);
return [
'source' => $this->source,
'from_address' => $this->sourceEmail,
'subject' => $subject,
'content' => $record->message,
'tags' => $tags,
'project' => $this->source,
];
}
/**
* @inheritDoc
*
* @return mixed[][]
*/
public function formatBatch(array $records): array
{
$formatted = [];
foreach ($records as $record) {
$formatted[] = $this->format($record);
}
return $formatted;
}
public function getShortMessage(string $message): string
{
static $hasMbString;
if (null === $hasMbString) {
$hasMbString = \function_exists('mb_strlen');
}
$maxLength = 45;
if ($hasMbString) {
if (mb_strlen($message, 'UTF-8') > $maxLength) {
$message = mb_substr($message, 0, $maxLength - 4, 'UTF-8') . ' ...';
}
} else {
if (\strlen($message) > $maxLength) {
$message = substr($message, 0, $maxLength - 4) . ' ...';
}
}
return $message;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/NormalizerFormatter.php | src/Monolog/Formatter/NormalizerFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\JsonSerializableDateTimeImmutable;
use Monolog\Utils;
use Throwable;
use Monolog\LogRecord;
/**
* Normalizes incoming records to remove objects/resources so it's easier to dump to various targets
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class NormalizerFormatter implements FormatterInterface
{
public const SIMPLE_DATE = "Y-m-d\TH:i:sP";
protected string $dateFormat;
protected int $maxNormalizeDepth = 9;
protected int $maxNormalizeItemCount = 1000;
private int $jsonEncodeOptions = Utils::DEFAULT_JSON_FLAGS;
protected string $basePath = '';
/**
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
*/
public function __construct(?string $dateFormat = null)
{
$this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat;
}
/**
* @inheritDoc
*/
public function format(LogRecord $record)
{
return $this->normalizeRecord($record);
}
/**
* Normalize an arbitrary value to a scalar|array|null
*
* @return null|scalar|array<mixed[]|scalar|null>
*/
public function normalizeValue(mixed $data): mixed
{
return $this->normalize($data);
}
/**
* @inheritDoc
*/
public function formatBatch(array $records)
{
foreach ($records as $key => $record) {
$records[$key] = $this->format($record);
}
return $records;
}
public function getDateFormat(): string
{
return $this->dateFormat;
}
/**
* @return $this
*/
public function setDateFormat(string $dateFormat): self
{
$this->dateFormat = $dateFormat;
return $this;
}
/**
* The maximum number of normalization levels to go through
*/
public function getMaxNormalizeDepth(): int
{
return $this->maxNormalizeDepth;
}
/**
* @return $this
*/
public function setMaxNormalizeDepth(int $maxNormalizeDepth): self
{
$this->maxNormalizeDepth = $maxNormalizeDepth;
return $this;
}
/**
* The maximum number of items to normalize per level
*/
public function getMaxNormalizeItemCount(): int
{
return $this->maxNormalizeItemCount;
}
/**
* @return $this
*/
public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self
{
$this->maxNormalizeItemCount = $maxNormalizeItemCount;
return $this;
}
/**
* Enables `json_encode` pretty print.
*
* @return $this
*/
public function setJsonPrettyPrint(bool $enable): self
{
if ($enable) {
$this->jsonEncodeOptions |= JSON_PRETTY_PRINT;
} else {
$this->jsonEncodeOptions &= ~JSON_PRETTY_PRINT;
}
return $this;
}
/**
* Setting a base path will hide the base path from exception and stack trace file names to shorten them
* @return $this
*/
public function setBasePath(string $path = ''): self
{
if ($path !== '') {
$path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
$this->basePath = $path;
return $this;
}
/**
* Provided as extension point
*
* Because normalize is called with sub-values of context data etc, normalizeRecord can be
* extended when data needs to be appended on the record array but not to other normalized data.
*
* @return array<mixed[]|scalar|null>
*/
protected function normalizeRecord(LogRecord $record): array
{
/** @var array<mixed[]|scalar|null> $normalized */
$normalized = $this->normalize($record->toArray());
return $normalized;
}
/**
* @return null|scalar|array<mixed[]|scalar|null>
*/
protected function normalize(mixed $data, int $depth = 0): mixed
{
if ($depth > $this->maxNormalizeDepth) {
return 'Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization';
}
if (null === $data || \is_scalar($data)) {
if (\is_float($data)) {
if (is_infinite($data)) {
return ($data > 0 ? '' : '-') . 'INF';
}
if (is_nan($data)) {
return 'NaN';
}
}
return $data;
}
if (\is_array($data)) {
$normalized = [];
$count = 1;
foreach ($data as $key => $value) {
if ($count++ > $this->maxNormalizeItemCount) {
$normalized['...'] = 'Over ' . $this->maxNormalizeItemCount . ' items ('.\count($data).' total), aborting normalization';
break;
}
$normalized[$key] = $this->normalize($value, $depth + 1);
}
return $normalized;
}
if ($data instanceof \DateTimeInterface) {
return $this->formatDate($data);
}
if (\is_object($data)) {
if ($data instanceof Throwable) {
return $this->normalizeException($data, $depth);
}
if ($data instanceof \JsonSerializable) {
/** @var null|scalar|array<mixed[]|scalar|null> $value */
$value = $data->jsonSerialize();
} elseif (\get_class($data) === '__PHP_Incomplete_Class') {
$accessor = new \ArrayObject($data);
$value = (string) $accessor['__PHP_Incomplete_Class_Name'];
} elseif (method_exists($data, '__toString')) {
try {
/** @var string $value */
$value = $data->__toString();
} catch (\Throwable) {
// if the toString method is failing, use the default behavior
/** @var null|scalar|array<mixed[]|scalar|null> $value */
$value = json_decode($this->toJson($data, true), true);
}
} else {
// the rest is normalized by json encoding and decoding it
/** @var null|scalar|array<mixed[]|scalar|null> $value */
$value = json_decode($this->toJson($data, true), true);
}
return [Utils::getClass($data) => $value];
}
if (\is_resource($data)) {
return sprintf('[resource(%s)]', get_resource_type($data));
}
return '[unknown('.\gettype($data).')]';
}
/**
* @return array<array-key, string|int|array<string|int|array<string>>>
*/
protected function normalizeException(Throwable $e, int $depth = 0)
{
if ($depth > $this->maxNormalizeDepth) {
return ['Over ' . $this->maxNormalizeDepth . ' levels deep, aborting normalization'];
}
if ($e instanceof \JsonSerializable) {
return (array) $e->jsonSerialize();
}
$file = $e->getFile();
if ($this->basePath !== '') {
$file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file);
}
$data = [
'class' => Utils::getClass($e),
'message' => $e->getMessage(),
'code' => (int) $e->getCode(),
'file' => $file.':'.$e->getLine(),
];
if ($e instanceof \SoapFault) {
if (isset($e->faultcode)) {
$data['faultcode'] = $e->faultcode;
}
if (isset($e->faultactor)) {
$data['faultactor'] = $e->faultactor;
}
if (isset($e->detail)) {
if (\is_string($e->detail)) {
$data['detail'] = $e->detail;
} elseif (\is_object($e->detail) || \is_array($e->detail)) {
$data['detail'] = $this->toJson($e->detail, true);
}
}
}
$trace = $e->getTrace();
foreach ($trace as $frame) {
if (isset($frame['file'], $frame['line'])) {
$file = $frame['file'];
if ($this->basePath !== '') {
$file = preg_replace('{^'.preg_quote($this->basePath).'}', '', $file);
}
$data['trace'][] = $file.':'.$frame['line'];
}
}
if (($previous = $e->getPrevious()) instanceof \Throwable) {
$data['previous'] = $this->normalizeException($previous, $depth + 1);
}
return $data;
}
/**
* Return the JSON representation of a value
*
* @param mixed $data
* @throws \RuntimeException if encoding fails and errors are not ignored
* @return string if encoding fails and ignoreErrors is true 'null' is returned
*/
protected function toJson($data, bool $ignoreErrors = false): string
{
return Utils::jsonEncode($data, $this->jsonEncodeOptions, $ignoreErrors);
}
protected function formatDate(\DateTimeInterface $date): string
{
// in case the date format isn't custom then we defer to the custom JsonSerializableDateTimeImmutable
// formatting logic, which will pick the right format based on whether useMicroseconds is on
if ($this->dateFormat === self::SIMPLE_DATE && $date instanceof JsonSerializableDateTimeImmutable) {
return (string) $date;
}
return $date->format($this->dateFormat);
}
/**
* @return $this
*/
public function addJsonEncodeOption(int $option): self
{
$this->jsonEncodeOptions |= $option;
return $this;
}
/**
* @return $this
*/
public function removeJsonEncodeOption(int $option): self
{
$this->jsonEncodeOptions &= ~$option;
return $this;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/JsonFormatter.php | src/Monolog/Formatter/JsonFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Stringable;
use Throwable;
use Monolog\LogRecord;
/**
* Encodes whatever record data is passed to it as json
*
* This can be useful to log to databases or remote APIs
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class JsonFormatter extends NormalizerFormatter
{
public const BATCH_MODE_JSON = 1;
public const BATCH_MODE_NEWLINES = 2;
/** @var self::BATCH_MODE_* */
protected int $batchMode;
protected bool $appendNewline;
protected bool $ignoreEmptyContextAndExtra;
protected bool $includeStacktraces = false;
/**
* @param self::BATCH_MODE_* $batchMode
*/
public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = true, bool $ignoreEmptyContextAndExtra = false, bool $includeStacktraces = false)
{
$this->batchMode = $batchMode;
$this->appendNewline = $appendNewline;
$this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra;
$this->includeStacktraces = $includeStacktraces;
parent::__construct();
}
/**
* The batch mode option configures the formatting style for
* multiple records. By default, multiple records will be
* formatted as a JSON-encoded array. However, for
* compatibility with some API endpoints, alternative styles
* are available.
*/
public function getBatchMode(): int
{
return $this->batchMode;
}
/**
* True if newlines are appended to every formatted record
*/
public function isAppendingNewlines(): bool
{
return $this->appendNewline;
}
/**
* @inheritDoc
*/
public function format(LogRecord $record): string
{
$normalized = $this->normalizeRecord($record);
return $this->toJson($normalized, true) . ($this->appendNewline ? "\n" : '');
}
/**
* @inheritDoc
*/
public function formatBatch(array $records): string
{
return match ($this->batchMode) {
static::BATCH_MODE_NEWLINES => $this->formatBatchNewlines($records),
default => $this->formatBatchJson($records),
};
}
/**
* @return $this
*/
public function includeStacktraces(bool $include = true): self
{
$this->includeStacktraces = $include;
return $this;
}
/**
* @return array<array<mixed>|bool|float|int|\stdClass|string|null>
*/
protected function normalizeRecord(LogRecord $record): array
{
$normalized = parent::normalizeRecord($record);
if (isset($normalized['context']) && $normalized['context'] === []) {
if ($this->ignoreEmptyContextAndExtra) {
unset($normalized['context']);
} else {
$normalized['context'] = new \stdClass;
}
}
if (isset($normalized['extra']) && $normalized['extra'] === []) {
if ($this->ignoreEmptyContextAndExtra) {
unset($normalized['extra']);
} else {
$normalized['extra'] = new \stdClass;
}
}
return $normalized;
}
/**
* Return a JSON-encoded array of records.
*
* @phpstan-param LogRecord[] $records
*/
protected function formatBatchJson(array $records): string
{
$formatted = array_map(fn (LogRecord $record) => $this->normalizeRecord($record), $records);
return $this->toJson($formatted, true);
}
/**
* Use new lines to separate records instead of a
* JSON-encoded array.
*
* @phpstan-param LogRecord[] $records
*/
protected function formatBatchNewlines(array $records): string
{
$oldNewline = $this->appendNewline;
$this->appendNewline = false;
$formatted = array_map(fn (LogRecord $record) => $this->format($record), $records);
$this->appendNewline = $oldNewline;
return implode("\n", $formatted);
}
/**
* Normalizes given $data.
*
* @return null|scalar|array<mixed[]|scalar|null|object>|object
*/
protected function normalize(mixed $data, int $depth = 0): mixed
{
if ($depth > $this->maxNormalizeDepth) {
return 'Over '.$this->maxNormalizeDepth.' levels deep, aborting normalization';
}
if (\is_array($data)) {
$normalized = [];
$count = 1;
foreach ($data as $key => $value) {
if ($count++ > $this->maxNormalizeItemCount) {
$normalized['...'] = 'Over '.$this->maxNormalizeItemCount.' items ('.\count($data).' total), aborting normalization';
break;
}
$normalized[$key] = $this->normalize($value, $depth + 1);
}
return $normalized;
}
if (\is_object($data)) {
if ($data instanceof \DateTimeInterface) {
return $this->formatDate($data);
}
if ($data instanceof Throwable) {
return $this->normalizeException($data, $depth);
}
// if the object has specific json serializability we want to make sure we skip the __toString treatment below
if ($data instanceof \JsonSerializable) {
return $data;
}
if ($data instanceof Stringable) {
try {
return $data->__toString();
} catch (Throwable) {
return $data::class;
}
}
if (\get_class($data) === '__PHP_Incomplete_Class') {
return new \ArrayObject($data);
}
return $data;
}
if (\is_resource($data)) {
return parent::normalize($data);
}
return $data;
}
/**
* Normalizes given exception with or without its own stack trace based on
* `includeStacktraces` property.
*
* @return array<array-key, string|int|array<string|int|array<string>>>
*/
protected function normalizeException(Throwable $e, int $depth = 0): array
{
$data = parent::normalizeException($e, $depth);
if (!$this->includeStacktraces) {
unset($data['trace']);
}
return $data;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/GelfMessageFormatter.php | src/Monolog/Formatter/GelfMessageFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\Level;
use Gelf\Message;
use Monolog\Utils;
use Monolog\LogRecord;
/**
* Serializes a log message to GELF
* @see http://docs.graylog.org/en/latest/pages/gelf.html
*
* @author Matt Lehner <mlehner@gmail.com>
*/
class GelfMessageFormatter extends NormalizerFormatter
{
protected const DEFAULT_MAX_LENGTH = 32766;
/**
* @var string the name of the system for the Gelf log message
*/
protected string $systemName;
/**
* @var string a prefix for 'extra' fields from the Monolog record (optional)
*/
protected string $extraPrefix;
/**
* @var string a prefix for 'context' fields from the Monolog record (optional)
*/
protected string $contextPrefix;
/**
* @var int max length per field
*/
protected int $maxLength;
/**
* Translates Monolog log levels to Graylog2 log priorities.
*/
private function getGraylog2Priority(Level $level): int
{
return match ($level) {
Level::Debug => 7,
Level::Info => 6,
Level::Notice => 5,
Level::Warning => 4,
Level::Error => 3,
Level::Critical => 2,
Level::Alert => 1,
Level::Emergency => 0,
};
}
/**
* @throws \RuntimeException
*/
public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null)
{
if (!class_exists(Message::class)) {
throw new \RuntimeException('Composer package graylog2/gelf-php is required to use Monolog\'s GelfMessageFormatter');
}
parent::__construct('U.u');
$this->systemName = (null === $systemName || $systemName === '') ? (string) gethostname() : $systemName;
$this->extraPrefix = null === $extraPrefix ? '' : $extraPrefix;
$this->contextPrefix = $contextPrefix;
$this->maxLength = null === $maxLength ? self::DEFAULT_MAX_LENGTH : $maxLength;
}
/**
* @inheritDoc
*/
public function format(LogRecord $record): Message
{
$context = $extra = [];
if (isset($record->context)) {
/** @var array<array<mixed>|bool|float|int|string|null> $context */
$context = parent::normalize($record->context);
}
if (isset($record->extra)) {
/** @var array<array<mixed>|bool|float|int|string|null> $extra */
$extra = parent::normalize($record->extra);
}
$message = new Message();
$message
->setTimestamp($record->datetime)
->setShortMessage($record->message)
->setHost($this->systemName)
->setLevel($this->getGraylog2Priority($record->level));
// message length + system name length + 200 for padding / metadata
$len = 200 + \strlen($record->message) + \strlen($this->systemName);
if ($len > $this->maxLength) {
$message->setShortMessage(Utils::substr($record->message, 0, $this->maxLength));
}
if (isset($record->channel)) {
$message->setAdditional('facility', $record->channel);
}
foreach ($extra as $key => $val) {
$key = (string) preg_replace('#[^\w.-]#', '-', (string) $key);
$val = \is_bool($val) ? ($val ? 1 : 0) : $val;
$val = \is_scalar($val) || null === $val ? $val : $this->toJson($val);
$len = \strlen($this->extraPrefix . $key . $val);
if ($len > $this->maxLength) {
$message->setAdditional($this->extraPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength));
continue;
}
$message->setAdditional($this->extraPrefix . $key, $val);
}
foreach ($context as $key => $val) {
$key = (string) preg_replace('#[^\w.-]#', '-', (string) $key);
$val = \is_bool($val) ? ($val ? 1 : 0) : $val;
$val = \is_scalar($val) || null === $val ? $val : $this->toJson($val);
$len = \strlen($this->contextPrefix . $key . $val);
if ($len > $this->maxLength) {
$message->setAdditional($this->contextPrefix . $key, Utils::substr((string) $val, 0, $this->maxLength));
continue;
}
$message->setAdditional($this->contextPrefix . $key, $val);
}
if (!$message->hasAdditional('file') && isset($context['exception']['file'])) {
if (1 === preg_match("/^(.+):([0-9]+)$/", $context['exception']['file'], $matches)) {
$message->setAdditional('file', $matches[1]);
$message->setAdditional('line', $matches[2]);
}
}
return $message;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/FormatterInterface.php | src/Monolog/Formatter/FormatterInterface.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\LogRecord;
/**
* Interface for formatters
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface FormatterInterface
{
/**
* Formats a log record.
*
* @param LogRecord $record A record to format
* @return mixed The formatted record
*/
public function format(LogRecord $record);
/**
* Formats a set of log records.
*
* @param array<LogRecord> $records A set of records to format
* @return mixed The formatted set of records
*/
public function formatBatch(array $records);
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/LogstashFormatter.php | src/Monolog/Formatter/LogstashFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\LogRecord;
/**
* Serializes a log message to Logstash Event Format
*
* @see https://www.elastic.co/products/logstash
* @see https://github.com/elastic/logstash/blob/master/logstash-core/src/main/java/org/logstash/Event.java
*
* @author Tim Mower <timothy.mower@gmail.com>
*/
class LogstashFormatter extends NormalizerFormatter
{
/**
* @var string the name of the system for the Logstash log message, used to fill the @source field
*/
protected string $systemName;
/**
* @var string an application name for the Logstash log message, used to fill the @type field
*/
protected string $applicationName;
/**
* @var string the key for 'extra' fields from the Monolog record
*/
protected string $extraKey;
/**
* @var string the key for 'context' fields from the Monolog record
*/
protected string $contextKey;
/**
* @param string $applicationName The application that sends the data, used as the "type" field of logstash
* @param string|null $systemName The system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine
* @param string $extraKey The key for extra keys inside logstash "fields", defaults to extra
* @param string $contextKey The key for context keys inside logstash "fields", defaults to context
*/
public function __construct(string $applicationName, ?string $systemName = null, string $extraKey = 'extra', string $contextKey = 'context')
{
// logstash requires a ISO 8601 format date with optional millisecond precision.
parent::__construct('Y-m-d\TH:i:s.uP');
$this->systemName = $systemName === null ? (string) gethostname() : $systemName;
$this->applicationName = $applicationName;
$this->extraKey = $extraKey;
$this->contextKey = $contextKey;
}
/**
* @inheritDoc
*/
public function format(LogRecord $record): string
{
$recordData = parent::format($record);
$message = [
'@timestamp' => $recordData['datetime'],
'@version' => 1,
'host' => $this->systemName,
];
if (isset($recordData['message'])) {
$message['message'] = $recordData['message'];
}
if (isset($recordData['channel'])) {
$message['type'] = $recordData['channel'];
$message['channel'] = $recordData['channel'];
}
if (isset($recordData['level_name'])) {
$message['level'] = $recordData['level_name'];
}
if (isset($recordData['level'])) {
$message['monolog_level'] = $recordData['level'];
}
if ('' !== $this->applicationName) {
$message['type'] = $this->applicationName;
}
if (\count($recordData['extra']) > 0) {
$message[$this->extraKey] = $recordData['extra'];
}
if (\count($recordData['context']) > 0) {
$message[$this->contextKey] = $recordData['context'];
}
return $this->toJson($message) . "\n";
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/HtmlFormatter.php | src/Monolog/Formatter/HtmlFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\Utils;
use Monolog\LogRecord;
/**
* Formats incoming records into an HTML table
*
* This is especially useful for html email logging
*
* @author Tiago Brito <tlfbrito@gmail.com>
*/
class HtmlFormatter extends NormalizerFormatter
{
/**
* Translates Monolog log levels to html color priorities.
*/
protected function getLevelColor(Level $level): string
{
return match ($level) {
Level::Debug => '#CCCCCC',
Level::Info => '#28A745',
Level::Notice => '#17A2B8',
Level::Warning => '#FFC107',
Level::Error => '#FD7E14',
Level::Critical => '#DC3545',
Level::Alert => '#821722',
Level::Emergency => '#000000',
};
}
/**
* @param string|null $dateFormat The format of the timestamp: one supported by DateTime::format
*/
public function __construct(?string $dateFormat = null)
{
parent::__construct($dateFormat);
}
/**
* Creates an HTML table row
*
* @param string $th Row header content
* @param string $td Row standard cell content
* @param bool $escapeTd false if td content must not be html escaped
*/
protected function addRow(string $th, string $td = ' ', bool $escapeTd = true): string
{
$th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8');
if ($escapeTd) {
$td = '<pre>'.htmlspecialchars($td, ENT_NOQUOTES, 'UTF-8').'</pre>';
}
return "<tr style=\"padding: 4px;text-align: left;\">\n<th style=\"vertical-align: top;background: #ccc;color: #000\" width=\"100\">$th:</th>\n<td style=\"padding: 4px;text-align: left;vertical-align: top;background: #eee;color: #000\">".$td."</td>\n</tr>";
}
/**
* Create a HTML h1 tag
*
* @param string $title Text to be in the h1
*/
protected function addTitle(string $title, Level $level): string
{
$title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8');
return '<h1 style="background: '.$this->getLevelColor($level).';color: #ffffff;padding: 5px;" class="monolog-output">'.$title.'</h1>';
}
/**
* Formats a log record.
*
* @return string The formatted record
*/
public function format(LogRecord $record): string
{
$output = $this->addTitle($record->level->getName(), $record->level);
$output .= '<table cellspacing="1" width="100%" class="monolog-output">';
$output .= $this->addRow('Message', $record->message);
$output .= $this->addRow('Time', $this->formatDate($record->datetime));
$output .= $this->addRow('Channel', $record->channel);
if (\count($record->context) > 0) {
$embeddedTable = '<table cellspacing="1" width="100%">';
foreach ($record->context as $key => $value) {
$embeddedTable .= $this->addRow((string) $key, $this->convertToString($value));
}
$embeddedTable .= '</table>';
$output .= $this->addRow('Context', $embeddedTable, false);
}
if (\count($record->extra) > 0) {
$embeddedTable = '<table cellspacing="1" width="100%">';
foreach ($record->extra as $key => $value) {
$embeddedTable .= $this->addRow((string) $key, $this->convertToString($value));
}
$embeddedTable .= '</table>';
$output .= $this->addRow('Extra', $embeddedTable, false);
}
return $output.'</table>';
}
/**
* Formats a set of log records.
*
* @return string The formatted set of records
*/
public function formatBatch(array $records): string
{
$message = '';
foreach ($records as $record) {
$message .= $this->format($record);
}
return $message;
}
/**
* @param mixed $data
*/
protected function convertToString($data): string
{
if (null === $data || \is_scalar($data)) {
return (string) $data;
}
$data = $this->normalize($data);
return Utils::jsonEncode($data, JSON_PRETTY_PRINT | Utils::DEFAULT_JSON_FLAGS, true);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/LogglyFormatter.php | src/Monolog/Formatter/LogglyFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Monolog\LogRecord;
/**
* Encodes message information into JSON in a format compatible with Loggly.
*
* @author Adam Pancutt <adam@pancutt.com>
*/
class LogglyFormatter extends JsonFormatter
{
/**
* Overrides the default batch mode to new lines for compatibility with the
* Loggly bulk API.
*/
public function __construct(int $batchMode = self::BATCH_MODE_NEWLINES, bool $appendNewline = false)
{
parent::__construct($batchMode, $appendNewline);
}
/**
* Appends the 'timestamp' parameter for indexing by Loggly.
*
* @see https://www.loggly.com/docs/automated-parsing/#json
* @see \Monolog\Formatter\JsonFormatter::format()
*/
protected function normalizeRecord(LogRecord $record): array
{
$recordData = parent::normalizeRecord($record);
$recordData["timestamp"] = $record->datetime->format("Y-m-d\TH:i:s.uO");
unset($recordData["datetime"]);
return $recordData;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Formatter/ElasticaFormatter.php | src/Monolog/Formatter/ElasticaFormatter.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Formatter;
use Elastica\Document;
use Monolog\LogRecord;
/**
* Format a log message into an Elastica Document
*
* @author Jelle Vink <jelle.vink@gmail.com>
*/
class ElasticaFormatter extends NormalizerFormatter
{
/**
* @var string Elastic search index name
*/
protected string $index;
/**
* @var string|null Elastic search document type
*/
protected string|null $type;
/**
* @param string $index Elastic Search index name
* @param ?string $type Elastic Search document type, deprecated as of Elastica 7
*/
public function __construct(string $index, ?string $type)
{
// elasticsearch requires a ISO 8601 format date with optional millisecond precision.
parent::__construct('Y-m-d\TH:i:s.uP');
$this->index = $index;
$this->type = $type;
}
/**
* @inheritDoc
*/
public function format(LogRecord $record)
{
$record = parent::format($record);
return $this->getDocument($record);
}
public function getIndex(): string
{
return $this->index;
}
/**
* @deprecated since Elastica 7 type has no effect
*/
public function getType(): string
{
/** @phpstan-ignore-next-line */
return $this->type;
}
/**
* Convert a log message into an Elastica Document
*
* @param mixed[] $record
*/
protected function getDocument(array $record): Document
{
$document = new Document();
$document->setData($record);
$document->setIndex($this->index);
return $document;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Test/TestCase.php | src/Monolog/Test/TestCase.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Test;
/**
* Lets you easily generate log records and a dummy formatter for testing purposes
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated use MonologTestCase instead.
*/
class TestCase extends MonologTestCase
{
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Test/MonologTestCase.php | src/Monolog/Test/MonologTestCase.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Test;
use Monolog\Level;
use Monolog\Logger;
use Monolog\LogRecord;
use Monolog\JsonSerializableDateTimeImmutable;
use Monolog\Formatter\FormatterInterface;
use Psr\Log\LogLevel;
/**
* Lets you easily generate log records and a dummy formatter for testing purposes
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class MonologTestCase extends \PHPUnit\Framework\TestCase
{
/**
* @param array<mixed> $context
* @param array<mixed> $extra
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
*/
protected function getRecord(int|string|Level $level = Level::Warning, string|\Stringable $message = 'test', array $context = [], string $channel = 'test', \DateTimeImmutable $datetime = new JsonSerializableDateTimeImmutable(true), array $extra = []): LogRecord
{
return new LogRecord(
message: (string) $message,
context: $context,
level: Logger::toMonologLevel($level),
channel: $channel,
datetime: $datetime,
extra: $extra,
);
}
/**
* @phpstan-return list<LogRecord>
*/
protected function getMultipleRecords(): array
{
return [
$this->getRecord(Level::Debug, 'debug message 1'),
$this->getRecord(Level::Debug, 'debug message 2'),
$this->getRecord(Level::Info, 'information'),
$this->getRecord(Level::Warning, 'warning'),
$this->getRecord(Level::Error, 'error'),
];
}
protected function getIdentityFormatter(): FormatterInterface
{
$formatter = $this->createMock(FormatterInterface::class);
$formatter->expects(self::any())
->method('format')
->willReturnCallback(function ($record) {
return $record->message;
});
return $formatter;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/GelfHandler.php | src/Monolog/Handler/GelfHandler.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Gelf\PublisherInterface;
use Monolog\Level;
use Monolog\Formatter\GelfMessageFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord;
/**
* Handler to send messages to a Graylog2 (http://www.graylog2.org) server
*
* @author Matt Lehner <mlehner@gmail.com>
* @author Benjamin Zikarsky <benjamin@zikarsky.de>
*/
class GelfHandler extends AbstractProcessingHandler
{
/**
* @var PublisherInterface the publisher object that sends the message to the server
*/
protected PublisherInterface $publisher;
/**
* @param PublisherInterface $publisher a gelf publisher object
*/
public function __construct(PublisherInterface $publisher, int|string|Level $level = Level::Debug, bool $bubble = true)
{
parent::__construct($level, $bubble);
$this->publisher = $publisher;
}
/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
$this->publisher->publish($record->formatted);
}
/**
* @inheritDoc
*/
protected function getDefaultFormatter(): FormatterInterface
{
return new GelfMessageFormatter();
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/LogEntriesHandler.php | src/Monolog/Handler/LogEntriesHandler.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
use Monolog\LogRecord;
/**
* @author Robert Kaufmann III <rok3@rok3.me>
*/
class LogEntriesHandler extends SocketHandler
{
protected string $logToken;
/**
* @param string $token Log token supplied by LogEntries
* @param bool $useSSL Whether or not SSL encryption should be used.
* @param string $host Custom hostname to send the data to if needed
*
* @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
*/
public function __construct(
string $token,
bool $useSSL = true,
$level = Level::Debug,
bool $bubble = true,
string $host = 'data.logentries.com',
bool $persistent = false,
float $timeout = 0.0,
float $writingTimeout = 10.0,
?float $connectionTimeout = null,
?int $chunkSize = null
) {
if ($useSSL && !\extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler');
}
$endpoint = $useSSL ? 'ssl://' . $host . ':443' : $host . ':80';
parent::__construct(
$endpoint,
$level,
$bubble,
$persistent,
$timeout,
$writingTimeout,
$connectionTimeout,
$chunkSize
);
$this->logToken = $token;
}
/**
* @inheritDoc
*/
protected function generateDataStream(LogRecord $record): string
{
return $this->logToken . ' ' . $record->formatted;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |