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 |
|---|---|---|---|---|---|---|---|---|
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/FleepHookHandler.php | src/Monolog/Handler/FleepHookHandler.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\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;
use Monolog\Level;
use Monolog\LogRecord;
/**
* Sends logs to Fleep.io using Webhook integrations
*
* You'll need a Fleep.io account to use this handler.
*
* @see https://fleep.io/integrations/webhooks/ Fleep Webhooks Documentation
* @author Ando Roots <ando@sqroot.eu>
*/
class FleepHookHandler extends SocketHandler
{
protected const FLEEP_HOST = 'fleep.io';
protected const FLEEP_HOOK_URI = '/hook/';
/**
* @var string Webhook token (specifies the conversation where logs are sent)
*/
protected string $token;
/**
* Construct a new Fleep.io Handler.
*
* For instructions on how to create a new web hook in your conversations
* see https://fleep.io/integrations/webhooks/
*
* @param string $token Webhook token
* @throws MissingExtensionException if OpenSSL is missing
*/
public function __construct(
string $token,
$level = Level::Debug,
bool $bubble = true,
bool $persistent = false,
float $timeout = 0.0,
float $writingTimeout = 10.0,
?float $connectionTimeout = null,
?int $chunkSize = null
) {
if (!\extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler');
}
$this->token = $token;
$connectionString = 'ssl://' . static::FLEEP_HOST . ':443';
parent::__construct(
$connectionString,
$level,
$bubble,
$persistent,
$timeout,
$writingTimeout,
$connectionTimeout,
$chunkSize
);
}
/**
* Returns the default formatter to use with this handler
*
* Overloaded to remove empty context and extra arrays from the end of the log message.
*
* @return LineFormatter
*/
protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter(null, null, true, true);
}
/**
* Handles a log record
*/
public function write(LogRecord $record): void
{
parent::write($record);
$this->closeSocket();
}
/**
* @inheritDoc
*/
protected function generateDataStream(LogRecord $record): string
{
$content = $this->buildContent($record);
return $this->buildHeader($content) . $content;
}
/**
* Builds the header of the API Call
*/
private function buildHeader(string $content): string
{
$header = "POST " . static::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n";
$header .= "Host: " . static::FLEEP_HOST . "\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . \strlen($content) . "\r\n";
$header .= "\r\n";
return $header;
}
/**
* Builds the body of API call
*/
private function buildContent(LogRecord $record): string
{
$dataArray = [
'message' => $record->formatted,
];
return http_build_query($dataArray);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/NullHandler.php | src/Monolog/Handler/NullHandler.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 Psr\Log\LogLevel;
use Monolog\Logger;
use Monolog\LogRecord;
/**
* Blackhole
*
* Any record it can handle will be thrown away. This can be used
* to put on top of an existing stack to override it temporarily.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class NullHandler extends Handler
{
private Level $level;
/**
* @param string|int|Level $level The minimum logging level at which this handler will be triggered
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $level
*/
public function __construct(string|int|Level $level = Level::Debug)
{
$this->level = Logger::toMonologLevel($level);
}
/**
* @inheritDoc
*/
public function isHandling(LogRecord $record): bool
{
return $record->level->value >= $this->level->value;
}
/**
* @inheritDoc
*/
public function handle(LogRecord $record): bool
{
return $record->level->value >= $this->level->value;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/CouchDBHandler.php | src/Monolog/Handler/CouchDBHandler.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\Formatter\FormatterInterface;
use Monolog\Formatter\JsonFormatter;
use Monolog\Level;
use Monolog\LogRecord;
/**
* CouchDB handler
*
* @author Markus Bachmann <markus.bachmann@bachi.biz>
* @phpstan-type Options array{
* host: string,
* port: int,
* dbname: string,
* username: string|null,
* password: string|null
* }
* @phpstan-type InputOptions array{
* host?: string,
* port?: int,
* dbname?: string,
* username?: string|null,
* password?: string|null
* }
*/
class CouchDBHandler extends AbstractProcessingHandler
{
/**
* @var mixed[]
* @phpstan-var Options
*/
private array $options;
/**
* @param mixed[] $options
*
* @phpstan-param InputOptions $options
*/
public function __construct(array $options = [], int|string|Level $level = Level::Debug, bool $bubble = true)
{
$this->options = array_merge([
'host' => 'localhost',
'port' => 5984,
'dbname' => 'logger',
'username' => null,
'password' => null,
], $options);
parent::__construct($level, $bubble);
}
/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
$basicAuth = null;
if (null !== $this->options['username'] && null !== $this->options['password']) {
$basicAuth = sprintf('%s:%s@', $this->options['username'], $this->options['password']);
}
$url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname'];
$context = stream_context_create([
'http' => [
'method' => 'POST',
'content' => $record->formatted,
'ignore_errors' => true,
'max_redirects' => 0,
'header' => 'Content-type: application/json',
],
]);
if (false === @file_get_contents($url, false, $context)) {
throw new \RuntimeException(sprintf('Could not connect to %s', $url));
}
}
/**
* @inheritDoc
*/
protected function getDefaultFormatter(): FormatterInterface
{
return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/PHPConsoleHandler.php | src/Monolog/Handler/PHPConsoleHandler.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\Formatter\LineFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\Level;
use Monolog\Utils;
use PhpConsole\Connector;
use PhpConsole\Handler as VendorPhpConsoleHandler;
use PhpConsole\Helper;
use Monolog\LogRecord;
use PhpConsole\Storage;
/**
* Monolog handler for Google Chrome extension "PHP Console"
*
* Display PHP error/debug log messages in Google Chrome console and notification popups, executes PHP code remotely
*
* Usage:
* 1. Install Google Chrome extension [now dead and removed from the chrome store]
* 2. See overview https://github.com/barbushin/php-console#overview
* 3. Install PHP Console library https://github.com/barbushin/php-console#installation
* 4. Example (result will looks like http://i.hizliresim.com/vg3Pz4.png)
*
* $logger = new \Monolog\Logger('all', array(new \Monolog\Handler\PHPConsoleHandler()));
* \Monolog\ErrorHandler::register($logger);
* echo $undefinedVar;
* $logger->debug('SELECT * FROM users', array('db', 'time' => 0.012));
* PC::debug($_SERVER); // PHP Console debugger for any type of vars
*
* @author Sergey Barbushin https://www.linkedin.com/in/barbushin
* @phpstan-type Options array{
* enabled: bool,
* classesPartialsTraceIgnore: string[],
* debugTagsKeysInContext: array<int|string>,
* useOwnErrorsHandler: bool,
* useOwnExceptionsHandler: bool,
* sourcesBasePath: string|null,
* registerHelper: bool,
* serverEncoding: string|null,
* headersLimit: int|null,
* password: string|null,
* enableSslOnlyMode: bool,
* ipMasks: string[],
* enableEvalListener: bool,
* dumperDetectCallbacks: bool,
* dumperLevelLimit: int,
* dumperItemsCountLimit: int,
* dumperItemSizeLimit: int,
* dumperDumpSizeLimit: int,
* detectDumpTraceAndSource: bool,
* dataStorage: Storage|null
* }
* @phpstan-type InputOptions array{
* enabled?: bool,
* classesPartialsTraceIgnore?: string[],
* debugTagsKeysInContext?: array<int|string>,
* useOwnErrorsHandler?: bool,
* useOwnExceptionsHandler?: bool,
* sourcesBasePath?: string|null,
* registerHelper?: bool,
* serverEncoding?: string|null,
* headersLimit?: int|null,
* password?: string|null,
* enableSslOnlyMode?: bool,
* ipMasks?: string[],
* enableEvalListener?: bool,
* dumperDetectCallbacks?: bool,
* dumperLevelLimit?: int,
* dumperItemsCountLimit?: int,
* dumperItemSizeLimit?: int,
* dumperDumpSizeLimit?: int,
* detectDumpTraceAndSource?: bool,
* dataStorage?: Storage|null
* }
*
* @deprecated Since 2.8.0 and 3.2.0, PHPConsole is abandoned and thus we will drop this handler in Monolog 4
*/
class PHPConsoleHandler extends AbstractProcessingHandler
{
/**
* @phpstan-var Options
*/
private array $options = [
'enabled' => true, // bool Is PHP Console server enabled
'classesPartialsTraceIgnore' => ['Monolog\\'], // array Hide calls of classes started with...
'debugTagsKeysInContext' => [0, 'tag'], // bool Is PHP Console server enabled
'useOwnErrorsHandler' => false, // bool Enable errors handling
'useOwnExceptionsHandler' => false, // bool Enable exceptions handling
'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths
'registerHelper' => true, // bool Register PhpConsole\Helper that allows short debug calls like PC::debug($var, 'ta.g.s')
'serverEncoding' => null, // string|null Server internal encoding
'headersLimit' => null, // int|null Set headers size limit for your web-server
'password' => null, // string|null Protect PHP Console connection by password
'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed
'ipMasks' => [], // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1')
'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required)
'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings
'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level
'dumperItemsCountLimit' => 100, // int Maximum dumped var same level array items or object properties number
'dumperItemSizeLimit' => 5000, // int Maximum length of any string or dumped array item
'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON
'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug
'dataStorage' => null, // \PhpConsole\Storage|null Fixes problem with custom $_SESSION handler (see https://github.com/barbushin/php-console#troubleshooting-with-_session-handler-overridden-in-some-frameworks)
];
private Connector $connector;
/**
* @param array<string, mixed> $options See \Monolog\Handler\PHPConsoleHandler::$options for more details
* @param Connector|null $connector Instance of \PhpConsole\Connector class (optional)
* @throws \RuntimeException
* @phpstan-param InputOptions $options
*/
public function __construct(array $options = [], ?Connector $connector = null, int|string|Level $level = Level::Debug, bool $bubble = true)
{
if (!class_exists('PhpConsole\Connector')) {
throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
}
parent::__construct($level, $bubble);
$this->options = $this->initOptions($options);
$this->connector = $this->initConnector($connector);
}
/**
* @param array<string, mixed> $options
* @return array<string, mixed>
*
* @phpstan-param InputOptions $options
* @phpstan-return Options
*/
private function initOptions(array $options): array
{
$wrongOptions = array_diff(array_keys($options), array_keys($this->options));
if (\count($wrongOptions) > 0) {
throw new \RuntimeException('Unknown options: ' . implode(', ', $wrongOptions));
}
return array_replace($this->options, $options);
}
private function initConnector(?Connector $connector = null): Connector
{
if (null === $connector) {
if ($this->options['dataStorage'] instanceof Storage) {
Connector::setPostponeStorage($this->options['dataStorage']);
}
$connector = Connector::getInstance();
}
if ($this->options['registerHelper'] && !Helper::isRegistered()) {
Helper::register();
}
if ($this->options['enabled'] && $connector->isActiveClient()) {
if ($this->options['useOwnErrorsHandler'] || $this->options['useOwnExceptionsHandler']) {
$handler = VendorPhpConsoleHandler::getInstance();
$handler->setHandleErrors($this->options['useOwnErrorsHandler']);
$handler->setHandleExceptions($this->options['useOwnExceptionsHandler']);
$handler->start();
}
if (null !== $this->options['sourcesBasePath']) {
$connector->setSourcesBasePath($this->options['sourcesBasePath']);
}
if (null !== $this->options['serverEncoding']) {
$connector->setServerEncoding($this->options['serverEncoding']);
}
if (null !== $this->options['password']) {
$connector->setPassword($this->options['password']);
}
if ($this->options['enableSslOnlyMode']) {
$connector->enableSslOnlyMode();
}
if (\count($this->options['ipMasks']) > 0) {
$connector->setAllowedIpMasks($this->options['ipMasks']);
}
if (null !== $this->options['headersLimit'] && $this->options['headersLimit'] > 0) {
$connector->setHeadersLimit($this->options['headersLimit']);
}
if ($this->options['detectDumpTraceAndSource']) {
$connector->getDebugDispatcher()->detectTraceAndSource = true;
}
$dumper = $connector->getDumper();
$dumper->levelLimit = $this->options['dumperLevelLimit'];
$dumper->itemsCountLimit = $this->options['dumperItemsCountLimit'];
$dumper->itemSizeLimit = $this->options['dumperItemSizeLimit'];
$dumper->dumpSizeLimit = $this->options['dumperDumpSizeLimit'];
$dumper->detectCallbacks = $this->options['dumperDetectCallbacks'];
if ($this->options['enableEvalListener']) {
$connector->startEvalRequestsListener();
}
}
return $connector;
}
public function getConnector(): Connector
{
return $this->connector;
}
/**
* @return array<string, mixed>
*/
public function getOptions(): array
{
return $this->options;
}
public function handle(LogRecord $record): bool
{
if ($this->options['enabled'] && $this->connector->isActiveClient()) {
return parent::handle($record);
}
return !$this->bubble;
}
/**
* Writes the record down to the log of the implementing handler
*/
protected function write(LogRecord $record): void
{
if ($record->level->isLowerThan(Level::Notice)) {
$this->handleDebugRecord($record);
} elseif (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) {
$this->handleExceptionRecord($record);
} else {
$this->handleErrorRecord($record);
}
}
private function handleDebugRecord(LogRecord $record): void
{
[$tags, $filteredContext] = $this->getRecordTags($record);
$message = $record->message;
if (\count($filteredContext) > 0) {
$message .= ' ' . Utils::jsonEncode($this->connector->getDumper()->dump(array_filter($filteredContext)), null, true);
}
$this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']);
}
private function handleExceptionRecord(LogRecord $record): void
{
$this->connector->getErrorsDispatcher()->dispatchException($record->context['exception']);
}
private function handleErrorRecord(LogRecord $record): void
{
$context = $record->context;
$this->connector->getErrorsDispatcher()->dispatchError(
$context['code'] ?? null,
$context['message'] ?? $record->message,
$context['file'] ?? null,
$context['line'] ?? null,
$this->options['classesPartialsTraceIgnore']
);
}
/**
* @return array{string, mixed[]}
*/
private function getRecordTags(LogRecord $record): array
{
$tags = null;
$filteredContext = [];
if ($record->context !== []) {
$filteredContext = $record->context;
foreach ($this->options['debugTagsKeysInContext'] as $key) {
if (isset($filteredContext[$key])) {
$tags = $filteredContext[$key];
if ($key === 0) {
array_shift($filteredContext);
} else {
unset($filteredContext[$key]);
}
break;
}
}
}
return [$tags ?? $record->level->toPsrLogLevel(), $filteredContext];
}
/**
* @inheritDoc
*/
protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter('%message%');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/NewRelicHandler.php | src/Monolog/Handler/NewRelicHandler.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\Utils;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord;
/**
* Class to record a log on a NewRelic application.
* Enabling New Relic High Security mode may prevent capture of useful information.
*
* This handler requires a NormalizerFormatter to function and expects an array in $record->formatted
*
* @see https://docs.newrelic.com/docs/agents/php-agent
* @see https://docs.newrelic.com/docs/accounts-partnerships/accounts/security/high-security
*/
class NewRelicHandler extends AbstractProcessingHandler
{
/**
* @inheritDoc
*/
public function __construct(
int|string|Level $level = Level::Error,
bool $bubble = true,
/**
* Name of the New Relic application that will receive logs from this handler.
*/
protected string|null $appName = null,
/**
* Some context and extra data is passed into the handler as arrays of values. Do we send them as is
* (useful if we are using the API), or explode them for display on the NewRelic RPM website?
*/
protected bool $explodeArrays = false,
/**
* Name of the current transaction
*/
protected string|null $transactionName = null
) {
parent::__construct($level, $bubble);
}
/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
if (!$this->isNewRelicEnabled()) {
throw new MissingExtensionException('The newrelic PHP extension is required to use the NewRelicHandler');
}
if (null !== ($appName = $this->getAppName($record->context))) {
$this->setNewRelicAppName($appName);
}
if (null !== ($transactionName = $this->getTransactionName($record->context))) {
$this->setNewRelicTransactionName($transactionName);
unset($record->formatted['context']['transaction_name']);
}
if (isset($record->context['exception']) && $record->context['exception'] instanceof \Throwable) {
newrelic_notice_error($record->message, $record->context['exception']);
unset($record->formatted['context']['exception']);
} else {
newrelic_notice_error($record->message);
}
if (isset($record->formatted['context']) && \is_array($record->formatted['context'])) {
foreach ($record->formatted['context'] as $key => $parameter) {
if (\is_array($parameter) && $this->explodeArrays) {
foreach ($parameter as $paramKey => $paramValue) {
$this->setNewRelicParameter('context_' . $key . '_' . $paramKey, $paramValue);
}
} else {
$this->setNewRelicParameter('context_' . $key, $parameter);
}
}
}
if (isset($record->formatted['extra']) && \is_array($record->formatted['extra'])) {
foreach ($record->formatted['extra'] as $key => $parameter) {
if (\is_array($parameter) && $this->explodeArrays) {
foreach ($parameter as $paramKey => $paramValue) {
$this->setNewRelicParameter('extra_' . $key . '_' . $paramKey, $paramValue);
}
} else {
$this->setNewRelicParameter('extra_' . $key, $parameter);
}
}
}
}
/**
* Checks whether the NewRelic extension is enabled in the system.
*/
protected function isNewRelicEnabled(): bool
{
return \extension_loaded('newrelic');
}
/**
* Returns the appname where this log should be sent. Each log can override the default appname, set in this
* handler's constructor, by providing the appname in it's context.
*
* @param mixed[] $context
*/
protected function getAppName(array $context): ?string
{
if (isset($context['appname'])) {
return $context['appname'];
}
return $this->appName;
}
/**
* Returns the name of the current transaction. Each log can override the default transaction name, set in this
* handler's constructor, by providing the transaction_name in it's context
*
* @param mixed[] $context
*/
protected function getTransactionName(array $context): ?string
{
if (isset($context['transaction_name'])) {
return $context['transaction_name'];
}
return $this->transactionName;
}
/**
* Sets the NewRelic application that should receive this log.
*/
protected function setNewRelicAppName(string $appName): void
{
newrelic_set_appname($appName);
}
/**
* Overwrites the name of the current transaction
*/
protected function setNewRelicTransactionName(string $transactionName): void
{
newrelic_name_transaction($transactionName);
}
/**
* @param mixed $value
*/
protected function setNewRelicParameter(string $key, $value): void
{
if (null === $value || \is_scalar($value)) {
newrelic_add_custom_parameter($key, $value);
} else {
newrelic_add_custom_parameter($key, Utils::jsonEncode($value, null, true));
}
}
/**
* @inheritDoc
*/
protected function getDefaultFormatter(): FormatterInterface
{
return new NormalizerFormatter();
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/DynamoDbHandler.php | src/Monolog/Handler/DynamoDbHandler.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 Aws\Sdk;
use Aws\DynamoDb\DynamoDbClient;
use Monolog\Formatter\FormatterInterface;
use Aws\DynamoDb\Marshaler;
use Monolog\Formatter\ScalarFormatter;
use Monolog\Level;
use Monolog\LogRecord;
/**
* Amazon DynamoDB handler (http://aws.amazon.com/dynamodb/)
*
* @link https://github.com/aws/aws-sdk-php/
* @author Andrew Lawson <adlawson@gmail.com>
*/
class DynamoDbHandler extends AbstractProcessingHandler
{
public const DATE_FORMAT = 'Y-m-d\TH:i:s.uO';
protected DynamoDbClient $client;
protected string $table;
protected Marshaler $marshaler;
public function __construct(DynamoDbClient $client, string $table, int|string|Level $level = Level::Debug, bool $bubble = true)
{
$this->marshaler = new Marshaler;
$this->client = $client;
$this->table = $table;
parent::__construct($level, $bubble);
}
/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
$filtered = $this->filterEmptyFields($record->formatted);
$formatted = $this->marshaler->marshalItem($filtered);
$this->client->putItem([
'TableName' => $this->table,
'Item' => $formatted,
]);
}
/**
* @param mixed[] $record
* @return mixed[]
*/
protected function filterEmptyFields(array $record): array
{
return array_filter($record, function ($value) {
return [] !== $value;
});
}
/**
* @inheritDoc
*/
protected function getDefaultFormatter(): FormatterInterface
{
return new ScalarFormatter(self::DATE_FORMAT);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/RollbarHandler.php | src/Monolog/Handler/RollbarHandler.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 Rollbar\RollbarLogger;
use Throwable;
use Monolog\LogRecord;
/**
* Sends errors to Rollbar
*
* If the context data contains a `payload` key, that is used as an array
* of payload options to RollbarLogger's log method.
*
* Rollbar's context info will contain the context + extra keys from the log record
* merged, and then on top of that a few keys:
*
* - level (rollbar level name)
* - monolog_level (monolog level name, raw level, as rollbar only has 5 but monolog 8)
* - channel
* - datetime (unix timestamp)
*
* @author Paul Statezny <paulstatezny@gmail.com>
*/
class RollbarHandler extends AbstractProcessingHandler
{
protected RollbarLogger $rollbarLogger;
/**
* Records whether any log records have been added since the last flush of the rollbar notifier
*/
private bool $hasRecords = false;
protected bool $initialized = false;
/**
* @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token
*/
public function __construct(RollbarLogger $rollbarLogger, int|string|Level $level = Level::Error, bool $bubble = true)
{
$this->rollbarLogger = $rollbarLogger;
parent::__construct($level, $bubble);
}
/**
* Translates Monolog log levels to Rollbar levels.
*
* @return 'debug'|'info'|'warning'|'error'|'critical'
*/
protected function toRollbarLevel(Level $level): string
{
return match ($level) {
Level::Debug => 'debug',
Level::Info => 'info',
Level::Notice => 'info',
Level::Warning => 'warning',
Level::Error => 'error',
Level::Critical => 'critical',
Level::Alert => 'critical',
Level::Emergency => 'critical',
};
}
/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
if (!$this->initialized) {
// __destructor() doesn't get called on Fatal errors
register_shutdown_function([$this, 'close']);
$this->initialized = true;
}
$context = $record->context;
$context = array_merge($context, $record->extra, [
'level' => $this->toRollbarLevel($record->level),
'monolog_level' => $record->level->getName(),
'channel' => $record->channel,
'datetime' => $record->datetime->format('U'),
]);
if (isset($context['exception']) && $context['exception'] instanceof Throwable) {
$exception = $context['exception'];
unset($context['exception']);
$toLog = $exception;
} else {
$toLog = $record->message;
}
$this->rollbarLogger->log($context['level'], $toLog, $context);
$this->hasRecords = true;
}
public function flush(): void
{
if ($this->hasRecords) {
$this->rollbarLogger->flush();
$this->hasRecords = false;
}
}
/**
* @inheritDoc
*/
public function close(): void
{
$this->flush();
}
/**
* @inheritDoc
*/
public function reset(): void
{
$this->flush();
parent::reset();
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/SyslogUdpHandler.php | src/Monolog/Handler/SyslogUdpHandler.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 DateTimeInterface;
use Monolog\Handler\SyslogUdp\UdpSocket;
use Monolog\Level;
use Monolog\LogRecord;
use Monolog\Utils;
/**
* A Handler for logging to a remote syslogd server.
*
* @author Jesper Skovgaard Nielsen <nulpunkt@gmail.com>
* @author Dominik Kukacka <dominik.kukacka@gmail.com>
*/
class SyslogUdpHandler extends AbstractSyslogHandler
{
const RFC3164 = 0;
const RFC5424 = 1;
const RFC5424e = 2;
/** @var array<self::RFC*, string> */
private array $dateFormats = [
self::RFC3164 => 'M d H:i:s',
self::RFC5424 => \DateTime::RFC3339,
self::RFC5424e => \DateTime::RFC3339_EXTENDED,
];
protected UdpSocket $socket;
protected string $ident;
/** @var self::RFC* */
protected int $rfc;
/**
* @param string $host Either IP/hostname or a path to a unix socket (port must be 0 then)
* @param int $port Port number, or 0 if $host is a unix socket
* @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param string $ident Program name or tag for each log message.
* @param int $rfc RFC to format the message for.
* @throws MissingExtensionException when there is no socket extension
*
* @phpstan-param self::RFC* $rfc
*/
public function __construct(string $host, int $port = 514, string|int $facility = LOG_USER, int|string|Level $level = Level::Debug, bool $bubble = true, string $ident = 'php', int $rfc = self::RFC5424)
{
if (!\extension_loaded('sockets')) {
throw new MissingExtensionException('The sockets extension is required to use the SyslogUdpHandler');
}
parent::__construct($facility, $level, $bubble);
$this->ident = $ident;
$this->rfc = $rfc;
$this->socket = new UdpSocket($host, $port);
}
protected function write(LogRecord $record): void
{
$lines = $this->splitMessageIntoLines($record->formatted);
$header = $this->makeCommonSyslogHeader($this->toSyslogPriority($record->level), $record->datetime);
foreach ($lines as $line) {
$this->socket->write($line, $header);
}
}
public function close(): void
{
$this->socket->close();
}
/**
* @param string|string[] $message
* @return string[]
*/
private function splitMessageIntoLines($message): array
{
if (\is_array($message)) {
$message = implode("\n", $message);
}
$lines = preg_split('/$\R?^/m', (string) $message, -1, PREG_SPLIT_NO_EMPTY);
if (false === $lines) {
$pcreErrorCode = preg_last_error();
throw new \RuntimeException('Could not preg_split: ' . $pcreErrorCode . ' / ' . preg_last_error_msg());
}
return $lines;
}
/**
* Make common syslog header (see rfc5424 or rfc3164)
*/
protected function makeCommonSyslogHeader(int $severity, DateTimeInterface $datetime): string
{
$priority = $severity + $this->facility;
$pid = getmypid();
if (false === $pid) {
$pid = '-';
}
$hostname = gethostname();
if (false === $hostname) {
$hostname = '-';
}
if ($this->rfc === self::RFC3164) {
// see https://github.com/phpstan/phpstan/issues/5348
// @phpstan-ignore-next-line
$dateNew = $datetime->setTimezone(new \DateTimeZone('UTC'));
$date = $dateNew->format($this->dateFormats[$this->rfc]);
return "<$priority>" .
$date . " " .
$hostname . " " .
$this->ident . "[" . $pid . "]: ";
}
$date = $datetime->format($this->dateFormats[$this->rfc]);
return "<$priority>1 " .
$date . " " .
$hostname . " " .
$this->ident . " " .
$pid . " - - ";
}
/**
* Inject your own socket, mainly used for testing
*
* @return $this
*/
public function setSocket(UdpSocket $socket): self
{
$this->socket = $socket;
return $this;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/PsrHandler.php | src/Monolog/Handler/PsrHandler.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 Psr\Log\LoggerInterface;
use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord;
/**
* Proxies log messages to an existing PSR-3 compliant logger.
*
* If a formatter is configured, the formatter's output MUST be a string and the
* formatted message will be fed to the wrapped PSR logger instead of the original
* log record's message.
*
* @author Michael Moussa <michael.moussa@gmail.com>
*/
class PsrHandler extends AbstractHandler implements FormattableHandlerInterface
{
/**
* PSR-3 compliant logger
*/
protected LoggerInterface $logger;
protected FormatterInterface|null $formatter = null;
private bool $includeExtra;
/**
* @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied
*/
public function __construct(LoggerInterface $logger, int|string|Level $level = Level::Debug, bool $bubble = true, bool $includeExtra = false)
{
parent::__construct($level, $bubble);
$this->logger = $logger;
$this->includeExtra = $includeExtra;
}
/**
* @inheritDoc
*/
public function handle(LogRecord $record): bool
{
if (!$this->isHandling($record)) {
return false;
}
$message = $this->formatter !== null
? (string) $this->formatter->format($record)
: $record->message;
$context = $this->includeExtra
? [...$record->extra, ...$record->context]
: $record->context;
$this->logger->log($record->level->toPsrLogLevel(), $message, $context);
return false === $this->bubble;
}
/**
* Sets the formatter.
*/
public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
$this->formatter = $formatter;
return $this;
}
/**
* Gets the formatter.
*/
public function getFormatter(): FormatterInterface
{
if ($this->formatter === null) {
throw new \LogicException('No formatter has been set and this handler does not have a default formatter');
}
return $this->formatter;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/WebRequestRecognizerTrait.php | src/Monolog/Handler/WebRequestRecognizerTrait.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;
trait WebRequestRecognizerTrait
{
/**
* Checks if PHP's serving a web request
*/
protected function isWebRequest(): bool
{
return 'cli' !== \PHP_SAPI && 'phpdbg' !== \PHP_SAPI;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/ProcessHandler.php | src/Monolog/Handler/ProcessHandler.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;
/**
* Stores to STDIN of any process, specified by a command.
*
* Usage example:
* <pre>
* $log = new Logger('myLogger');
* $log->pushHandler(new ProcessHandler('/usr/bin/php /var/www/monolog/someScript.php'));
* </pre>
*
* @author Kolja Zuelsdorf <koljaz@web.de>
*/
class ProcessHandler extends AbstractProcessingHandler
{
/**
* Holds the process to receive data on its STDIN.
*
* @var resource|bool|null
*/
private $process;
private string $command;
private ?string $cwd;
/**
* @var resource[]
*/
private array $pipes = [];
private float $timeout;
/**
* @var array<int, list<string>>
*/
protected const DESCRIPTOR_SPEC = [
0 => ['pipe', 'r'], // STDIN is a pipe that the child will read from
1 => ['pipe', 'w'], // STDOUT is a pipe that the child will write to
2 => ['pipe', 'w'], // STDERR is a pipe to catch the any errors
];
/**
* @param string $command Command for the process to start. Absolute paths are recommended,
* especially if you do not use the $cwd parameter.
* @param string|null $cwd "Current working directory" (CWD) for the process to be executed in.
* @param float $timeout The maximum timeout (in seconds) for the stream_select() function.
* @throws \InvalidArgumentException
*/
public function __construct(string $command, int|string|Level $level = Level::Debug, bool $bubble = true, ?string $cwd = null, float $timeout = 1.0)
{
if ($command === '') {
throw new \InvalidArgumentException('The command argument must be a non-empty string.');
}
if ($cwd === '') {
throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string or null.');
}
parent::__construct($level, $bubble);
$this->command = $command;
$this->cwd = $cwd;
$this->timeout = $timeout;
}
/**
* Writes the record down to the log of the implementing handler
*
* @throws \UnexpectedValueException
*/
protected function write(LogRecord $record): void
{
$this->ensureProcessIsStarted();
$this->writeProcessInput($record->formatted);
$errors = $this->readProcessErrors();
if ($errors !== '') {
throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors));
}
}
/**
* Makes sure that the process is actually started, and if not, starts it,
* assigns the stream pipes, and handles startup errors, if any.
*/
private function ensureProcessIsStarted(): void
{
if (\is_resource($this->process) === false) {
$this->startProcess();
$this->handleStartupErrors();
}
}
/**
* Starts the actual process and sets all streams to non-blocking.
*/
private function startProcess(): void
{
$this->process = proc_open($this->command, static::DESCRIPTOR_SPEC, $this->pipes, $this->cwd);
foreach ($this->pipes as $pipe) {
stream_set_blocking($pipe, false);
}
}
/**
* Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any.
*
* @throws \UnexpectedValueException
*/
private function handleStartupErrors(): void
{
$selected = $this->selectErrorStream();
if (false === $selected) {
throw new \UnexpectedValueException('Something went wrong while selecting a stream.');
}
$errors = $this->readProcessErrors();
if (\is_resource($this->process) === false || $errors !== '') {
throw new \UnexpectedValueException(
sprintf('The process "%s" could not be opened: ' . $errors, $this->command)
);
}
}
/**
* Selects the STDERR stream.
*
* @return int|bool
*/
protected function selectErrorStream()
{
$empty = [];
$errorPipes = [$this->pipes[2]];
$seconds = (int) $this->timeout;
return stream_select($errorPipes, $empty, $empty, $seconds, (int) (($this->timeout - $seconds) * 1000000));
}
/**
* Reads the errors of the process, if there are any.
*
* @codeCoverageIgnore
* @return string Empty string if there are no errors.
*/
protected function readProcessErrors(): string
{
return (string) stream_get_contents($this->pipes[2]);
}
/**
* Writes to the input stream of the opened process.
*
* @codeCoverageIgnore
*/
protected function writeProcessInput(string $string): void
{
fwrite($this->pipes[0], $string);
}
/**
* @inheritDoc
*/
public function close(): void
{
if (\is_resource($this->process)) {
foreach ($this->pipes as $pipe) {
fclose($pipe);
}
proc_close($this->process);
$this->process = null;
}
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/MissingExtensionException.php | src/Monolog/Handler/MissingExtensionException.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;
/**
* Exception can be thrown if an extension for a handler is missing
*
* @author Christian Bergau <cbergau86@gmail.com>
*/
class MissingExtensionException extends \Exception
{
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/FormattableHandlerInterface.php | src/Monolog/Handler/FormattableHandlerInterface.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\Formatter\FormatterInterface;
/**
* Interface to describe loggers that have a formatter
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface FormattableHandlerInterface
{
/**
* Sets the formatter.
*
* @return HandlerInterface self
*/
public function setFormatter(FormatterInterface $formatter): HandlerInterface;
/**
* Gets the formatter.
*/
public function getFormatter(): FormatterInterface;
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/FlowdockHandler.php | src/Monolog/Handler/FlowdockHandler.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\Utils;
use Monolog\Formatter\FlowdockFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord;
/**
* Sends notifications through the Flowdock push API
*
* This must be configured with a FlowdockFormatter instance via setFormatter()
*
* Notes:
* API token - Flowdock API token
*
* @author Dominik Liebler <liebler.dominik@gmail.com>
* @see https://www.flowdock.com/api/push
* @deprecated Since 2.9.0 and 3.3.0, Flowdock was shutdown we will thus drop this handler in Monolog 4
*/
class FlowdockHandler extends SocketHandler
{
protected string $apiToken;
/**
* @throws MissingExtensionException if OpenSSL is missing
*/
public function __construct(
string $apiToken,
$level = Level::Debug,
bool $bubble = true,
bool $persistent = false,
float $timeout = 0.0,
float $writingTimeout = 10.0,
?float $connectionTimeout = null,
?int $chunkSize = null
) {
if (!\extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler');
}
parent::__construct(
'ssl://api.flowdock.com:443',
$level,
$bubble,
$persistent,
$timeout,
$writingTimeout,
$connectionTimeout,
$chunkSize
);
$this->apiToken = $apiToken;
}
/**
* @inheritDoc
*/
public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
if (!$formatter instanceof FlowdockFormatter) {
throw new \InvalidArgumentException('The FlowdockHandler requires an instance of Monolog\Formatter\FlowdockFormatter to function correctly');
}
return parent::setFormatter($formatter);
}
/**
* Gets the default formatter.
*/
protected function getDefaultFormatter(): FormatterInterface
{
throw new \InvalidArgumentException('The FlowdockHandler must be configured (via setFormatter) with an instance of Monolog\Formatter\FlowdockFormatter to function correctly');
}
/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
parent::write($record);
$this->closeSocket();
}
/**
* @inheritDoc
*/
protected function generateDataStream(LogRecord $record): string
{
$content = $this->buildContent($record);
return $this->buildHeader($content) . $content;
}
/**
* Builds the body of API call
*/
private function buildContent(LogRecord $record): string
{
return Utils::jsonEncode($record->formatted);
}
/**
* Builds the header of the API Call
*/
private function buildHeader(string $content): string
{
$header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n";
$header .= "Host: api.flowdock.com\r\n";
$header .= "Content-Type: application/json\r\n";
$header .= "Content-Length: " . \strlen($content) . "\r\n";
$header .= "\r\n";
return $header;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/SymfonyMailerHandler.php | src/Monolog/Handler/SymfonyMailerHandler.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 Closure;
use Monolog\Level;
use Monolog\LogRecord;
use Monolog\Utils;
use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mailer\Transport\TransportInterface;
use Symfony\Component\Mime\Email;
/**
* SymfonyMailerHandler uses Symfony's Mailer component to send the emails
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class SymfonyMailerHandler extends MailHandler
{
protected MailerInterface|TransportInterface $mailer;
/** @var Email|Closure(string, LogRecord[]): Email */
private Email|Closure $emailTemplate;
/**
* @phpstan-param Email|Closure(string, LogRecord[]): Email $email
*
* @param MailerInterface|TransportInterface $mailer The mailer to use
* @param Closure|Email $email An email template, the subject/body will be replaced
*/
public function __construct($mailer, Email|Closure $email, int|string|Level $level = Level::Error, bool $bubble = true)
{
parent::__construct($level, $bubble);
$this->mailer = $mailer;
$this->emailTemplate = $email;
}
/**
* {@inheritDoc}
*/
protected function send(string $content, array $records): void
{
$this->mailer->send($this->buildMessage($content, $records));
}
/**
* Gets the formatter for the Swift_Message subject.
*
* @param string|null $format The format of the subject
*/
protected function getSubjectFormatter(?string $format): FormatterInterface
{
return new LineFormatter($format);
}
/**
* Creates instance of Email to be sent
*
* @param string $content formatted email body to be sent
* @param LogRecord[] $records Log records that formed the content
*/
protected function buildMessage(string $content, array $records): Email
{
$message = null;
if ($this->emailTemplate instanceof Email) {
$message = clone $this->emailTemplate;
} elseif (\is_callable($this->emailTemplate)) {
$message = ($this->emailTemplate)($content, $records);
}
if (!$message instanceof Email) {
$record = reset($records);
throw new \InvalidArgumentException('Could not resolve message as instance of Email or a callable returning it' . ($record instanceof LogRecord ? Utils::getRecordMessageForException($record) : ''));
}
if (\count($records) > 0) {
$subjectFormatter = $this->getSubjectFormatter($message->getSubject());
$message->subject($subjectFormatter->format($this->getHighestRecord($records)));
}
if ($this->isHtmlBody($content)) {
if (null !== ($charset = $message->getHtmlCharset())) {
$message->html($content, $charset);
} else {
$message->html($content);
}
} else {
if (null !== ($charset = $message->getTextCharset())) {
$message->text($content, $charset);
} else {
$message->text($content);
}
}
return $message->date(new \DateTimeImmutable());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/IFTTTHandler.php | src/Monolog/Handler/IFTTTHandler.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\Utils;
use Monolog\LogRecord;
/**
* IFTTTHandler uses cURL to trigger IFTTT Maker actions
*
* Register a secret key and trigger/event name at https://ifttt.com/maker
*
* value1 will be the channel from monolog's Logger constructor,
* value2 will be the level name (ERROR, WARNING, ..)
* value3 will be the log record's message
*
* @author Nehal Patel <nehal@nehalpatel.me>
*/
class IFTTTHandler extends AbstractProcessingHandler
{
private string $eventName;
private string $secretKey;
/**
* @param string $eventName The name of the IFTTT Maker event that should be triggered
* @param string $secretKey A valid IFTTT secret key
*
* @throws MissingExtensionException If the curl extension is missing
*/
public function __construct(string $eventName, string $secretKey, int|string|Level $level = Level::Error, bool $bubble = true)
{
if (!\extension_loaded('curl')) {
throw new MissingExtensionException('The curl extension is needed to use the IFTTTHandler');
}
$this->eventName = $eventName;
$this->secretKey = $secretKey;
parent::__construct($level, $bubble);
}
/**
* @inheritDoc
*/
public function write(LogRecord $record): void
{
$postData = [
"value1" => $record->channel,
"value2" => $record["level_name"],
"value3" => $record->message,
];
$postString = Utils::jsonEncode($postData);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://maker.ifttt.com/trigger/" . $this->eventName . "/with/key/" . $this->secretKey);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
]);
Curl\Util::execute($ch);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/RotatingFileHandler.php | src/Monolog/Handler/RotatingFileHandler.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 DateTimeZone;
use InvalidArgumentException;
use Monolog\Level;
use Monolog\Utils;
use Monolog\LogRecord;
/**
* Stores logs to files that are rotated every day and a limited number of files are kept.
*
* This rotation is only intended to be used as a workaround. Using logrotate to
* handle the rotation is strongly encouraged when you can use it.
*
* @author Christophe Coevoet <stof@notk.org>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class RotatingFileHandler extends StreamHandler
{
public const FILE_PER_DAY = 'Y-m-d';
public const FILE_PER_MONTH = 'Y-m';
public const FILE_PER_YEAR = 'Y';
protected string $filename;
protected int $maxFiles;
protected bool|null $mustRotate = null;
protected \DateTimeImmutable $nextRotation;
protected string $filenameFormat;
protected string $dateFormat;
protected DateTimeZone|null $timezone = null;
/**
* @param int $maxFiles The maximal amount of files to keep (0 means unlimited)
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
* @param bool $useLocking Try to lock log file before doing any writes
*/
public function __construct(string $filename, int $maxFiles = 0, int|string|Level $level = Level::Debug, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false, string $dateFormat = self::FILE_PER_DAY, string $filenameFormat = '{filename}-{date}', DateTimeZone|null $timezone = null)
{
$this->filename = Utils::canonicalizePath($filename);
$this->maxFiles = $maxFiles;
$this->setFilenameFormat($filenameFormat, $dateFormat);
$this->nextRotation = $this->getNextRotation();
$this->timezone = $timezone;
parent::__construct($this->getTimedFilename(), $level, $bubble, $filePermission, $useLocking);
}
/**
* @inheritDoc
*/
public function close(): void
{
parent::close();
if (true === $this->mustRotate) {
$this->rotate();
}
}
/**
* @inheritDoc
*/
public function reset(): void
{
parent::reset();
}
/**
* @return $this
*/
public function setFilenameFormat(string $filenameFormat, string $dateFormat): self
{
$this->setDateFormat($dateFormat);
if (substr_count($filenameFormat, '{date}') === 0) {
throw new InvalidArgumentException(
'Invalid filename format - format must contain at least `{date}`, because otherwise rotating is impossible.'
);
}
$this->filenameFormat = $filenameFormat;
$this->url = $this->getTimedFilename();
$this->close();
return $this;
}
/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
// on the first record written, if the log is new, we rotate (once per day) after the log has been written so that the new file exists
if (null === $this->mustRotate) {
$this->mustRotate = null === $this->url || !file_exists($this->url);
}
// if the next rotation is expired, then we rotate immediately
if ($this->nextRotation <= $record->datetime) {
$this->mustRotate = true;
$this->close(); // triggers rotation
}
parent::write($record);
if (true === $this->mustRotate) {
$this->close(); // triggers rotation
}
}
/**
* Rotates the files.
*/
protected function rotate(): void
{
// update filename
$this->url = $this->getTimedFilename();
$this->nextRotation = $this->getNextRotation();
$this->mustRotate = false;
// skip GC of old logs if files are unlimited
if (0 === $this->maxFiles) {
return;
}
$logFiles = glob($this->getGlobPattern());
if (false === $logFiles) {
// failed to glob
return;
}
if ($this->maxFiles >= \count($logFiles)) {
// no files to remove
return;
}
// Sorting the files by name to remove the older ones
usort($logFiles, function ($a, $b) {
return strcmp($b, $a);
});
$basePath = dirname($this->filename);
foreach (\array_slice($logFiles, $this->maxFiles) as $file) {
if (is_writable($file)) {
// suppress errors here as unlink() might fail if two processes
// are cleaning up/rotating at the same time
set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): bool {
return true;
});
unlink($file);
$dir = dirname($file);
while ($dir !== $basePath) {
$entries = scandir($dir);
if ($entries === false || \count(array_diff($entries, ['.', '..'])) > 0) {
break;
}
rmdir($dir);
$dir = dirname($dir);
}
restore_error_handler();
}
}
}
protected function getTimedFilename(): string
{
$fileInfo = pathinfo($this->filename);
$timedFilename = str_replace(
['{filename}', '{date}'],
[$fileInfo['filename'], (new \DateTimeImmutable(timezone: $this->timezone))->format($this->dateFormat)],
($fileInfo['dirname'] ?? '') . '/' . $this->filenameFormat
);
if (isset($fileInfo['extension'])) {
$timedFilename .= '.'.$fileInfo['extension'];
}
return $timedFilename;
}
protected function getGlobPattern(): string
{
$fileInfo = pathinfo($this->filename);
$glob = str_replace(
['{filename}', '{date}'],
[$fileInfo['filename'], str_replace(
['Y', 'y', 'm', 'd'],
['[0-9][0-9][0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]', '[0-9][0-9]'],
$this->dateFormat
)],
($fileInfo['dirname'] ?? '') . '/' . $this->filenameFormat
);
if (isset($fileInfo['extension'])) {
$glob .= '.'.$fileInfo['extension'];
}
return $glob;
}
protected function setDateFormat(string $dateFormat): void
{
if (0 === preg_match('{^[Yy](([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) {
throw new InvalidArgumentException(
'Invalid date format - format must be one of '.
'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '.
'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '.
'date formats using slashes, underscores and/or dots instead of dashes.'
);
}
$this->dateFormat = $dateFormat;
}
protected function getNextRotation(): \DateTimeImmutable
{
return match (str_replace(['/','_','.'], '-', $this->dateFormat)) {
self::FILE_PER_MONTH => (new \DateTimeImmutable('first day of next month'))->setTime(0, 0, 0),
self::FILE_PER_YEAR => (new \DateTimeImmutable('first day of January next year'))->setTime(0, 0, 0),
default => (new \DateTimeImmutable('tomorrow'))->setTime(0, 0, 0),
};
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/HandlerInterface.php | src/Monolog/Handler/HandlerInterface.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\LogRecord;
/**
* Interface that all Monolog Handlers must implement
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface HandlerInterface
{
/**
* Checks whether the given record will be handled by this handler.
*
* This is mostly done for performance reasons, to avoid calling processors for nothing.
*
* Handlers should still check the record levels within handle(), returning false in isHandling()
* is no guarantee that handle() will not be called, and isHandling() might not be called
* for a given record.
*
* @param LogRecord $record Partial log record having only a level initialized
*/
public function isHandling(LogRecord $record): bool;
/**
* Handles a record.
*
* All records may be passed to this method, and the handler should discard
* those that it does not want to handle.
*
* The return value of this function controls the bubbling process of the handler stack.
* Unless the bubbling is interrupted (by returning true), the Logger class will keep on
* calling further handlers in the stack with a given log record.
*
* @param LogRecord $record The record to handle
* @return bool true means that this handler handled the record, and that bubbling is not permitted.
* false means the record was either not processed or that this handler allows bubbling.
*/
public function handle(LogRecord $record): bool;
/**
* Handles a set of records at once.
*
* @param array<LogRecord> $records The records to handle
*/
public function handleBatch(array $records): void;
/**
* Closes the handler.
*
* Ends a log cycle and frees all resources used by the handler.
*
* Closing a Handler means flushing all buffers and freeing any open resources/handles.
*
* Implementations have to be idempotent (i.e. it should be possible to call close several times without breakage)
* and ideally handlers should be able to reopen themselves on handle() after they have been closed.
*
* This is useful at the end of a request and will be called automatically when the object
* is destroyed if you extend Monolog\Handler\Handler.
*
* If you are thinking of calling this method yourself, most likely you should be
* calling ResettableInterface::reset instead. Have a look.
*/
public function close(): void;
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/SyslogUdp/UdpSocket.php | src/Monolog/Handler/SyslogUdp/UdpSocket.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\SyslogUdp;
use Monolog\Utils;
use Socket;
class UdpSocket
{
protected const DATAGRAM_MAX_LENGTH = 65023;
protected string $ip;
protected int $port;
protected ?Socket $socket = null;
public function __construct(string $ip, int $port = 514)
{
$this->ip = $ip;
$this->port = $port;
}
public function write(string $line, string $header = ""): void
{
$this->send($this->assembleMessage($line, $header));
}
public function close(): void
{
if ($this->socket instanceof Socket) {
socket_close($this->socket);
$this->socket = null;
}
}
protected function getSocket(): Socket
{
if (null !== $this->socket) {
return $this->socket;
}
$domain = AF_INET;
$protocol = SOL_UDP;
// Check if we are using unix sockets.
if ($this->port === 0) {
$domain = AF_UNIX;
$protocol = IPPROTO_IP;
}
$socket = socket_create($domain, SOCK_DGRAM, $protocol);
if ($socket instanceof Socket) {
return $this->socket = $socket;
}
throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' could not be opened via socket_create');
}
protected function send(string $chunk): void
{
socket_sendto($this->getSocket(), $chunk, \strlen($chunk), $flags = 0, $this->ip, $this->port);
}
protected function assembleMessage(string $line, string $header): string
{
$chunkSize = static::DATAGRAM_MAX_LENGTH - \strlen($header);
return $header . Utils::substr($line, 0, $chunkSize);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php | src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.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\FingersCrossed;
use Monolog\Level;
use Monolog\Logger;
use Psr\Log\LogLevel;
use Monolog\LogRecord;
/**
* Channel and Error level based monolog activation strategy. Allows to trigger activation
* based on level per channel. e.g. trigger activation on level 'ERROR' by default, except
* for records of the 'sql' channel; those should trigger activation on level 'WARN'.
*
* Example:
*
* <code>
* $activationStrategy = new ChannelLevelActivationStrategy(
* Level::Critical,
* array(
* 'request' => Level::Alert,
* 'sensitive' => Level::Error,
* )
* );
* $handler = new FingersCrossedHandler(new StreamHandler('php://stderr'), $activationStrategy);
* </code>
*
* @author Mike Meessen <netmikey@gmail.com>
*/
class ChannelLevelActivationStrategy implements ActivationStrategyInterface
{
private Level $defaultActionLevel;
/**
* @var array<string, Level>
*/
private array $channelToActionLevel;
/**
* @param int|string|Level|LogLevel::* $defaultActionLevel The default action level to be used if the record's category doesn't match any
* @param array<string, int|string|Level|LogLevel::*> $channelToActionLevel An array that maps channel names to action levels.
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $defaultActionLevel
* @phpstan-param array<string, value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::*> $channelToActionLevel
*/
public function __construct(int|string|Level $defaultActionLevel, array $channelToActionLevel = [])
{
$this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel);
$this->channelToActionLevel = array_map(Logger::toMonologLevel(...), $channelToActionLevel);
}
public function isHandlerActivated(LogRecord $record): bool
{
if (isset($this->channelToActionLevel[$record->channel])) {
return $record->level->value >= $this->channelToActionLevel[$record->channel]->value;
}
return $record->level->value >= $this->defaultActionLevel->value;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php | src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.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\FingersCrossed;
use Monolog\Level;
use Monolog\LogRecord;
use Monolog\Logger;
use Psr\Log\LogLevel;
/**
* Error level based activation strategy.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class ErrorLevelActivationStrategy implements ActivationStrategyInterface
{
private Level $actionLevel;
/**
* @param int|string|Level $actionLevel Level or name or value
*
* @phpstan-param value-of<Level::VALUES>|value-of<Level::NAMES>|Level|LogLevel::* $actionLevel
*/
public function __construct(int|string|Level $actionLevel)
{
$this->actionLevel = Logger::toMonologLevel($actionLevel);
}
public function isHandlerActivated(LogRecord $record): bool
{
return $record->level->value >= $this->actionLevel->value;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php | src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.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\FingersCrossed;
use Monolog\LogRecord;
/**
* Interface for activation strategies for the FingersCrossedHandler.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface ActivationStrategyInterface
{
/**
* Returns whether the given record activates the handler.
*/
public function isHandlerActivated(LogRecord $record): bool;
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/Slack/SlackRecord.php | src/Monolog/Handler/Slack/SlackRecord.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\Slack;
use Monolog\Level;
use Monolog\Utils;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\LogRecord;
/**
* Slack record utility helping to log to Slack webhooks or API.
*
* @author Greg Kedzierski <greg@gregkedzierski.com>
* @author Haralan Dobrev <hkdobrev@gmail.com>
* @see https://api.slack.com/incoming-webhooks
* @see https://api.slack.com/docs/message-attachments
*/
class SlackRecord
{
public const COLOR_DANGER = 'danger';
public const COLOR_WARNING = 'warning';
public const COLOR_GOOD = 'good';
public const COLOR_DEFAULT = '#e3e4e6';
/**
* Slack channel (encoded ID or name)
*/
private string|null $channel;
/**
* Name of a bot
*/
private string|null $username;
/**
* User icon e.g. 'ghost', 'http://example.com/user.png'
*/
private string|null $userIcon;
/**
* Whether the message should be added to Slack as attachment (plain text otherwise)
*/
private bool $useAttachment;
/**
* Whether the the context/extra messages added to Slack as attachments are in a short style
*/
private bool $useShortAttachment;
/**
* Whether the attachment should include context and extra data
*/
private bool $includeContextAndExtra;
/**
* Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
* @var string[]
*/
private array $excludeFields;
private FormatterInterface|null $formatter;
private NormalizerFormatter $normalizerFormatter;
/**
* @param string[] $excludeFields
*/
public function __construct(
?string $channel = null,
?string $username = null,
bool $useAttachment = true,
?string $userIcon = null,
bool $useShortAttachment = false,
bool $includeContextAndExtra = false,
array $excludeFields = [],
FormatterInterface|null $formatter = null
) {
$this
->setChannel($channel)
->setUsername($username)
->useAttachment($useAttachment)
->setUserIcon($userIcon)
->useShortAttachment($useShortAttachment)
->includeContextAndExtra($includeContextAndExtra)
->excludeFields($excludeFields)
->setFormatter($formatter);
if ($this->includeContextAndExtra) {
$this->normalizerFormatter = new NormalizerFormatter();
}
}
/**
* Returns required data in format that Slack
* is expecting.
*
* @phpstan-return mixed[]
*/
public function getSlackData(LogRecord $record): array
{
$dataArray = [];
if ($this->username !== null) {
$dataArray['username'] = $this->username;
}
if ($this->channel !== null) {
$dataArray['channel'] = $this->channel;
}
if ($this->formatter !== null && !$this->useAttachment) {
$message = $this->formatter->format($record);
} else {
$message = $record->message;
}
$recordData = $this->removeExcludedFields($record);
if ($this->useAttachment) {
$attachment = [
'fallback' => $message,
'text' => $message,
'color' => $this->getAttachmentColor($record->level),
'fields' => [],
'mrkdwn_in' => ['fields'],
'ts' => $recordData['datetime']->getTimestamp(),
'footer' => $this->username,
'footer_icon' => $this->userIcon,
];
if ($this->useShortAttachment) {
$attachment['title'] = $recordData['level_name'];
} else {
$attachment['title'] = 'Message';
$attachment['fields'][] = $this->generateAttachmentField('Level', $recordData['level_name']);
}
if ($this->includeContextAndExtra) {
foreach (['extra', 'context'] as $key) {
if (!isset($recordData[$key]) || \count($recordData[$key]) === 0) {
continue;
}
if ($this->useShortAttachment) {
$attachment['fields'][] = $this->generateAttachmentField(
$key,
$recordData[$key]
);
} else {
// Add all extra fields as individual fields in attachment
$attachment['fields'] = array_merge(
$attachment['fields'],
$this->generateAttachmentFields($recordData[$key])
);
}
}
}
$dataArray['attachments'] = [$attachment];
} else {
$dataArray['text'] = $message;
}
if ($this->userIcon !== null) {
if (false !== ($iconUrl = filter_var($this->userIcon, FILTER_VALIDATE_URL))) {
$dataArray['icon_url'] = $iconUrl;
} else {
$dataArray['icon_emoji'] = ":{$this->userIcon}:";
}
}
return $dataArray;
}
/**
* Returns a Slack message attachment color associated with
* provided level.
*/
public function getAttachmentColor(Level $level): string
{
return match ($level) {
Level::Error, Level::Critical, Level::Alert, Level::Emergency => static::COLOR_DANGER,
Level::Warning => static::COLOR_WARNING,
Level::Info, Level::Notice => static::COLOR_GOOD,
Level::Debug => static::COLOR_DEFAULT
};
}
/**
* Stringifies an array of key/value pairs to be used in attachment fields
*
* @param mixed[] $fields
*/
public function stringify(array $fields): string
{
/** @var array<array<mixed>|bool|float|int|string|null> $normalized */
$normalized = $this->normalizerFormatter->normalizeValue($fields);
$hasSecondDimension = \count(array_filter($normalized, 'is_array')) > 0;
$hasOnlyNonNumericKeys = \count(array_filter(array_keys($normalized), 'is_numeric')) === 0;
return $hasSecondDimension || $hasOnlyNonNumericKeys
? Utils::jsonEncode($normalized, JSON_PRETTY_PRINT|Utils::DEFAULT_JSON_FLAGS)
: Utils::jsonEncode($normalized, Utils::DEFAULT_JSON_FLAGS);
}
/**
* Channel used by the bot when posting
*
* @param ?string $channel
* @return $this
*/
public function setChannel(?string $channel = null): self
{
$this->channel = $channel;
return $this;
}
/**
* Username used by the bot when posting
*
* @param ?string $username
* @return $this
*/
public function setUsername(?string $username = null): self
{
$this->username = $username;
return $this;
}
/**
* @return $this
*/
public function useAttachment(bool $useAttachment = true): self
{
$this->useAttachment = $useAttachment;
return $this;
}
/**
* @return $this
*/
public function setUserIcon(?string $userIcon = null): self
{
$this->userIcon = $userIcon;
if (\is_string($userIcon)) {
$this->userIcon = trim($userIcon, ':');
}
return $this;
}
/**
* @return $this
*/
public function useShortAttachment(bool $useShortAttachment = false): self
{
$this->useShortAttachment = $useShortAttachment;
return $this;
}
/**
* @return $this
*/
public function includeContextAndExtra(bool $includeContextAndExtra = false): self
{
$this->includeContextAndExtra = $includeContextAndExtra;
if ($this->includeContextAndExtra) {
$this->normalizerFormatter = new NormalizerFormatter();
}
return $this;
}
/**
* @param string[] $excludeFields
* @return $this
*/
public function excludeFields(array $excludeFields = []): self
{
$this->excludeFields = $excludeFields;
return $this;
}
/**
* @return $this
*/
public function setFormatter(?FormatterInterface $formatter = null): self
{
$this->formatter = $formatter;
return $this;
}
/**
* Generates attachment field
*
* @param string|mixed[] $value
*
* @return array{title: string, value: string, short: false}
*/
private function generateAttachmentField(string $title, $value): array
{
$value = \is_array($value)
? sprintf('```%s```', substr($this->stringify($value), 0, 1990))
: $value;
return [
'title' => ucfirst($title),
'value' => $value,
'short' => false,
];
}
/**
* Generates a collection of attachment fields from array
*
* @param mixed[] $data
*
* @return array<array{title: string, value: string, short: false}>
*/
private function generateAttachmentFields(array $data): array
{
/** @var array<array<mixed>|string> $normalized */
$normalized = $this->normalizerFormatter->normalizeValue($data);
$fields = [];
foreach ($normalized as $key => $value) {
$fields[] = $this->generateAttachmentField((string) $key, $value);
}
return $fields;
}
/**
* Get a copy of record with fields excluded according to $this->excludeFields
*
* @return mixed[]
*/
private function removeExcludedFields(LogRecord $record): array
{
$recordData = $record->toArray();
foreach ($this->excludeFields as $field) {
$keys = explode('.', $field);
$node = &$recordData;
$lastKey = end($keys);
foreach ($keys as $key) {
if (!isset($node[$key])) {
break;
}
if ($lastKey === $key) {
unset($node[$key]);
break;
}
$node = &$node[$key];
}
}
return $recordData;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Handler/Curl/Util.php | src/Monolog/Handler/Curl/Util.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\Curl;
use CurlHandle;
/**
* This class is marked as internal and it is not under the BC promise of the package.
*
* @internal
*/
final class Util
{
/** @var array<int> */
private static array $retriableErrorCodes = [
CURLE_COULDNT_RESOLVE_HOST,
CURLE_COULDNT_CONNECT,
CURLE_HTTP_NOT_FOUND,
CURLE_READ_ERROR,
CURLE_OPERATION_TIMEOUTED,
CURLE_HTTP_POST_ERROR,
CURLE_SSL_CONNECT_ERROR,
];
/**
* Executes a CURL request with optional retries and exception on failure
*
* @param CurlHandle $ch curl handler
* @return bool|string @see curl_exec
*/
public static function execute(CurlHandle $ch, int $retries = 5): bool|string
{
while ($retries > 0) {
$retries--;
$curlResponse = curl_exec($ch);
if ($curlResponse === false) {
$curlErrno = curl_errno($ch);
if (false === \in_array($curlErrno, self::$retriableErrorCodes, true) || $retries === 0) {
$curlError = curl_error($ch);
throw new \RuntimeException(sprintf('Curl error (code %d): %s', $curlErrno, $curlError));
}
continue;
}
return $curlResponse;
}
return false;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Attribute/AsMonologProcessor.php | src/Monolog/Attribute/AsMonologProcessor.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\Attribute;
/**
* A reusable attribute to help configure a class or a method as a processor.
*
* Using it offers no guarantee: it needs to be leveraged by a Monolog third-party consumer.
*
* Using it with the Monolog library only has no effect at all: processors should still be turned into a callable if
* needed and manually pushed to the loggers and to the processable handlers.
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class AsMonologProcessor
{
/**
* @param string|null $channel The logging channel the processor should be pushed to.
* @param string|null $handler The handler the processor should be pushed to.
* @param string|null $method The method that processes the records (if the attribute is used at the class level).
* @param int|null $priority The priority of the processor so the order can be determined.
*/
public function __construct(
public readonly ?string $channel = null,
public readonly ?string $handler = null,
public readonly ?string $method = null,
public readonly ?int $priority = null
) {
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/src/Monolog/Attribute/WithMonologChannel.php | src/Monolog/Attribute/WithMonologChannel.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\Attribute;
/**
* A reusable attribute to help configure a class as expecting a given logger channel.
*
* Using it offers no guarantee: it needs to be leveraged by a Monolog third-party consumer.
*
* Using it with the Monolog library only has no effect at all: wiring the logger instance into
* other classes is not managed by Monolog.
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
final class WithMonologChannel
{
public function __construct(
public readonly string $channel
) {
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/bootstrap.php | tests/bootstrap.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.
*/
date_default_timezone_set('UTC');
require __DIR__.'/../vendor/autoload.php';
// B.C. for PSR Log's old inheritance
// see https://github.com/php-fig/log/pull/52
if (!class_exists('\\PHPUnit_Framework_TestCase', true)) {
class_alias('\\PHPUnit\\Framework\\TestCase', '\\PHPUnit_Framework_TestCase');
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/SignalHandlerTest.php | tests/Monolog/SignalHandlerTest.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 Monolog\Handler\StreamHandler;
use Monolog\Handler\TestHandler;
use Monolog\Test\MonologTestCase;
use PHPUnit\Framework\Attributes\DataProvider;
use Psr\Log\LogLevel;
/**
* @author Robert Gust-Bardon <robert@gust-bardon.org>
* @covers Monolog\SignalHandler
*/
class SignalHandlerTest extends MonologTestCase
{
private bool $asyncSignalHandling;
private array $blockedSignals = [];
private array $signalHandlers = [];
protected function setUp(): void
{
$this->signalHandlers = [];
if (\extension_loaded('pcntl')) {
if (\function_exists('pcntl_async_signals')) {
$this->asyncSignalHandling = pcntl_async_signals();
}
if (\function_exists('pcntl_sigprocmask')) {
pcntl_sigprocmask(SIG_SETMASK, [], $this->blockedSignals);
}
}
}
public function tearDown(): void
{
parent::tearDown();
if ($this->asyncSignalHandling !== null) {
pcntl_async_signals($this->asyncSignalHandling);
}
if ($this->blockedSignals !== null) {
pcntl_sigprocmask(SIG_SETMASK, $this->blockedSignals);
}
if ($this->signalHandlers) {
pcntl_signal_dispatch();
foreach ($this->signalHandlers as $signo => $handler) {
pcntl_signal($signo, $handler);
}
}
unset($this->signalHandlers, $this->blockedSignals, $this->asyncSignalHandling);
}
private function setSignalHandler($signo, $handler = SIG_DFL)
{
if (\function_exists('pcntl_signal_get_handler')) {
$this->signalHandlers[$signo] = pcntl_signal_get_handler($signo);
} else {
$this->signalHandlers[$signo] = SIG_DFL;
}
$this->assertTrue(pcntl_signal($signo, $handler));
}
public function testHandleSignal()
{
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$signo = 2; // SIGINT.
$siginfo = ['signo' => $signo, 'errno' => 0, 'code' => 0];
$errHandler->handleSignal($signo, $siginfo);
$this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasCriticalRecords());
$records = $handler->getRecords();
$this->assertSame($siginfo, $records[0]['context']);
}
/**
* @depends testHandleSignal
* @requires extension pcntl
* @requires extension posix
* @requires function pcntl_signal
* @requires function pcntl_signal_dispatch
* @requires function posix_getpid
* @requires function posix_kill
*/
public function testRegisterSignalHandler()
{
// SIGCONT and SIGURG should be ignored by default.
if (!\defined('SIGCONT') || !\defined('SIGURG')) {
$this->markTestSkipped('This test requires the SIGCONT and SIGURG pcntl constants.');
}
$this->setSignalHandler(SIGCONT, SIG_IGN);
$this->setSignalHandler(SIGURG, SIG_IGN);
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$pid = posix_getpid();
$this->assertTrue(posix_kill($pid, SIGURG));
$this->assertTrue(pcntl_signal_dispatch());
$this->assertCount(0, $handler->getRecords());
$errHandler->registerSignalHandler(SIGURG, LogLevel::INFO, false, false, false);
$this->assertTrue(posix_kill($pid, SIGCONT));
$this->assertTrue(pcntl_signal_dispatch());
$this->assertCount(0, $handler->getRecords());
$this->assertTrue(posix_kill($pid, SIGURG));
$this->assertTrue(pcntl_signal_dispatch());
$this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasInfoThatContains('SIGURG'));
}
/**
* @depends testRegisterSignalHandler
* @requires function pcntl_fork
* @requires function pcntl_sigprocmask
* @requires function pcntl_waitpid
*/
#[DataProvider('defaultPreviousProvider')]
public function testRegisterDefaultPreviousSignalHandler($signo, $callPrevious, $expected)
{
$this->setSignalHandler($signo, SIG_DFL);
$path = tempnam(sys_get_temp_dir(), 'monolog-');
$this->assertNotFalse($path);
$pid = pcntl_fork();
if ($pid === 0) { // Child.
$streamHandler = new StreamHandler($path);
$streamHandler->setFormatter($this->getIdentityFormatter());
$logger = new Logger('test', [$streamHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler($signo, LogLevel::INFO, $callPrevious, false, false);
pcntl_sigprocmask(SIG_SETMASK, [SIGCONT]);
posix_kill(posix_getpid(), $signo);
pcntl_signal_dispatch();
// If $callPrevious is true, SIGINT should terminate by this line.
pcntl_sigprocmask(SIG_SETMASK, [], $oldset);
file_put_contents($path, implode(' ', $oldset), FILE_APPEND);
posix_kill(posix_getpid(), $signo);
pcntl_signal_dispatch();
exit();
}
$this->assertNotSame(-1, $pid);
$this->assertNotSame(-1, pcntl_waitpid($pid, $status));
$this->assertNotSame(-1, $status);
$this->assertSame($expected, file_get_contents($path));
}
public static function defaultPreviousProvider()
{
if (!\defined('SIGCONT') || !\defined('SIGINT') || !\defined('SIGURG')) {
return [];
}
return [
[SIGINT, false, 'Program received signal SIGINT'.SIGCONT.'Program received signal SIGINT'],
[SIGINT, true, 'Program received signal SIGINT'],
[SIGURG, false, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'],
[SIGURG, true, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'],
];
}
/**
* @depends testRegisterSignalHandler
* @requires function pcntl_signal_get_handler
*/
#[DataProvider('callablePreviousProvider')]
public function testRegisterCallablePreviousSignalHandler($callPrevious)
{
$this->setSignalHandler(SIGURG, SIG_IGN);
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$previousCalled = 0;
pcntl_signal(SIGURG, function ($signo, ?array $siginfo = null) use (&$previousCalled) {
++$previousCalled;
});
$errHandler->registerSignalHandler(SIGURG, LogLevel::INFO, $callPrevious, false, false);
$this->assertTrue(posix_kill(posix_getpid(), SIGURG));
$this->assertTrue(pcntl_signal_dispatch());
$this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasInfoThatContains('SIGURG'));
$this->assertSame($callPrevious ? 1 : 0, $previousCalled);
}
public static function callablePreviousProvider()
{
return [
[false],
[true],
];
}
/**
* @depends testRegisterDefaultPreviousSignalHandler
* @requires function pcntl_fork
* @requires function pcntl_waitpid
*/
#[DataProvider('restartSyscallsProvider')]
public function testRegisterSyscallRestartingSignalHandler($restartSyscalls)
{
$this->setSignalHandler(SIGURG, SIG_IGN);
$parentPid = posix_getpid();
$microtime = microtime(true);
$pid = pcntl_fork();
if ($pid === 0) { // Child.
usleep(100000);
posix_kill($parentPid, SIGURG);
usleep(100000);
exit();
}
$this->assertNotSame(-1, $pid);
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler(SIGURG, LogLevel::INFO, false, $restartSyscalls, false);
if ($restartSyscalls) {
// pcntl_wait is expected to be restarted after the signal handler.
$this->assertNotSame(-1, pcntl_waitpid($pid, $status));
} else {
// pcntl_wait is expected to be interrupted when the signal handler is invoked.
$this->assertSame(-1, pcntl_waitpid($pid, $status));
}
$this->assertSame($restartSyscalls, microtime(true) - $microtime > 0.15);
$this->assertTrue(pcntl_signal_dispatch());
$this->assertCount(1, $handler->getRecords());
if ($restartSyscalls) {
// The child has already exited.
$this->assertSame(-1, pcntl_waitpid($pid, $status));
} else {
// The child has not exited yet.
$this->assertNotSame(-1, pcntl_waitpid($pid, $status));
}
}
public static function restartSyscallsProvider()
{
return [
[false],
[true],
[false],
[true],
];
}
/**
* @depends testRegisterDefaultPreviousSignalHandler
* @requires function pcntl_async_signals
*/
#[DataProvider('asyncProvider')]
public function testRegisterAsyncSignalHandler($initialAsync, $desiredAsync, $expectedBefore, $expectedAfter)
{
$this->setSignalHandler(SIGURG, SIG_IGN);
pcntl_async_signals($initialAsync);
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler(SIGURG, LogLevel::INFO, false, false, $desiredAsync);
$this->assertTrue(posix_kill(posix_getpid(), SIGURG));
$this->assertCount($expectedBefore, $handler->getRecords());
$this->assertTrue(pcntl_signal_dispatch());
$this->assertCount($expectedAfter, $handler->getRecords());
}
public static function asyncProvider()
{
return [
[false, false, 0, 1],
[false, null, 0, 1],
[false, true, 1, 1],
[true, false, 0, 1],
[true, null, 1, 1],
[true, true, 1, 1],
];
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/ErrorHandlerTest.php | tests/Monolog/ErrorHandlerTest.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 Monolog\Handler\TestHandler;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\WithoutErrorHandler;
use Psr\Log\LogLevel;
class ErrorHandlerTest extends \PHPUnit\Framework\TestCase
{
public function testRegister()
{
$logger = new Logger('test', [$handler = new TestHandler]);
$this->assertInstanceOf(ErrorHandler::class, ErrorHandler::register($logger, false, false, false));
}
#[WithoutErrorHandler]
public function testHandleError()
{
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new ErrorHandler($logger);
$phpunitHandler = set_error_handler($prevHandler = function () {
});
try {
$errHandler->registerErrorHandler([], true);
$prop = $this->getPrivatePropertyValue($errHandler, 'previousErrorHandler');
$this->assertTrue(\is_callable($prop));
$this->assertSame($prevHandler, $prop);
$resHandler = $errHandler->registerErrorHandler([E_USER_NOTICE => LogLevel::EMERGENCY], false);
$this->assertSame($errHandler, $resHandler);
trigger_error('Foo', E_USER_ERROR);
$this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasErrorRecords());
trigger_error('Foo', E_USER_NOTICE);
$this->assertCount(2, $handler->getRecords());
// check that the remapping of notice to emergency above worked
$this->assertTrue($handler->hasEmergencyRecords());
$this->assertFalse($handler->hasNoticeRecords());
} finally {
// restore previous handler
set_error_handler($phpunitHandler);
}
}
public static function fatalHandlerProvider()
{
return [
[null, 10, str_repeat(' ', 1024 * 10), LogLevel::ALERT],
[LogLevel::DEBUG, 15, str_repeat(' ', 1024 * 15), LogLevel::DEBUG],
];
}
protected function getPrivatePropertyValue($instance, $property)
{
$ref = new \ReflectionClass(\get_class($instance));
$prop = $ref->getProperty($property);
return $prop->getValue($instance);
}
#[DataProvider('fatalHandlerProvider')]
#[WithoutErrorHandler]
public function testFatalHandler(
$level,
$reservedMemorySize,
$expectedReservedMemory,
$expectedFatalLevel
) {
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new ErrorHandler($logger);
$res = $errHandler->registerFatalHandler($level, $reservedMemorySize);
$this->assertSame($res, $errHandler);
$this->assertTrue($this->getPrivatePropertyValue($errHandler, 'hasFatalErrorHandler'));
$this->assertEquals($expectedReservedMemory, $this->getPrivatePropertyValue($errHandler, 'reservedMemory'));
$this->assertEquals($expectedFatalLevel, $this->getPrivatePropertyValue($errHandler, 'fatalLevel'));
}
#[WithoutErrorHandler]
public function testHandleException()
{
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new ErrorHandler($logger);
$resHandler = $errHandler->registerExceptionHandler($map = ['Monolog\CustomTestException' => LogLevel::DEBUG, 'TypeError' => LogLevel::NOTICE, 'Throwable' => LogLevel::WARNING], false);
$this->assertSame($errHandler, $resHandler);
$map['ParseError'] = LogLevel::CRITICAL;
$prop = $this->getPrivatePropertyValue($errHandler, 'uncaughtExceptionLevelMap');
$this->assertSame($map, $prop);
$errHandler->registerExceptionHandler([], true);
$prop = $this->getPrivatePropertyValue($errHandler, 'previousExceptionHandler');
$this->assertTrue(\is_callable($prop));
restore_exception_handler();
restore_exception_handler();
}
public function testCodeToString()
{
$method = new \ReflectionMethod(ErrorHandler::class, 'codeToString');
$this->assertEquals('E_ERROR', $method->invokeArgs(null, [E_ERROR]));
$this->assertEquals('E_WARNING', $method->invokeArgs(null, [E_WARNING]));
$this->assertEquals('E_PARSE', $method->invokeArgs(null, [E_PARSE]));
$this->assertEquals('E_NOTICE', $method->invokeArgs(null, [E_NOTICE]));
$this->assertEquals('E_CORE_ERROR', $method->invokeArgs(null, [E_CORE_ERROR]));
$this->assertEquals('E_CORE_WARNING', $method->invokeArgs(null, [E_CORE_WARNING]));
$this->assertEquals('E_COMPILE_ERROR', $method->invokeArgs(null, [E_COMPILE_ERROR]));
$this->assertEquals('E_COMPILE_WARNING', $method->invokeArgs(null, [E_COMPILE_WARNING]));
$this->assertEquals('E_USER_ERROR', $method->invokeArgs(null, [E_USER_ERROR]));
$this->assertEquals('E_USER_WARNING', $method->invokeArgs(null, [E_USER_WARNING]));
$this->assertEquals('E_USER_NOTICE', $method->invokeArgs(null, [E_USER_NOTICE]));
$this->assertEquals('E_STRICT', $method->invokeArgs(null, [2048]));
$this->assertEquals('E_RECOVERABLE_ERROR', $method->invokeArgs(null, [E_RECOVERABLE_ERROR]));
$this->assertEquals('E_DEPRECATED', $method->invokeArgs(null, [E_DEPRECATED]));
$this->assertEquals('E_USER_DEPRECATED', $method->invokeArgs(null, [E_USER_DEPRECATED]));
$this->assertEquals('Unknown PHP error', $method->invokeArgs(null, [E_ALL]));
}
}
class CustomTestException extends \Exception
{
}
class CustomCustomException extends CustomTestException
{
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/PsrLogCompatTest.php | tests/Monolog/PsrLogCompatTest.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;
use Monolog\Handler\TestHandler;
use Monolog\Formatter\LineFormatter;
use Monolog\Processor\PsrLogMessageProcessor;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Stringable;
class PsrLogCompatTest extends \Monolog\Test\MonologTestCase
{
private TestHandler $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->handler);
}
public function getLogger(): LoggerInterface
{
$logger = new Logger('foo');
$logger->pushHandler($handler = new TestHandler);
$logger->pushProcessor(new PsrLogMessageProcessor);
$handler->setFormatter(new LineFormatter('%level_name% %message%'));
$this->handler = $handler;
return $logger;
}
public function getLogs(): array
{
$convert = function ($record) {
$lower = function ($match) {
return strtolower($match[0]);
};
return preg_replace_callback('{^[A-Z]+}', $lower, $record->formatted);
};
return array_map($convert, $this->handler->getRecords());
}
public function testImplements()
{
$this->assertInstanceOf(LoggerInterface::class, $this->getLogger());
}
#[DataProvider('provideLevelsAndMessages')]
public function testLogsAtAllLevels($level, $message)
{
$logger = $this->getLogger();
$logger->{$level}($message, ['user' => 'Bob']);
$logger->log($level, $message, ['user' => 'Bob']);
$expected = [
"$level message of level $level with context: Bob",
"$level message of level $level with context: Bob",
];
$this->assertEquals($expected, $this->getLogs());
}
public static function provideLevelsAndMessages()
{
return [
LogLevel::EMERGENCY => [LogLevel::EMERGENCY, 'message of level emergency with context: {user}'],
LogLevel::ALERT => [LogLevel::ALERT, 'message of level alert with context: {user}'],
LogLevel::CRITICAL => [LogLevel::CRITICAL, 'message of level critical with context: {user}'],
LogLevel::ERROR => [LogLevel::ERROR, 'message of level error with context: {user}'],
LogLevel::WARNING => [LogLevel::WARNING, 'message of level warning with context: {user}'],
LogLevel::NOTICE => [LogLevel::NOTICE, 'message of level notice with context: {user}'],
LogLevel::INFO => [LogLevel::INFO, 'message of level info with context: {user}'],
LogLevel::DEBUG => [LogLevel::DEBUG, 'message of level debug with context: {user}'],
];
}
public function testThrowsOnInvalidLevel()
{
$logger = $this->getLogger();
$this->expectException(InvalidArgumentException::class);
$logger->log('invalid level', 'Foo');
}
public function testContextReplacement()
{
$logger = $this->getLogger();
$logger->info('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
$expected = ['info {Message {nothing} Bob Bar a}'];
$this->assertEquals($expected, $this->getLogs());
}
public function testObjectCastToString()
{
$string = uniqid('DUMMY');
$dummy = $this->createStringable($string);
$dummy->expects($this->once())
->method('__toString');
$this->getLogger()->warning($dummy);
$expected = ["warning $string"];
$this->assertEquals($expected, $this->getLogs());
}
public function testContextCanContainAnything()
{
$closed = fopen('php://memory', 'r');
fclose($closed);
$context = [
'bool' => true,
'null' => null,
'string' => 'Foo',
'int' => 0,
'float' => 0.5,
'nested' => ['with object' => $this->createStringable()],
'object' => new \DateTime('now', new DateTimeZone('Europe/London')),
'resource' => fopen('php://memory', 'r'),
'closed' => $closed,
];
$this->getLogger()->warning('Crazy context data', $context);
$expected = ['warning Crazy context data'];
$this->assertEquals($expected, $this->getLogs());
}
public function testContextExceptionKeyCanBeExceptionOrOtherValues()
{
$logger = $this->getLogger();
$logger->warning('Random message', ['exception' => 'oops']);
$logger->critical('Uncaught Exception!', ['exception' => new \LogicException('Fail')]);
$expected = [
'warning Random message',
'critical Uncaught Exception!',
];
$this->assertEquals($expected, $this->getLogs());
}
/**
* Creates a mock of a `Stringable`.
*
* @param string $string The string that must be represented by the stringable.
*/
protected function createStringable(string $string = ''): MockObject&Stringable
{
$mock = $this->getMockBuilder(Stringable::class)
->getMock();
$mock->method('__toString')
->willReturn($string);
return $mock;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/LoggerTest.php | tests/Monolog/LoggerTest.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 Monolog\Handler\HandlerInterface;
use Monolog\Processor\WebProcessor;
use Monolog\Handler\TestHandler;
use Monolog\Test\MonologTestCase;
use PHPUnit\Framework\Attributes\DataProvider;
class LoggerTest extends MonologTestCase
{
/**
* @covers Logger::getName
*/
public function testGetName()
{
$logger = new Logger('foo');
$this->assertEquals('foo', $logger->getName());
}
/**
* @covers Logger::withName
*/
public function testWithName()
{
$first = new Logger('first', [$handler = new TestHandler()]);
$second = $first->withName('second');
$this->assertSame('first', $first->getName());
$this->assertSame('second', $second->getName());
$this->assertSame($handler, $second->popHandler());
}
/**
* @covers Logger::toMonologLevel
*/
public function testConvertPSR3ToMonologLevel()
{
$this->assertEquals(Logger::toMonologLevel('debug'), Level::Debug);
$this->assertEquals(Logger::toMonologLevel('info'), Level::Info);
$this->assertEquals(Logger::toMonologLevel('notice'), Level::Notice);
$this->assertEquals(Logger::toMonologLevel('warning'), Level::Warning);
$this->assertEquals(Logger::toMonologLevel('error'), Level::Error);
$this->assertEquals(Logger::toMonologLevel('critical'), Level::Critical);
$this->assertEquals(Logger::toMonologLevel('alert'), Level::Alert);
$this->assertEquals(Logger::toMonologLevel('emergency'), Level::Emergency);
}
/**
* @covers Monolog\Logger::addRecord
* @covers Monolog\Logger::log
*/
public function testConvertRFC5424ToMonologLevelInAddRecordAndLog()
{
$logger = new Logger('test');
$handler = new TestHandler;
$logger->pushHandler($handler);
foreach ([
7 => 100,
6 => 200,
5 => 250,
4 => 300,
3 => 400,
2 => 500,
1 => 550,
0 => 600,
] as $rfc5424Level => $monologLevel) {
$handler->reset();
$logger->addRecord($rfc5424Level, 'test');
$logger->log($rfc5424Level, 'test');
$records = $handler->getRecords();
self::assertCount(2, $records);
self::assertSame($monologLevel, $records[0]['level']);
self::assertSame($monologLevel, $records[1]['level']);
}
}
/**
* @covers Logger::__construct
*/
public function testChannel()
{
$logger = new Logger('foo');
$handler = new TestHandler;
$logger->pushHandler($handler);
$logger->warning('test');
list($record) = $handler->getRecords();
$this->assertEquals('foo', $record->channel);
}
/**
* @covers Logger::addRecord
*/
public function testLogPreventsCircularLogging()
{
$logger = new Logger(__METHOD__);
$loggingHandler = new LoggingHandler($logger);
$testHandler = new TestHandler();
$logger->pushHandler($loggingHandler);
$logger->pushHandler($testHandler);
$logger->addRecord(Level::Alert, 'test');
$records = $testHandler->getRecords();
$this->assertCount(3, $records);
$this->assertSame('ALERT', $records[0]->level->getName());
$this->assertSame('DEBUG', $records[1]->level->getName());
$this->assertSame('WARNING', $records[2]->level->getName());
}
/**
* @covers Monolog\Logger::addRecord
*/
public function testLog()
{
$logger = new Logger(__METHOD__);
$handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();
$handler->expects($this->never())->method('isHandling');
$handler->expects($this->once())->method('handle');
$logger->pushHandler($handler);
$this->assertTrue($logger->addRecord(Level::Warning, 'test'));
}
/**
* @covers Logger::addRecord
*/
public function testLogAlwaysHandledIfNoProcessorsArePresent()
{
$logger = new Logger(__METHOD__);
$handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();
$handler->expects($this->never())->method('isHandling');
$handler->expects($this->once())->method('handle');
$logger->pushHandler($handler);
$this->assertTrue($logger->addRecord(Level::Warning, 'test'));
}
/**
* @covers Logger::addRecord
*/
public function testLogNotHandledIfProcessorsArePresent()
{
$logger = new Logger(__METHOD__);
$handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();
$handler->expects($this->once())->method('isHandling')->willReturn(false);
$handler->expects($this->never())->method('handle');
$logger->pushProcessor(fn (LogRecord $record) => $record);
$logger->pushHandler($handler);
$this->assertFalse($logger->addRecord(Level::Warning, 'test'));
}
public function testHandlersInCtor()
{
$handler1 = new TestHandler;
$handler2 = new TestHandler;
$logger = new Logger(__METHOD__, [$handler1, $handler2]);
$this->assertEquals($handler1, $logger->popHandler());
$this->assertEquals($handler2, $logger->popHandler());
}
public function testProcessorsInCtor()
{
$processor1 = new WebProcessor;
$processor2 = new WebProcessor;
$logger = new Logger(__METHOD__, [], [$processor1, $processor2]);
$this->assertEquals($processor1, $logger->popProcessor());
$this->assertEquals($processor2, $logger->popProcessor());
}
/**
* @covers Logger::pushHandler
* @covers Logger::popHandler
*/
public function testPushPopHandler()
{
$logger = new Logger(__METHOD__);
$handler1 = new TestHandler;
$handler2 = new TestHandler;
$logger->pushHandler($handler1);
$logger->pushHandler($handler2);
$this->assertEquals($handler2, $logger->popHandler());
$this->assertEquals($handler1, $logger->popHandler());
$this->expectException(\LogicException::class);
$logger->popHandler();
}
/**
* @covers Logger::setHandlers
*/
public function testSetHandlers()
{
$logger = new Logger(__METHOD__);
$handler1 = new TestHandler;
$handler2 = new TestHandler;
$logger->pushHandler($handler1);
$logger->setHandlers([$handler2]);
// handler1 has been removed
$this->assertEquals([$handler2], $logger->getHandlers());
$logger->setHandlers([
"AMapKey" => $handler1,
"Woop" => $handler2,
]);
// Keys have been scrubbed
$this->assertEquals([$handler1, $handler2], $logger->getHandlers());
}
/**
* @covers Logger::pushProcessor
* @covers Logger::popProcessor
*/
public function testPushPopProcessor()
{
$logger = new Logger(__METHOD__);
$processor1 = new WebProcessor;
$processor2 = new WebProcessor;
$logger->pushProcessor($processor1);
$logger->pushProcessor($processor2);
$this->assertEquals($processor2, $logger->popProcessor());
$this->assertEquals($processor1, $logger->popProcessor());
$this->expectException(\LogicException::class);
$logger->popProcessor();
}
/**
* @covers Logger::addRecord
*/
public function testProcessorsAreExecuted()
{
$logger = new Logger(__METHOD__);
$handler = new TestHandler;
$logger->pushHandler($handler);
$logger->pushProcessor(function ($record) {
$record->extra['win'] = true;
return $record;
});
$logger->error('test');
list($record) = $handler->getRecords();
$this->assertTrue($record->extra['win']);
}
/**
* @covers Logger::addRecord
*/
public function testProcessorsAreCalledOnlyOnce()
{
$logger = new Logger(__METHOD__);
$handler = $this->createMock('Monolog\Handler\HandlerInterface');
$handler->expects($this->any())
->method('isHandling')
->willReturn(true);
$handler->expects($this->any())
->method('handle')
->willReturn(true);
$logger->pushHandler($handler);
$processor = $this->getMockBuilder('Monolog\Processor\WebProcessor')
->disableOriginalConstructor()
->onlyMethods(['__invoke'])
->getMock()
;
$processor->expects($this->once())
->method('__invoke')
->willReturnArgument(0)
;
$logger->pushProcessor($processor);
$logger->error('test');
}
/**
* @covers Logger::addRecord
*/
public function testProcessorsNotCalledWhenNotHandled()
{
$logger = new Logger(__METHOD__);
$handler = $this->createMock('Monolog\Handler\HandlerInterface');
$handler->expects($this->once())
->method('isHandling')
->willReturn(false);
$logger->pushHandler($handler);
$that = $this;
$logger->pushProcessor(function ($record) use ($that) {
$that->fail('The processor should not be called');
});
$logger->alert('test');
}
/**
* @covers Logger::addRecord
*/
public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresent()
{
$logger = new Logger(__METHOD__);
$logger->pushProcessor(fn ($record) => $record);
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->never())
->method('isHandling')
->willReturn(false);
$handler1->expects($this->once())
->method('handle')
->willReturn(false);
$logger->pushHandler($handler1);
$handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->once())
->method('isHandling')
->willReturn(true);
$handler2->expects($this->once())
->method('handle')
->willReturn(false);
$logger->pushHandler($handler2);
$handler3 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler3->expects($this->once())
->method('isHandling')
->willReturn(false);
$handler3->expects($this->never())
->method('handle')
;
$logger->pushHandler($handler3);
$logger->debug('test');
}
/**
* @covers Logger::addRecord
*/
public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresentWithAssocArray()
{
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->never())
->method('isHandling')
->willReturn(false);
$handler1->expects($this->once())
->method('handle')
->willReturn(false);
$handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->once())
->method('isHandling')
->willReturn(true);
$handler2->expects($this->once())
->method('handle')
->willReturn(false);
$handler3 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler3->expects($this->once())
->method('isHandling')
->willReturn(false);
$handler3->expects($this->never())
->method('handle')
;
$logger = new Logger(__METHOD__, ['last' => $handler3, 'second' => $handler2, 'first' => $handler1]);
$logger->pushProcessor(fn ($record) => $record);
$logger->debug('test');
}
/**
* @covers Logger::addRecord
*/
public function testBubblingWhenTheHandlerReturnsFalse()
{
$logger = new Logger(__METHOD__);
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->any())
->method('isHandling')
->willReturn(true);
$handler1->expects($this->once())
->method('handle')
->willReturn(false);
$logger->pushHandler($handler1);
$handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->any())
->method('isHandling')
->willReturn(true);
$handler2->expects($this->once())
->method('handle')
->willReturn(false);
$logger->pushHandler($handler2);
$logger->debug('test');
}
/**
* @covers Logger::addRecord
*/
public function testNotBubblingWhenTheHandlerReturnsTrue()
{
$logger = new Logger(__METHOD__);
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->any())
->method('isHandling')
->willReturn(true);
$handler1->expects($this->never())
->method('handle')
;
$logger->pushHandler($handler1);
$handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->any())
->method('isHandling')
->willReturn(true);
$handler2->expects($this->once())
->method('handle')
->willReturn(true);
$logger->pushHandler($handler2);
$logger->debug('test');
}
/**
* @covers Logger::isHandling
*/
public function testIsHandling()
{
$logger = new Logger(__METHOD__);
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->any())
->method('isHandling')
->willReturn(false);
$logger->pushHandler($handler1);
$this->assertFalse($logger->isHandling(Level::Debug));
$handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->any())
->method('isHandling')
->willReturn(true);
$logger->pushHandler($handler2);
$this->assertTrue($logger->isHandling(Level::Debug));
}
/**
* @covers Level::Debug
* @covers Level::Info
* @covers Level::Notice
* @covers Level::Warning
* @covers Level::Error
* @covers Level::Critical
* @covers Level::Alert
* @covers Level::Emergency
*/
#[DataProvider('logMethodProvider')]
public function testLogMethods(string $method, Level $expectedLevel)
{
$logger = new Logger('foo');
$handler = new TestHandler;
$logger->pushHandler($handler);
$logger->{$method}('test');
list($record) = $handler->getRecords();
$this->assertEquals($expectedLevel, $record->level);
}
public static function logMethodProvider()
{
return [
// PSR-3 methods
['debug', Level::Debug],
['info', Level::Info],
['notice', Level::Notice],
['warning', Level::Warning],
['error', Level::Error],
['critical', Level::Critical],
['alert', Level::Alert],
['emergency', Level::Emergency],
];
}
/**
* @covers Logger::setTimezone
*/
#[DataProvider('setTimezoneProvider')]
public function testSetTimezone($tz)
{
$logger = new Logger('foo');
$logger->setTimezone($tz);
$handler = new TestHandler;
$logger->pushHandler($handler);
$logger->info('test');
list($record) = $handler->getRecords();
$this->assertEquals($tz, $record->datetime->getTimezone());
}
public static function setTimezoneProvider()
{
return array_map(
function ($tz) {
return [new \DateTimeZone($tz)];
},
\DateTimeZone::listIdentifiers()
);
}
/**
* @covers Logger::setTimezone
* @covers JsonSerializableDateTimeImmutable::__construct
*/
public function testTimezoneIsRespectedInUTC()
{
foreach ([true, false] as $microseconds) {
$logger = new Logger('foo');
$logger->useMicrosecondTimestamps($microseconds);
$tz = new \DateTimeZone('America/New_York');
$logger->setTimezone($tz);
$handler = new TestHandler;
$logger->pushHandler($handler);
$dt = new \DateTime('now', $tz);
$logger->info('test');
list($record) = $handler->getRecords();
$this->assertEquals($tz, $record->datetime->getTimezone());
$this->assertEquals($dt->format('Y/m/d H:i'), $record->datetime->format('Y/m/d H:i'), 'Time should match timezone with microseconds set to: '.var_export($microseconds, true));
}
}
/**
* @covers Logger::setTimezone
* @covers JsonSerializableDateTimeImmutable::__construct
*/
public function testTimezoneIsRespectedInOtherTimezone()
{
date_default_timezone_set('CET');
foreach ([true, false] as $microseconds) {
$logger = new Logger('foo');
$logger->useMicrosecondTimestamps($microseconds);
$tz = new \DateTimeZone('America/New_York');
$logger->setTimezone($tz);
$handler = new TestHandler;
$logger->pushHandler($handler);
$dt = new \DateTime('now', $tz);
$logger->info('test');
list($record) = $handler->getRecords();
$this->assertEquals($tz, $record->datetime->getTimezone());
$this->assertEquals($dt->format('Y/m/d H:i'), $record->datetime->format('Y/m/d H:i'), 'Time should match timezone with microseconds set to: '.var_export($microseconds, true));
}
}
public function tearDown(): void
{
date_default_timezone_set('UTC');
}
/**
* @covers Logger::useMicrosecondTimestamps
* @covers Logger::addRecord
*/
#[DataProvider('useMicrosecondTimestampsProvider')]
public function testUseMicrosecondTimestamps($micro, $assert, $assertFormat)
{
if (PHP_VERSION_ID === 70103) {
$this->markTestSkipped();
}
$logger = new Logger('foo');
$logger->useMicrosecondTimestamps($micro);
$handler = new TestHandler;
$logger->pushHandler($handler);
$logger->info('test');
list($record) = $handler->getRecords();
$this->{$assert}('000000', $record->datetime->format('u'));
$this->assertSame($record->datetime->format($assertFormat), (string) $record->datetime);
}
public static function useMicrosecondTimestampsProvider()
{
return [
// this has a very small chance of a false negative (1/10^6)
'with microseconds' => [true, 'assertNotSame', 'Y-m-d\TH:i:s.uP'],
// php 7.1 always includes microseconds, so we keep them in, but we format the datetime without
'without microseconds' => [false, 'assertNotSame', 'Y-m-d\TH:i:sP'],
];
}
public function testProcessorsDoNotInterfereBetweenHandlers()
{
$logger = new Logger('foo');
$logger->pushHandler($t1 = new TestHandler());
$logger->pushHandler($t2 = new TestHandler());
$t1->pushProcessor(function (LogRecord $record) {
$record->extra['foo'] = 'bar';
return $record;
});
$logger->error('Foo');
self::assertSame([], $t2->getRecords()[0]->extra);
}
/**
* @covers Logger::setExceptionHandler
*/
public function testSetExceptionHandler()
{
$logger = new Logger(__METHOD__);
$this->assertNull($logger->getExceptionHandler());
$callback = function ($ex) {
};
$logger->setExceptionHandler($callback);
$this->assertEquals($callback, $logger->getExceptionHandler());
}
/**
* @covers Logger::handleException
*/
public function testDefaultHandleException()
{
$logger = new Logger(__METHOD__);
$handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();
$handler->expects($this->any())
->method('isHandling')
->willReturn(true);
$handler->expects($this->any())
->method('handle')
->will($this->throwException(new \Exception('Some handler exception')))
;
$this->expectException(\Exception::class);
$logger->pushHandler($handler);
$logger->info('test');
}
/**
* @covers Logger::handleException
* @covers Logger::addRecord
*/
public function testCustomHandleException()
{
$logger = new Logger(__METHOD__);
$that = $this;
$logger->setExceptionHandler(function ($e, $record) use ($that) {
$that->assertEquals($e->getMessage(), 'Some handler exception');
$that->assertInstanceOf(LogRecord::class, $record);
$that->assertEquals($record->message, 'test');
});
$handler = $this->getMockBuilder('Monolog\Handler\HandlerInterface')->getMock();
$handler->expects($this->any())
->method('isHandling')
->willReturn(true);
$handler->expects($this->any())
->method('handle')
->will($this->throwException(new \Exception('Some handler exception')))
;
$logger->pushHandler($handler);
$logger->info('test');
}
public function testSerializable()
{
$logger = new Logger(__METHOD__);
$copy = unserialize(serialize($logger));
self::assertInstanceOf(Logger::class, $copy);
self::assertSame($logger->getName(), $copy->getName());
self::assertSame($logger->getTimezone()->getName(), $copy->getTimezone()->getName());
self::assertSame($logger->getHandlers(), $copy->getHandlers());
}
public function testReset()
{
$logger = new Logger('app');
$testHandler = new Handler\TestHandler();
$testHandler->setSkipReset(true);
$bufferHandler = new Handler\BufferHandler($testHandler);
$groupHandler = new Handler\GroupHandler([$bufferHandler]);
$fingersCrossedHandler = new Handler\FingersCrossedHandler($groupHandler);
$logger->pushHandler($fingersCrossedHandler);
$processorUid1 = new Processor\UidProcessor(10);
$uid1 = $processorUid1->getUid();
$groupHandler->pushProcessor($processorUid1);
$processorUid2 = new Processor\UidProcessor(5);
$uid2 = $processorUid2->getUid();
$logger->pushProcessor($processorUid2);
$getProperty = function ($object, $property) {
$reflectionProperty = new \ReflectionProperty(\get_class($object), $property);
return $reflectionProperty->getValue($object);
};
$assertBufferOfBufferHandlerEmpty = function () use ($getProperty, $bufferHandler) {
self::assertEmpty($getProperty($bufferHandler, 'buffer'));
};
$assertBuffersEmpty = function () use ($assertBufferOfBufferHandlerEmpty, $getProperty, $fingersCrossedHandler) {
$assertBufferOfBufferHandlerEmpty();
self::assertEmpty($getProperty($fingersCrossedHandler, 'buffer'));
};
$logger->debug('debug1');
$logger->reset();
$assertBuffersEmpty();
$this->assertFalse($testHandler->hasDebugRecords());
$this->assertFalse($testHandler->hasErrorRecords());
$this->assertNotSame($uid1, $uid1 = $processorUid1->getUid());
$this->assertNotSame($uid2, $uid2 = $processorUid2->getUid());
$logger->debug('debug2');
$logger->error('error2');
$logger->reset();
$assertBuffersEmpty();
$this->assertTrue($testHandler->hasRecordThatContains('debug2', Level::Debug));
$this->assertTrue($testHandler->hasRecordThatContains('error2', Level::Error));
$this->assertNotSame($uid1, $uid1 = $processorUid1->getUid());
$this->assertNotSame($uid2, $uid2 = $processorUid2->getUid());
$logger->info('info3');
$this->assertNotEmpty($getProperty($fingersCrossedHandler, 'buffer'));
$assertBufferOfBufferHandlerEmpty();
$this->assertFalse($testHandler->hasInfoRecords());
$logger->reset();
$assertBuffersEmpty();
$this->assertFalse($testHandler->hasInfoRecords());
$this->assertNotSame($uid1, $uid1 = $processorUid1->getUid());
$this->assertNotSame($uid2, $uid2 = $processorUid2->getUid());
$logger->notice('notice4');
$logger->emergency('emergency4');
$logger->reset();
$assertBuffersEmpty();
$this->assertFalse($testHandler->hasInfoRecords());
$this->assertTrue($testHandler->hasRecordThatContains('notice4', Level::Notice));
$this->assertTrue($testHandler->hasRecordThatContains('emergency4', Level::Emergency));
$this->assertNotSame($uid1, $processorUid1->getUid());
$this->assertNotSame($uid2, $processorUid2->getUid());
}
/**
* @covers Logger::addRecord
*/
public function testLogWithDateTime()
{
foreach ([true, false] as $microseconds) {
$logger = new Logger(__METHOD__);
$loggingHandler = new LoggingHandler($logger);
$testHandler = new TestHandler();
$logger->pushHandler($loggingHandler);
$logger->pushHandler($testHandler);
$datetime = (new JsonSerializableDateTimeImmutable($microseconds))->modify('2022-03-04 05:06:07');
$logger->addRecord(Level::Debug, 'test', [], $datetime);
list($record) = $testHandler->getRecords();
$this->assertEquals($datetime->format('Y-m-d H:i:s'), $record->datetime->format('Y-m-d H:i:s'));
}
}
public function testLogCycleDetectionWithFibersWithoutCycle()
{
$logger = new Logger(__METHOD__);
$fiberSuspendHandler = new FiberSuspendHandler();
$testHandler = new TestHandler();
$logger->pushHandler($fiberSuspendHandler);
$logger->pushHandler($testHandler);
$fibers = [];
for ($i = 0; $i < 10; $i++) {
$fiber = new \Fiber(static function () use ($logger) {
$logger->info('test');
});
$fiber->start();
// We need to keep a reference here, because otherwise the fiber gets automatically cleaned up
$fibers[] = $fiber;
}
self::assertCount(10, $testHandler->getRecords());
}
public function testLogCycleDetectionWithFibersWithCycle()
{
$logger = new Logger(__METHOD__);
$fiberSuspendHandler = new FiberSuspendHandler();
$loggingHandler = new LoggingHandler($logger);
$testHandler = new TestHandler();
$logger->pushHandler($fiberSuspendHandler);
$logger->pushHandler($loggingHandler);
$logger->pushHandler($testHandler);
$fiber = new \Fiber(static function () use ($logger) {
$logger->info('test');
});
$fiber->start();
self::assertCount(3, $testHandler->getRecords());
}
}
class LoggingHandler implements HandlerInterface
{
/**
* @var Logger
*/
private $logger;
public function __construct(Logger $logger)
{
$this->logger = $logger;
}
public function isHandling(LogRecord $record): bool
{
return true;
}
public function handle(LogRecord $record): bool
{
$this->logger->debug('Log triggered while logging');
return false;
}
public function handleBatch(array $records): void
{
}
public function close(): void
{
}
}
class FiberSuspendHandler implements HandlerInterface
{
public function isHandling(LogRecord $record): bool
{
return true;
}
public function handle(LogRecord $record): bool
{
\Fiber::suspend();
return true;
}
public function handleBatch(array $records): void
{
}
public function close(): void
{
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/UtilsTest.php | tests/Monolog/UtilsTest.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 PHPUnit\Framework\Attributes\DataProvider;
class UtilsTest extends \PHPUnit_Framework_TestCase
{
#[DataProvider('provideObjects')]
public function testGetClass(string $expected, object $object)
{
$this->assertSame($expected, Utils::getClass($object));
}
public static function provideObjects()
{
return [
['stdClass', new \stdClass()],
['class@anonymous', new class {
}],
['stdClass@anonymous', new class extends \stdClass {
}],
];
}
#[DataProvider('providePathsToCanonicalize')]
public function testCanonicalizePath(string $expected, string $input)
{
$this->assertSame($expected, Utils::canonicalizePath($input));
}
public static function providePathsToCanonicalize()
{
return [
['/foo/bar', '/foo/bar'],
['file://'.getcwd().'/bla', 'file://bla'],
[getcwd().'/bla', 'bla'],
[getcwd().'/./bla', './bla'],
['file:///foo/bar', 'file:///foo/bar'],
['any://foo', 'any://foo'],
['\\\\network\path', '\\\\network\path'],
];
}
#[DataProvider('providesHandleJsonErrorFailure')]
public function testHandleJsonErrorFailure(int $code, string $msg)
{
$this->expectException('RuntimeException', $msg);
Utils::handleJsonError($code, 'faked');
}
public static function providesHandleJsonErrorFailure()
{
return [
'depth' => [JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'],
'state' => [JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'],
'ctrl' => [JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'],
'default' => [-1, 'Unknown error'],
];
}
/**
* @param mixed $in Input
* @param mixed $expect Expected output
* @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
*/
#[DataProvider('providesDetectAndCleanUtf8')]
public function testDetectAndCleanUtf8($in, $expect)
{
$reflMethod = new \ReflectionMethod(Utils::class, 'detectAndCleanUtf8');
$args = [&$in];
$reflMethod->invokeArgs(null, $args);
$this->assertSame($expect, $in);
}
public static function providesDetectAndCleanUtf8()
{
$obj = new \stdClass;
return [
'null' => [null, null],
'int' => [123, 123],
'float' => [123.45, 123.45],
'bool false' => [false, false],
'bool true' => [true, true],
'ascii string' => ['abcdef', 'abcdef'],
'latin9 string' => ["\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'],
'unicode string' => ['¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'],
'empty array' => [[], []],
'array' => [['abcdef'], ['abcdef']],
'object' => [$obj, $obj],
];
}
public static function provideIniValuesToConvertToBytes()
{
return [
['1', 1],
['2', 2],
['2.5', 2],
['2.9', 2],
['1B', false],
['1X', false],
['1K', 1024],
['1 K', 1024],
[' 5 M ', 5*1024*1024],
['1G', 1073741824],
['', false],
[null, false],
['A', false],
['AA', false],
['B', false],
['BB', false],
['G', false],
['GG', false],
['-1', -1],
['-123', -123],
['-1A', -1],
['-1B', -1],
['-123G', -123],
['-B', false],
['-A', false],
['-', false],
[true, false],
[false, false],
];
}
#[DataProvider('provideIniValuesToConvertToBytes')]
public function testExpandIniShorthandBytes(string|null|bool $input, int|false $expected)
{
$result = Utils::expandIniShorthandBytes($input);
$this->assertEquals($expected, $result);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/RegistryTest.php | tests/Monolog/RegistryTest.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 PHPUnit\Framework\Attributes\DataProvider;
class RegistryTest extends \PHPUnit\Framework\TestCase
{
protected function setUp(): void
{
Registry::clear();
}
/**
* @covers Monolog\Registry::hasLogger
*/
#[DataProvider('hasLoggerProvider')]
public function testHasLogger(array $loggersToAdd, array $loggersToCheck, array $expectedResult)
{
foreach ($loggersToAdd as $loggerToAdd) {
Registry::addLogger($loggerToAdd);
}
foreach ($loggersToCheck as $index => $loggerToCheck) {
$this->assertSame($expectedResult[$index], Registry::hasLogger($loggerToCheck));
}
}
public static function hasLoggerProvider()
{
$logger1 = new Logger('test1');
$logger2 = new Logger('test2');
$logger3 = new Logger('test3');
return [
// only instances
[
[$logger1],
[$logger1, $logger2],
[true, false],
],
// only names
[
[$logger1],
['test1', 'test2'],
[true, false],
],
// mixed case
[
[$logger1, $logger2],
['test1', $logger2, 'test3', $logger3],
[true, true, false, false],
],
];
}
/**
* @covers Monolog\Registry::clear
*/
public function testClearClears()
{
Registry::addLogger(new Logger('test1'), 'log');
Registry::clear();
$this->expectException('\InvalidArgumentException');
Registry::getInstance('log');
}
/**
* @covers Monolog\Registry::addLogger
* @covers Monolog\Registry::removeLogger
*/
#[DataProvider('removedLoggerProvider')]
public function testRemovesLogger($loggerToAdd, $remove)
{
Registry::addLogger($loggerToAdd);
Registry::removeLogger($remove);
$this->expectException('\InvalidArgumentException');
Registry::getInstance($loggerToAdd->getName());
}
public static function removedLoggerProvider()
{
$logger1 = new Logger('test1');
return [
[$logger1, $logger1],
[$logger1, 'test1'],
];
}
/**
* @covers Monolog\Registry::addLogger
* @covers Monolog\Registry::getInstance
* @covers Monolog\Registry::__callStatic
*/
public function testGetsSameLogger()
{
$logger1 = new Logger('test1');
$logger2 = new Logger('test2');
Registry::addLogger($logger1, 'test1');
Registry::addLogger($logger2);
$this->assertSame($logger1, Registry::getInstance('test1'));
$this->assertSame($logger2, Registry::test2());
}
/**
* @covers Monolog\Registry::getInstance
*/
public function testFailsOnNonExistentLogger()
{
$this->expectException(\InvalidArgumentException::class);
Registry::getInstance('test1');
}
/**
* @covers Monolog\Registry::addLogger
*/
public function testReplacesLogger()
{
$log1 = new Logger('test1');
$log2 = new Logger('test2');
Registry::addLogger($log1, 'log');
Registry::addLogger($log2, 'log', true);
$this->assertSame($log2, Registry::getInstance('log'));
}
/**
* @covers Monolog\Registry::addLogger
*/
public function testFailsOnUnspecifiedReplacement()
{
$log1 = new Logger('test1');
$log2 = new Logger('test2');
Registry::addLogger($log1, 'log');
$this->expectException(\InvalidArgumentException::class);
Registry::addLogger($log2, 'log');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/ProcessIdProcessorTest.php | tests/Monolog/Processor/ProcessIdProcessorTest.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;
class ProcessIdProcessorTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Processor\ProcessIdProcessor::__invoke
*/
public function testProcessor()
{
$processor = new ProcessIdProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('process_id', $record->extra);
$this->assertIsInt($record->extra['process_id']);
$this->assertGreaterThan(0, $record->extra['process_id']);
$this->assertEquals(getmypid(), $record->extra['process_id']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php | tests/Monolog/Processor/MemoryPeakUsageProcessorTest.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;
class MemoryPeakUsageProcessorTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Processor\MemoryPeakUsageProcessor::__invoke
* @covers Monolog\Processor\MemoryProcessor::formatBytes
*/
public function testProcessor()
{
$processor = new MemoryPeakUsageProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('memory_peak_usage', $record->extra);
$this->assertMatchesRegularExpression('#[0-9.]+ (M|K)?B$#', $record->extra['memory_peak_usage']);
}
/**
* @covers Monolog\Processor\MemoryPeakUsageProcessor::__invoke
* @covers Monolog\Processor\MemoryProcessor::formatBytes
*/
public function testProcessorWithoutFormatting()
{
$processor = new MemoryPeakUsageProcessor(true, false);
$record = $processor($this->getRecord());
$this->assertArrayHasKey('memory_peak_usage', $record->extra);
$this->assertIsInt($record->extra['memory_peak_usage']);
$this->assertGreaterThan(0, $record->extra['memory_peak_usage']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/IntrospectionProcessorTest.php | tests/Monolog/Processor/IntrospectionProcessorTest.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 Acme;
class Tester
{
public function test($handler, $record)
{
$handler->handle($record);
}
}
function tester($handler, $record)
{
$handler->handle($record);
}
namespace Monolog\Processor;
use Monolog\Level;
use Monolog\Handler\TestHandler;
class IntrospectionProcessorTest extends \Monolog\Test\MonologTestCase
{
public function getHandler()
{
$processor = new IntrospectionProcessor();
$handler = new TestHandler();
$handler->pushProcessor($processor);
return $handler;
}
public function testProcessorFromClass()
{
$handler = $this->getHandler();
$tester = new \Acme\Tester;
$tester->test($handler, $this->getRecord());
list($record) = $handler->getRecords();
$this->assertEquals(__FILE__, $record->extra['file']);
$this->assertEquals(18, $record->extra['line']);
$this->assertEquals('Acme\Tester', $record->extra['class']);
$this->assertEquals('test', $record->extra['function']);
}
public function testProcessorFromFunc()
{
$handler = $this->getHandler();
\Acme\tester($handler, $this->getRecord());
list($record) = $handler->getRecords();
$this->assertEquals(__FILE__, $record->extra['file']);
$this->assertEquals(24, $record->extra['line']);
$this->assertEquals(null, $record->extra['class']);
$this->assertEquals('Acme\tester', $record->extra['function']);
}
public function testLevelTooLow()
{
$input = $this->getRecord(Level::Debug);
$expected = clone $input;
$processor = new IntrospectionProcessor(Level::Critical);
$actual = $processor($input);
$this->assertEquals($expected, $actual);
}
public function testLevelEqual()
{
$input = $this->getRecord(Level::Critical);
$expected = clone $input;
$expected['extra'] = [
'file' => null,
'line' => null,
'class' => 'PHPUnit\Framework\TestCase',
'function' => 'runTest',
'callType' => '->',
];
$processor = new IntrospectionProcessor(Level::Critical);
$actual = $processor($input);
$this->assertEquals($expected, $actual);
}
public function testLevelHigher()
{
$input = $this->getRecord(Level::Emergency);
$expected = clone $input;
$expected['extra'] = [
'file' => null,
'line' => null,
'class' => 'PHPUnit\Framework\TestCase',
'function' => 'runTest',
'callType' => '->',
];
$processor = new IntrospectionProcessor(Level::Critical);
$actual = $processor($input);
$this->assertEquals($expected, $actual);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/UidProcessorTest.php | tests/Monolog/Processor/UidProcessorTest.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;
class UidProcessorTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Processor\UidProcessor::__invoke
*/
public function testProcessor()
{
$processor = new UidProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('uid', $record->extra);
}
public function testGetUid()
{
$processor = new UidProcessor(10);
$this->assertEquals(10, \strlen($processor->getUid()));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/GitProcessorTest.php | tests/Monolog/Processor/GitProcessorTest.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;
class GitProcessorTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Processor\GitProcessor::__invoke
*/
public function testProcessor()
{
$processor = new GitProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('git', $record->extra);
$this->assertTrue(!\is_array($record->extra['git']['branch']));
}
/**
* @covers Monolog\Processor\GitProcessor::__invoke
*/
public function testProcessorWithLevel()
{
$processor = new GitProcessor(Level::Error);
$record = $processor($this->getRecord());
$this->assertArrayNotHasKey('git', $record->extra);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/ClosureContextProcessorTest.php | tests/Monolog/Processor/ClosureContextProcessorTest.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 PHPUnit\Framework\Attributes\DataProvider;
class ClosureContextProcessorTest extends \Monolog\Test\MonologTestCase
{
public function testReplace()
{
$context = ['obj' => new \stdClass()];
$processor = new ClosureContextProcessor();
$record = $processor($this->getRecord(context: [fn () => $context]));
$this->assertSame($context, $record->context);
}
#[DataProvider('getContexts')]
public function testSkip(array $context)
{
$processor = new ClosureContextProcessor();
$record = $processor($this->getRecord(context: $context));
$this->assertSame($context, $record->context);
}
public function testClosureReturnsNotArray()
{
$object = new \stdClass();
$processor = new ClosureContextProcessor();
$record = $processor($this->getRecord(context: [fn () => $object]));
$this->assertSame([$object], $record->context);
}
public function testClosureThrows()
{
$exception = new \Exception('For test.');
$expected = [
'error_on_context_generation' => 'For test.',
'exception' => $exception,
];
$processor = new ClosureContextProcessor();
$record = $processor($this->getRecord(context: [fn () => throw $exception]));
$this->assertSame($expected, $record->context);
}
public static function getContexts(): iterable
{
yield [['foo']];
yield [['foo' => 'bar']];
yield [['foo', 'bar']];
yield [['foo', fn () => 'bar']];
yield [[fn () => 'foo', 'bar']];
yield [['foo' => fn () => 'bar']];
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/TagProcessorTest.php | tests/Monolog/Processor/TagProcessorTest.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;
class TagProcessorTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Processor\TagProcessor::__invoke
*/
public function testProcessor()
{
$tags = [1, 2, 3];
$processor = new TagProcessor($tags);
$record = $processor($this->getRecord());
$this->assertEquals($tags, $record->extra['tags']);
}
/**
* @covers Monolog\Processor\TagProcessor::__invoke
*/
public function testProcessorTagModification()
{
$tags = [1, 2, 3];
$processor = new TagProcessor($tags);
$record = $processor($this->getRecord());
$this->assertEquals($tags, $record->extra['tags']);
$processor->setTags(['a', 'b']);
$record = $processor($this->getRecord());
$this->assertEquals(['a', 'b'], $record->extra['tags']);
$processor->addTags(['a', 'c', 'foo' => 'bar']);
$record = $processor($this->getRecord());
$this->assertEquals(['a', 'b', 'a', 'c', 'foo' => 'bar'], $record->extra['tags']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/LoadAverageProcessorTest.php | tests/Monolog/Processor/LoadAverageProcessorTest.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;
class LoadAverageProcessorTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Processor\LoadAverageProcessor::__invoke
*/
public function testProcessor()
{
$processor = new LoadAverageProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('load_average', $record->extra);
$this->assertIsFloat($record->extra['load_average']);
}
/**
* @covers Monolog\Processor\LoadAverageProcessor::__invoke
*/
public function testProcessorWithInvalidAvgSystemLoad()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid average system load: `3`');
new LoadAverageProcessor(3);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/WebProcessorTest.php | tests/Monolog/Processor/WebProcessorTest.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;
class WebProcessorTest extends \Monolog\Test\MonologTestCase
{
public function testProcessor()
{
$server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'HTTP_REFERER' => 'D',
'SERVER_NAME' => 'F',
'UNIQUE_ID' => 'G',
];
$processor = new WebProcessor($server);
$record = $processor($this->getRecord());
$this->assertEquals($server['REQUEST_URI'], $record->extra['url']);
$this->assertEquals($server['REMOTE_ADDR'], $record->extra['ip']);
$this->assertEquals($server['REQUEST_METHOD'], $record->extra['http_method']);
$this->assertEquals($server['HTTP_REFERER'], $record->extra['referrer']);
$this->assertEquals($server['SERVER_NAME'], $record->extra['server']);
$this->assertEquals($server['UNIQUE_ID'], $record->extra['unique_id']);
}
public function testProcessorDoNothingIfNoRequestUri()
{
$server = [
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
];
$processor = new WebProcessor($server);
$record = $processor($this->getRecord());
$this->assertEmpty($record->extra);
}
public function testProcessorReturnNullIfNoHttpReferer()
{
$server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'SERVER_NAME' => 'F',
];
$processor = new WebProcessor($server);
$record = $processor($this->getRecord());
$this->assertNull($record->extra['referrer']);
}
public function testProcessorDoesNotAddUniqueIdIfNotPresent()
{
$server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'SERVER_NAME' => 'F',
];
$processor = new WebProcessor($server);
$record = $processor($this->getRecord());
$this->assertFalse(isset($record->extra['unique_id']));
}
public function testProcessorAddsOnlyRequestedExtraFields()
{
$server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'SERVER_NAME' => 'F',
];
$processor = new WebProcessor($server, ['url', 'http_method']);
$record = $processor($this->getRecord());
$this->assertSame(['url' => 'A', 'http_method' => 'C'], $record->extra);
}
public function testProcessorAddsOnlyRequestedExtraFieldsIncludingOptionalFields()
{
$server = [
'REQUEST_URI' => 'A',
'UNIQUE_ID' => 'X',
];
$processor = new WebProcessor($server, ['url']);
$record = $processor($this->getRecord());
$this->assertSame(['url' => 'A'], $record->extra);
}
public function testProcessorConfiguringOfExtraFields()
{
$server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'SERVER_NAME' => 'F',
];
$processor = new WebProcessor($server, ['url' => 'REMOTE_ADDR']);
$record = $processor($this->getRecord());
$this->assertSame(['url' => 'B'], $record->extra);
}
public function testInvalidData()
{
$this->expectException(\TypeError::class);
new WebProcessor(new \stdClass);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/HostnameProcessorTest.php | tests/Monolog/Processor/HostnameProcessorTest.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;
class HostnameProcessorTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Processor\HostnameProcessor::__invoke
*/
public function testProcessor()
{
$processor = new HostnameProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('hostname', $record->extra);
$this->assertIsString($record->extra['hostname']);
$this->assertNotEmpty($record->extra['hostname']);
$this->assertEquals(gethostname(), $record->extra['hostname']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/MemoryUsageProcessorTest.php | tests/Monolog/Processor/MemoryUsageProcessorTest.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;
class MemoryUsageProcessorTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Processor\MemoryUsageProcessor::__invoke
* @covers Monolog\Processor\MemoryProcessor::formatBytes
*/
public function testProcessor()
{
$processor = new MemoryUsageProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('memory_usage', $record->extra);
$this->assertMatchesRegularExpression('#[0-9.]+ (M|K)?B$#', $record->extra['memory_usage']);
}
/**
* @covers Monolog\Processor\MemoryUsageProcessor::__invoke
* @covers Monolog\Processor\MemoryProcessor::formatBytes
*/
public function testProcessorWithoutFormatting()
{
$processor = new MemoryUsageProcessor(true, false);
$record = $processor($this->getRecord());
$this->assertArrayHasKey('memory_usage', $record->extra);
$this->assertIsInt($record->extra['memory_usage']);
$this->assertGreaterThan(0, $record->extra['memory_usage']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/MercurialProcessorTest.php | tests/Monolog/Processor/MercurialProcessorTest.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;
class MercurialProcessorTest extends \Monolog\Test\MonologTestCase
{
private string $oldCwd;
private string $testDir;
protected function setUp(): void
{
parent::setUp();
$this->oldCwd = getcwd();
$this->testDir = sys_get_temp_dir().'/monolog-processor-mercurial-test';
mkdir($this->testDir, recursive: true);
chdir($this->testDir);
}
protected function tearDown(): void
{
parent::tearDown();
chdir($this->oldCwd);
if (!file_exists($this->testDir)) {
return;
}
$items = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($this->testDir, \RecursiveDirectoryIterator::SKIP_DOTS),
\RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($items as $item) {
$item->isDir() ? rmdir((string) $item) : unlink((string) $item);
}
rmdir($this->testDir);
}
/**
* @covers Monolog\Processor\MercurialProcessor::__invoke
*/
public function testProcessor()
{
if (\defined('PHP_WINDOWS_VERSION_BUILD')) {
exec("where hg 2>NUL", $output, $result);
} else {
exec("which hg 2>/dev/null >/dev/null", $output, $result);
}
if ($result != 0) {
$this->markTestSkipped('hg is missing');
return;
}
exec('hg init');
exec('hg branch default');
touch('test.txt');
exec('hg add test.txt');
exec('hg commit -u foo -m "initial commit"');
$processor = new MercurialProcessor();
$record = $processor($this->getRecord());
$this->assertArrayHasKey('hg', $record->extra);
$this->assertSame('default', $record->extra['hg']['branch']);
$this->assertSame('0', $record->extra['hg']['revision']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Processor/PsrLogMessageProcessorTest.php | tests/Monolog/Processor/PsrLogMessageProcessorTest.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 PHPUnit\Framework\Attributes\DataProvider;
class PsrLogMessageProcessorTest extends \Monolog\Test\MonologTestCase
{
#[DataProvider('getPairs')]
public function testReplacement($val, $expected)
{
$proc = new PsrLogMessageProcessor;
$message = $proc($this->getRecord(message: '{foo}', context: ['foo' => $val]));
$this->assertEquals($expected, $message['message']);
$this->assertSame(['foo' => $val], $message['context']);
}
public function testReplacementWithContextRemoval()
{
$proc = new PsrLogMessageProcessor($dateFormat = null, $removeUsedContextFields = true);
$message = $proc($this->getRecord(message: '{foo}', context: ['foo' => 'bar', 'lorem' => 'ipsum']));
$this->assertSame('bar', $message['message']);
$this->assertSame(['lorem' => 'ipsum'], $message['context']);
}
public function testCustomDateFormat()
{
$format = "Y-m-d";
$date = new \DateTime();
$proc = new PsrLogMessageProcessor($format);
$message = $proc($this->getRecord(message: '{foo}', context: ['foo' => $date]));
$this->assertEquals($date->format($format), $message['message']);
$this->assertSame(['foo' => $date], $message['context']);
}
public static function getPairs()
{
$date = new \DateTime();
return [
['foo', 'foo'],
['3', '3'],
[3, '3'],
[null, ''],
[true, '1'],
[false, ''],
[$date, $date->format(PsrLogMessageProcessor::SIMPLE_DATE)],
[new \stdClass, '[object stdClass]'],
[[], 'array[]'],
[[], 'array[]'],
[[1, 2, 3], 'array[1,2,3]'],
[['foo' => 'bar'], 'array{"foo":"bar"}'],
[stream_context_create(), '[resource]'],
[Level::Info, Level::Info->value],
];
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/JsonFormatterTest.php | tests/Monolog/Formatter/JsonFormatterTest.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 Exception;
use Monolog\Level;
use Monolog\LogRecord;
use JsonSerializable;
use Monolog\Test\MonologTestCase;
class JsonFormatterTest extends MonologTestCase
{
/**
* @covers Monolog\Formatter\JsonFormatter::__construct
* @covers Monolog\Formatter\JsonFormatter::getBatchMode
* @covers Monolog\Formatter\JsonFormatter::isAppendingNewlines
*/
public function testConstruct()
{
$formatter = new JsonFormatter();
$this->assertEquals(JsonFormatter::BATCH_MODE_JSON, $formatter->getBatchMode());
$this->assertEquals(true, $formatter->isAppendingNewlines());
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES, false);
$this->assertEquals(JsonFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode());
$this->assertEquals(false, $formatter->isAppendingNewlines());
}
/**
* @covers Monolog\Formatter\JsonFormatter::format
*/
public function testFormat()
{
$formatter = new JsonFormatter();
$record = $this->getRecord();
$this->assertEquals(json_encode($record->toArray(), JSON_FORCE_OBJECT)."\n", $formatter->format($record));
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
$record = $this->getRecord();
$this->assertEquals('{"message":"test","context":{},"level":300,"level_name":"WARNING","channel":"test","datetime":"'.$record->datetime->format('Y-m-d\TH:i:s.uP').'","extra":{}}', $formatter->format($record));
}
/**
* @covers Monolog\Formatter\JsonFormatter::format
*/
public function testFormatWithPrettyPrint()
{
$formatter = new JsonFormatter();
$formatter->setJsonPrettyPrint(true);
$record = $this->getRecord();
$this->assertEquals(json_encode($record->toArray(), JSON_PRETTY_PRINT | JSON_FORCE_OBJECT)."\n", $formatter->format($record));
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
$formatter->setJsonPrettyPrint(true);
$record = $this->getRecord();
$this->assertEquals(
'{
"message": "test",
"context": {},
"level": 300,
"level_name": "WARNING",
"channel": "test",
"datetime": "'.$record->datetime->format('Y-m-d\TH:i:s.uP').'",
"extra": {}
}',
$formatter->format($record)
);
$formatter->setJsonPrettyPrint(false);
$record = $this->getRecord();
$this->assertEquals('{"message":"test","context":{},"level":300,"level_name":"WARNING","channel":"test","datetime":"'.$record->datetime->format('Y-m-d\TH:i:s.uP').'","extra":{}}', $formatter->format($record));
}
/**
* @covers Monolog\Formatter\JsonFormatter::formatBatch
* @covers Monolog\Formatter\JsonFormatter::formatBatchJson
*/
public function testFormatBatch()
{
$formatter = new JsonFormatter();
$records = [
$this->getRecord(Level::Warning),
$this->getRecord(Level::Debug),
];
$expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records);
$this->assertEquals('['.implode(',', $expected).']', $formatter->formatBatch($records));
}
/**
* @covers Monolog\Formatter\JsonFormatter::formatBatch
* @covers Monolog\Formatter\JsonFormatter::formatBatchNewlines
*/
public function testFormatBatchNewlines()
{
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
$records = [
$this->getRecord(Level::Warning),
$this->getRecord(Level::Debug),
];
$expected = array_map(fn (LogRecord $record) => json_encode($record->toArray(), JSON_FORCE_OBJECT), $records);
$this->assertEquals(implode("\n", $expected), $formatter->formatBatch($records));
}
public function testDefFormatWithException()
{
$formatter = new JsonFormatter();
$exception = new \RuntimeException('Foo');
$formattedException = $this->formatException($exception);
$message = $this->formatRecordWithExceptionInContext($formatter, $exception);
$this->assertContextContainsFormattedException($formattedException, $message);
}
public function testBasePathWithException(): void
{
$formatter = new JsonFormatter();
$formatter->setBasePath(\dirname(\dirname(\dirname(__DIR__))));
$exception = new \RuntimeException('Foo');
$message = $this->formatRecordWithExceptionInContext($formatter, $exception);
$parsed = json_decode($message, true);
self::assertSame('tests/Monolog/Formatter/JsonFormatterTest.php:' . (__LINE__ - 5), $parsed['context']['exception']['file']);
}
public function testDefFormatWithPreviousException()
{
$formatter = new JsonFormatter();
$exception = new \RuntimeException('Foo', 0, new \LogicException('Wut?'));
$formattedPrevException = $this->formatException($exception->getPrevious());
$formattedException = $this->formatException($exception, $formattedPrevException);
$message = $this->formatRecordWithExceptionInContext($formatter, $exception);
$this->assertContextContainsFormattedException($formattedException, $message);
}
public function testDefFormatWithThrowable()
{
$formatter = new JsonFormatter();
$throwable = new \Error('Foo');
$formattedThrowable = $this->formatException($throwable);
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertContextContainsFormattedException($formattedThrowable, $message);
}
public function testMaxNormalizeDepth()
{
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
$formatter->setMaxNormalizeDepth(1);
$throwable = new \Error('Foo');
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertContextContainsFormattedException('"Over 1 levels deep, aborting normalization"', $message);
}
public function testMaxNormalizeItemCountWith0ItemsMax()
{
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
$formatter->setMaxNormalizeDepth(9);
$formatter->setMaxNormalizeItemCount(0);
$throwable = new \Error('Foo');
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertEquals(
'{"...":"Over 0 items (7 total), aborting normalization"}'."\n",
$message
);
}
public function testMaxNormalizeItemCountWith2ItemsMax()
{
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true);
$formatter->setMaxNormalizeDepth(9);
$formatter->setMaxNormalizeItemCount(2);
$throwable = new \Error('Foo');
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertEquals(
'{"message":"foobar","context":{"exception":{"class":"Error","message":"Foo","code":0,"file":"'.__FILE__.':'.(__LINE__ - 5).'"}},"...":"Over 2 items (7 total), aborting normalization"}'."\n",
$message
);
}
public function testDefFormatWithResource()
{
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
$record = $this->getRecord(
context: ['field_resource' => opendir(__DIR__)],
);
$this->assertEquals('{"message":"test","context":{"field_resource":"[resource(stream)]"},"level":300,"level_name":"WARNING","channel":"test","datetime":"'.$record->datetime->format('Y-m-d\TH:i:s.uP').'","extra":{}}', $formatter->format($record));
}
/**
* @internal param string $exception
*/
private function assertContextContainsFormattedException(string $expected, string $actual)
{
$this->assertEquals(
'{"message":"foobar","context":{"exception":'.$expected.'},"level":500,"level_name":"CRITICAL","channel":"core","datetime":"2022-02-22T00:00:00+00:00","extra":{}}'."\n",
$actual
);
}
private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception): string
{
$message = $formatter->format($this->getRecord(
Level::Critical,
'foobar',
channel: 'core',
context: ['exception' => $exception],
datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
));
return $message;
}
/**
* @param \Exception|\Throwable $exception
*/
private function formatExceptionFilePathWithLine($exception): string
{
$options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
$path = substr(json_encode($exception->getFile(), $options), 1, -1);
return $path . ':' . $exception->getLine();
}
/**
* @param \Exception|\Throwable $exception
*/
private function formatException($exception, ?string $previous = null): string
{
$formattedException =
'{"class":"' . \get_class($exception) .
'","message":"' . $exception->getMessage() .
'","code":' . $exception->getCode() .
',"file":"' . $this->formatExceptionFilePathWithLine($exception) .
($previous ? '","previous":' . $previous : '"') .
'}';
return $formattedException;
}
public function testNormalizeHandleLargeArraysWithExactly1000Items()
{
$formatter = new NormalizerFormatter();
$largeArray = range(1, 1000);
$res = $formatter->format($this->getRecord(
Level::Critical,
'bar',
channel: 'test',
context: [$largeArray],
));
$this->assertCount(1000, $res['context'][0]);
$this->assertArrayNotHasKey('...', $res['context'][0]);
}
public function testNormalizeHandleLargeArrays()
{
$formatter = new NormalizerFormatter();
$largeArray = range(1, 2000);
$res = $formatter->format($this->getRecord(
Level::Critical,
'bar',
channel: 'test',
context: [$largeArray],
));
$this->assertCount(1001, $res['context'][0]);
$this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
}
public function testCanNormalizeIncompleteObject(): void
{
$serialized = "O:17:\"Monolog\TestClass\":1:{s:23:\"\x00Monolog\TestClass\x00name\";s:4:\"test\";}";
$object = unserialize($serialized);
$formatter = new JsonFormatter();
$record = $this->getRecord(context: ['object' => $object], datetime: new \DateTimeImmutable('2022-02-22 00:00:00'));
$result = $formatter->format($record);
self::assertSame('{"message":"test","context":{"object":{"__PHP_Incomplete_Class_Name":"Monolog\\\\TestClass"}},"level":300,"level_name":"WARNING","channel":"test","datetime":"2022-02-22T00:00:00+00:00","extra":{}}'."\n", $result);
}
public function testEmptyContextAndExtraFieldsCanBeIgnored()
{
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, true, true);
$record = $formatter->format($this->getRecord(
Level::Debug,
'Testing',
channel: 'test',
datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
));
$this->assertSame(
'{"message":"Testing","level":100,"level_name":"DEBUG","channel":"test","datetime":"2022-02-22T00:00:00+00:00"}'."\n",
$record
);
}
public function testFormatObjects()
{
$formatter = new JsonFormatter();
$record = $formatter->format($this->getRecord(
Level::Debug,
'Testing',
channel: 'test',
datetime: new \DateTimeImmutable('2022-02-22 00:00:00'),
context: [
'public' => new TestJsonNormPublic,
'private' => new TestJsonNormPrivate,
'withToStringAndJson' => new TestJsonNormWithToStringAndJson,
'withToString' => new TestJsonNormWithToString,
],
));
$this->assertSame(
'{"message":"Testing","context":{"public":{"foo":"fooValue"},"private":{},"withToStringAndJson":["json serialized"],"withToString":"stringified"},"level":100,"level_name":"DEBUG","channel":"test","datetime":"2022-02-22T00:00:00+00:00","extra":{}}'."\n",
$record
);
}
public function testNormalizeHandleExceptionInToString(): void
{
$formatter = new JsonFormatter();
$res = $formatter->format($this->getRecord(
Level::Critical,
'bar',
datetime: new \DateTimeImmutable('2025-05-19 00:00:00'),
channel: 'test',
context: ['object' => new TestJsonNormWithFailingToString],
));
$this->assertSame(
'{"message":"bar","context":{"object":"Monolog\\\\Formatter\\\\TestJsonNormWithFailingToString"},"level":500,"level_name":"CRITICAL","channel":"test","datetime":"2025-05-19T00:00:00+00:00","extra":{}}'."\n",
$res,
);
}
}
class TestJsonNormPublic
{
public $foo = 'fooValue';
}
class TestJsonNormPrivate
{
private $foo = 'fooValue';
}
class TestJsonNormWithToStringAndJson implements JsonSerializable
{
public function jsonSerialize(): mixed
{
return ['json serialized'];
}
public function __toString()
{
return 'SHOULD NOT SHOW UP';
}
}
class TestJsonNormWithToString
{
public function __toString()
{
return 'stringified';
}
}
class TestJsonNormWithFailingToString
{
public function __toString()
{
throw new Exception('Whatever');
}
} | php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/SyslogFormatterTest.php | tests/Monolog/Formatter/SyslogFormatterTest.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 DateTimeImmutable;
use Monolog\Level;
use Monolog\LogRecord;
use PHPUnit\Framework\Attributes\DataProvider;
class SyslogFormatterTest extends \Monolog\Test\MonologTestCase
{
/**
* @param mixed[] $context
* @param mixed[] $extra
*/
#[DataProvider('formatDataProvider')]
public function testFormat(
string $expected,
DateTimeImmutable $dateTime,
string $channel,
Level $level,
string $message,
?string $appName = null,
array $context = [],
array $extra = []
): void {
if ($appName !== null) {
$formatter = new SyslogFormatter($appName);
} else {
$formatter = new SyslogFormatter();
}
$record = new LogRecord(
datetime: $dateTime,
channel: $channel,
level: $level,
message: $message,
context: $context,
extra: $extra
);
$message = $formatter->format($record);
$this->assertEquals($expected, $message);
}
/**
* @return mixed[]
*/
public static function formatDataProvider(): array
{
return [
'error' => [
'expected' => "<11>1 1970-01-01T00:00:00.000000+00:00 " . gethostname() . " - " . getmypid() ." meh - ERROR: log \n",
'dateTime' => new DateTimeImmutable("@0"),
'channel' => 'meh',
'level' => Level::Error,
'message' => 'log',
],
'info' => [
'expected' => "<11>1 1970-01-01T00:00:00.000000+00:00 " . gethostname() . " - " . getmypid() ." meh - ERROR: log \n",
'dateTime' => new DateTimeImmutable("@0"),
'channel' => 'meh',
'level' => Level::Error,
'message' => 'log',
],
'with app name' => [
'expected' => "<11>1 1970-01-01T00:00:00.000000+00:00 " . gethostname() . " my-app " . getmypid() ." meh - ERROR: log \n",
'dateTime' => new DateTimeImmutable("@0"),
'channel' => 'meh',
'level' => Level::Error,
'message' => 'log',
'appName' => 'my-app',
],
'with context' => [
'expected' => "<11>1 1970-01-01T00:00:00.000000+00:00 " . gethostname() . " - " . getmypid() ." meh - ERROR: log {\"additional-context\":\"test\"} \n",
'dateTime' => new DateTimeImmutable("@0"),
'channel' => 'meh',
'level' => Level::Error,
'message' => 'log',
'appName' => null,
'context' => ['additional-context' => 'test'],
],
'with extra' => [
'expected' => "<11>1 1970-01-01T00:00:00.000000+00:00 " . gethostname() . " - " . getmypid() ." meh - ERROR: log {\"userId\":1}\n",
'dateTime' => new DateTimeImmutable("@0"),
'channel' => 'meh',
'level' => Level::Error,
'message' => 'log',
'appName' => null,
'context' => [],
'extra' => ['userId' => 1],
],
];
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/WildfireFormatterTest.php | tests/Monolog/Formatter/WildfireFormatterTest.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;
class WildfireFormatterTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Formatter\WildfireFormatter::format
*/
public function testDefaultFormat()
{
$wildfire = new WildfireFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
extra: ['ip' => '127.0.0.1'],
);
$message = $wildfire->format($record);
$this->assertEquals(
'125|[{"Type":"ERROR","File":"","Line":"","Label":"meh"},'
.'{"message":"log","context":{"from":"logger"},"extra":{"ip":"127.0.0.1"}}]|',
$message
);
}
/**
* @covers Monolog\Formatter\WildfireFormatter::format
*/
public function testFormatWithFileAndLine()
{
$wildfire = new WildfireFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
extra: ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14],
);
$message = $wildfire->format($record);
$this->assertEquals(
'129|[{"Type":"ERROR","File":"test","Line":14,"Label":"meh"},'
.'{"message":"log","context":{"from":"logger"},"extra":{"ip":"127.0.0.1"}}]|',
$message
);
}
/**
* @covers Monolog\Formatter\WildfireFormatter::format
*/
public function testFormatWithoutContext()
{
$wildfire = new WildfireFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
);
$message = $wildfire->format($record);
$this->assertEquals(
'58|[{"Type":"ERROR","File":"","Line":"","Label":"meh"},"log"]|',
$message
);
}
/**
* @covers Monolog\Formatter\WildfireFormatter::formatBatch
*/
public function testBatchFormatThrowException()
{
$this->expectException(\BadMethodCallException::class);
$wildfire = new WildfireFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
);
$wildfire->formatBatch([$record]);
}
/**
* @covers Monolog\Formatter\WildfireFormatter::format
*/
public function testTableFormat()
{
$wildfire = new WildfireFormatter();
$record = $this->getRecord(
Level::Error,
'table-message',
channel: 'table-channel',
context: [
'table' => [
['col1', 'col2', 'col3'],
['val1', 'val2', 'val3'],
['foo1', 'foo2', 'foo3'],
['bar1', 'bar2', 'bar3'],
],
],
);
$message = $wildfire->format($record);
$this->assertEquals(
'171|[{"Type":"TABLE","File":"","Line":"","Label":"table-channel: table-message"},[["col1","col2","col3"],["val1","val2","val3"],["foo1","foo2","foo3"],["bar1","bar2","bar3"]]]|',
$message
);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/FlowdockFormatterTest.php | tests/Monolog/Formatter/FlowdockFormatterTest.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\Test\MonologTestCase;
class FlowdockFormatterTest extends MonologTestCase
{
/**
* @covers Monolog\Formatter\FlowdockFormatter::format
*/
public function testFormat()
{
$formatter = new FlowdockFormatter('test_source', 'source@test.com');
$record = $this->getRecord();
$expected = [
'source' => 'test_source',
'from_address' => 'source@test.com',
'subject' => 'in test_source: WARNING - test',
'content' => 'test',
'tags' => ['#logs', '#warning', '#test'],
'project' => 'test_source',
];
$formatted = $formatter->format($record);
$this->assertEquals($expected, $formatted);
}
/**
* @ covers Monolog\Formatter\FlowdockFormatter::formatBatch
*/
public function testFormatBatch()
{
$formatter = new FlowdockFormatter('test_source', 'source@test.com');
$records = [
$this->getRecord(Level::Warning),
$this->getRecord(Level::Debug),
];
$formatted = $formatter->formatBatch($records);
$this->assertArrayHasKey('from_address', $formatted[0]);
$this->assertArrayHasKey('from_address', $formatted[1]);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/ScalarFormatterTest.php | tests/Monolog/Formatter/ScalarFormatterTest.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;
class ScalarFormatterTest extends \Monolog\Test\MonologTestCase
{
private ScalarFormatter $formatter;
public function setUp(): void
{
$this->formatter = new ScalarFormatter();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->formatter);
}
public function buildTrace(\Exception $e)
{
$data = [];
$trace = $e->getTrace();
foreach ($trace as $frame) {
if (isset($frame['file'])) {
$data[] = $frame['file'].':'.$frame['line'];
}
}
return $data;
}
public function encodeJson($data)
{
return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
public function testFormat()
{
$exception = new \Exception('foo');
$formatted = $this->formatter->format($this->getRecord(context: [
'foo' => 'string',
'bar' => 1,
'baz' => false,
'bam' => [1, 2, 3],
'bat' => ['foo' => 'bar'],
'bap' => $dt = new JsonSerializableDateTimeImmutable(true),
'ban' => $exception,
]));
$this->assertSame($this->encodeJson([
'foo' => 'string',
'bar' => 1,
'baz' => false,
'bam' => [1, 2, 3],
'bat' => ['foo' => 'bar'],
'bap' => (string) $dt,
'ban' => [
'class' => \get_class($exception),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(),
'trace' => $this->buildTrace($exception),
],
]), $formatted['context']);
}
public function testFormatWithErrorContext()
{
$context = ['file' => 'foo', 'line' => 1];
$formatted = $this->formatter->format($this->getRecord(
context: $context,
));
$this->assertSame($this->encodeJson($context), $formatted['context']);
}
public function testFormatWithExceptionContext()
{
$exception = new \Exception('foo');
$formatted = $this->formatter->format($this->getRecord(context: [
'exception' => $exception,
]));
$this->assertSame($this->encodeJson([
'exception' => [
'class' => \get_class($exception),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(),
'trace' => $this->buildTrace($exception),
],
]), $formatted['context']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/FluentdFormatterTest.php | tests/Monolog/Formatter/FluentdFormatterTest.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\Test\MonologTestCase;
class FluentdFormatterTest extends MonologTestCase
{
/**
* @covers Monolog\Formatter\FluentdFormatter::__construct
* @covers Monolog\Formatter\FluentdFormatter::isUsingLevelsInTag
*/
public function testConstruct()
{
$formatter = new FluentdFormatter();
$this->assertEquals(false, $formatter->isUsingLevelsInTag());
$formatter = new FluentdFormatter(false);
$this->assertEquals(false, $formatter->isUsingLevelsInTag());
$formatter = new FluentdFormatter(true);
$this->assertEquals(true, $formatter->isUsingLevelsInTag());
}
/**
* @covers Monolog\Formatter\FluentdFormatter::format
*/
public function testFormat()
{
$record = $this->getRecord(Level::Warning, datetime: new \DateTimeImmutable("@0"));
$formatter = new FluentdFormatter();
$this->assertEquals(
'["test",0,{"message":"test","context":[],"extra":[],"level":300,"level_name":"WARNING"}]',
$formatter->format($record)
);
}
/**
* @covers Monolog\Formatter\FluentdFormatter::format
*/
public function testFormatWithTag()
{
$record = $this->getRecord(Level::Error, datetime: new \DateTimeImmutable("@0"));
$formatter = new FluentdFormatter(true);
$this->assertEquals(
'["test.error",0,{"message":"test","context":[],"extra":[]}]',
$formatter->format($record)
);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/ElasticsearchFormatterTest.php | tests/Monolog/Formatter/ElasticsearchFormatterTest.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\Test\MonologTestCase;
class ElasticsearchFormatterTest extends MonologTestCase
{
/**
* @covers Monolog\Formatter\ElasticsearchFormatter::__construct
* @covers Monolog\Formatter\ElasticsearchFormatter::format
* @covers Monolog\Formatter\ElasticsearchFormatter::getDocument
*/
public function testFormat()
{
// Test log message
$msg = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['foo' => 7, 'bar', 'class' => new \stdClass],
datetime: new \DateTimeImmutable("@0"),
);
// Expected values
$expected = $msg->toArray();
$expected['datetime'] = '1970-01-01T00:00:00+00:00';
$expected['context'] = [
'class' => ['stdClass' => []],
'foo' => 7,
0 => 'bar',
];
// Format log message
$formatter = new ElasticsearchFormatter('my_index', 'doc_type');
$doc = $formatter->format($msg);
$this->assertIsArray($doc);
// Record parameters
$this->assertEquals('my_index', $doc['_index']);
$this->assertEquals('doc_type', $doc['_type']);
// Record data values
foreach (array_keys($expected) as $key) {
$this->assertEquals($expected[$key], $doc[$key]);
}
}
/**
* @covers Monolog\Formatter\ElasticsearchFormatter::getIndex
* @covers Monolog\Formatter\ElasticsearchFormatter::getType
*/
public function testGetters()
{
$formatter = new ElasticsearchFormatter('my_index', 'doc_type');
$this->assertEquals('my_index', $formatter->getIndex());
$this->assertEquals('doc_type', $formatter->getType());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/NormalizerFormatterTest.php | tests/Monolog/Formatter/NormalizerFormatterTest.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;
/**
* @covers Monolog\Formatter\NormalizerFormatter
*/
class NormalizerFormatterTest extends \Monolog\Test\MonologTestCase
{
public function testFormat()
{
$formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->format($this->getRecord(
Level::Error,
'foo',
channel: 'meh',
extra: ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
context: [
'foo' => 'bar',
'baz' => 'qux',
'inf' => INF,
'-inf' => -INF,
'nan' => acos(4),
],
));
$this->assertEquals([
'level_name' => Level::Error->getName(),
'level' => Level::Error->value,
'channel' => 'meh',
'message' => 'foo',
'datetime' => date('Y-m-d'),
'extra' => [
'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]],
'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'],
'baz' => [],
'res' => '[resource(stream)]',
],
'context' => [
'foo' => 'bar',
'baz' => 'qux',
'inf' => 'INF',
'-inf' => '-INF',
'nan' => 'NaN',
],
], $formatted);
}
public function testFormatExceptions()
{
$formatter = new NormalizerFormatter('Y-m-d');
$e = new \LogicException('bar');
$e2 = new \RuntimeException('foo', 0, $e);
$formatted = $formatter->normalizeValue([
'exception' => $e2,
]);
$this->assertGreaterThan(5, \count($formatted['exception']['trace']));
$this->assertTrue(isset($formatted['exception']['previous']));
unset($formatted['exception']['trace'], $formatted['exception']['previous']);
$this->assertEquals([
'exception' => [
'class' => \get_class($e2),
'message' => $e2->getMessage(),
'code' => $e2->getCode(),
'file' => $e2->getFile().':'.$e2->getLine(),
],
], $formatted);
}
public function testFormatExceptionWithBasePath(): void
{
$formatter = new NormalizerFormatter('Y-m-d');
$formatter->setBasePath(\dirname(\dirname(\dirname(__DIR__))));
$e = new \LogicException('bar');
$formatted = $formatter->normalizeValue([
'exception' => $e,
]);
self::assertSame('tests/Monolog/Formatter/NormalizerFormatterTest.php:' . (__LINE__ - 5), $formatted['exception']['file']);
self::assertStringStartsWith('vendor/phpunit/phpunit/src/Framework/TestCase.php:', $formatted['exception']['trace'][0]);
self::assertStringStartsWith('vendor/phpunit/phpunit/src/Framework/TestCase.php:', $formatted['exception']['trace'][1]);
}
public function testFormatSoapFaultException()
{
if (!class_exists('SoapFault')) {
$this->markTestSkipped('Requires the soap extension');
}
$formatter = new NormalizerFormatter('Y-m-d');
$e = new \SoapFault('foo', 'bar', 'hello', 'world');
$formatted = $formatter->normalizeValue([
'exception' => $e,
]);
unset($formatted['exception']['trace']);
$this->assertEquals([
'exception' => [
'class' => 'SoapFault',
'message' => 'bar',
'code' => 0,
'file' => $e->getFile().':'.$e->getLine(),
'faultcode' => 'foo',
'faultactor' => 'hello',
'detail' => 'world',
],
], $formatted);
$formatter = new NormalizerFormatter('Y-m-d');
$e = new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world']);
$formatted = $formatter->normalizeValue([
'exception' => $e,
]);
unset($formatted['exception']['trace']);
$this->assertEquals([
'exception' => [
'class' => 'SoapFault',
'message' => 'bar',
'code' => 0,
'file' => $e->getFile().':'.$e->getLine(),
'faultcode' => 'foo',
'faultactor' => 'hello',
'detail' => '{"bar":{"biz":"baz"},"foo":"world"}',
],
], $formatted);
}
public function testFormatToStringExceptionHandle()
{
$formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->format($this->getRecord(context: [
'myObject' => new TestToStringError(),
]));
$this->assertEquals(
[
'level_name' => Level::Warning->getName(),
'level' => Level::Warning->value,
'channel' => 'test',
'message' => 'test',
'context' => [
'myObject' => [
TestToStringError::class => [],
],
],
'datetime' => date('Y-m-d'),
'extra' => [],
],
$formatted
);
}
public function testBatchFormat()
{
$formatter = new NormalizerFormatter('Y-m-d');
$formatted = $formatter->formatBatch([
$this->getRecord(Level::Critical, 'bar', channel: 'test'),
$this->getRecord(Level::Warning, 'foo', channel: 'log'),
]);
$this->assertEquals([
[
'level_name' => Level::Critical->getName(),
'level' => Level::Critical->value,
'channel' => 'test',
'message' => 'bar',
'context' => [],
'datetime' => date('Y-m-d'),
'extra' => [],
],
[
'level_name' => Level::Warning->getName(),
'level' => Level::Warning->value,
'channel' => 'log',
'message' => 'foo',
'context' => [],
'datetime' => date('Y-m-d'),
'extra' => [],
],
], $formatted);
}
/**
* Test issue #137
*/
public function testIgnoresRecursiveObjectReferences()
{
// set up the recursion
$foo = new \stdClass();
$bar = new \stdClass();
$foo->bar = $bar;
$bar->foo = $foo;
// set an error handler to assert that the error is not raised anymore
$that = $this;
set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
if (error_reporting() & $level) {
restore_error_handler();
$that->fail("$message should not be raised");
}
return true;
});
$formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson');
$res = $reflMethod->invoke($formatter, [$foo, $bar], true);
restore_error_handler();
$this->assertEquals('[{"bar":{"foo":null}},{"foo":{"bar":null}}]', $res);
}
public function testCanNormalizeReferences()
{
$formatter = new NormalizerFormatter();
$x = ['foo' => 'bar'];
$y = ['x' => &$x];
$x['y'] = &$y;
$formatter->normalizeValue($y);
}
public function testToJsonIgnoresInvalidTypes()
{
// set up the invalid data
$resource = fopen(__FILE__, 'r');
// set an error handler to assert that the error is not raised anymore
$that = $this;
set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
if (error_reporting() & $level) {
restore_error_handler();
$that->fail("$message should not be raised");
}
return true;
});
$formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson');
$res = $reflMethod->invoke($formatter, [$resource], true);
restore_error_handler();
$this->assertEquals('[null]', $res);
}
public function testNormalizeHandleLargeArraysWithExactly1000Items()
{
$formatter = new NormalizerFormatter();
$largeArray = range(1, 1000);
$res = $formatter->format($this->getRecord(
Level::Critical,
'bar',
channel: 'test',
context: [$largeArray],
));
$this->assertCount(1000, $res['context'][0]);
$this->assertArrayNotHasKey('...', $res['context'][0]);
}
public function testNormalizeHandleLargeArrays()
{
$formatter = new NormalizerFormatter();
$largeArray = range(1, 2000);
$res = $formatter->format($this->getRecord(
Level::Critical,
'bar',
channel: 'test',
context: [$largeArray],
));
$this->assertCount(1001, $res['context'][0]);
$this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
}
public function testIgnoresInvalidEncoding()
{
$formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson');
// send an invalid unicode sequence as a object that can't be cleaned
$record = new \stdClass;
$record->message = "\xB1\x31";
$this->assertsame('{"message":"�1"}', $reflMethod->invoke($formatter, $record));
}
public function testConvertsInvalidEncodingAsLatin9()
{
$formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson');
$res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
$this->assertSame('{"message":"��������"}', $res);
}
public function testMaxNormalizeDepth()
{
$formatter = new NormalizerFormatter();
$formatter->setMaxNormalizeDepth(1);
$throwable = new \Error('Foo');
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertEquals(
'Over 1 levels deep, aborting normalization',
$message['context']['exception']
);
}
public function testMaxNormalizeItemCountWith0ItemsMax()
{
$formatter = new NormalizerFormatter();
$formatter->setMaxNormalizeDepth(9);
$formatter->setMaxNormalizeItemCount(0);
$throwable = new \Error('Foo');
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
$this->assertEquals(
["..." => "Over 0 items (7 total), aborting normalization"],
$message
);
}
public function testMaxNormalizeItemCountWith2ItemsMax()
{
$formatter = new NormalizerFormatter();
$formatter->setMaxNormalizeDepth(9);
$formatter->setMaxNormalizeItemCount(2);
$throwable = new \Error('Foo');
$message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
unset($message['context']['exception']['trace']);
unset($message['context']['exception']['file']);
$this->assertEquals(
[
"message" => "foobar",
"context" => ['exception' => [
'class' => 'Error',
'message' => 'Foo',
'code' => 0,
]],
"..." => "Over 2 items (7 total), aborting normalization",
],
$message
);
}
public function testExceptionTraceWithArgs()
{
try {
// This will contain $resource and $wrappedResource as arguments in the trace item
$resource = fopen('php://memory', 'rw+');
fwrite($resource, 'test_resource');
$wrappedResource = new TestFooNorm;
$wrappedResource->foo = $resource;
// Just do something stupid with a resource/wrapped resource as argument
$arr = [$wrappedResource, $resource];
// modifying the array inside throws a "usort(): Array was modified by the user comparison function"
usort($arr, function ($a, $b) {
throw new \ErrorException('Foo');
});
} catch (\Throwable $e) {
}
$formatter = new NormalizerFormatter();
$record = $this->getRecord(context: ['exception' => $e]);
$result = $formatter->format($record);
// See https://github.com/php/php-src/issues/8810 fixed in PHP 8.2
$offset = PHP_VERSION_ID >= 80200 ? 13 : 11;
$this->assertSame(
__FILE__.':'.(__LINE__ - $offset),
$result['context']['exception']['trace'][0]
);
}
private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception): array
{
$message = $formatter->format($this->getRecord(
Level::Critical,
'foobar',
channel: 'core',
context: ['exception' => $exception],
));
return $message;
}
public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
{
try {
$arg = new TestInfoLeak;
\call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime());
} catch (\Exception $e) {
}
$formatter = new NormalizerFormatter();
$record = $this->getRecord(context: ['exception' => $e]);
$result = $formatter->format($record);
$this->assertSame(
__FILE__ .':'.(__LINE__-9),
$result['context']['exception']['trace'][0]
);
}
public function testCanNormalizeIncompleteObject(): void
{
$serialized = "O:17:\"Monolog\TestClass\":1:{s:23:\"\x00Monolog\TestClass\x00name\";s:4:\"test\";}";
$object = unserialize($serialized);
$formatter = new NormalizerFormatter();
$record = $this->getRecord(context: ['object' => $object]);
$result = $formatter->format($record);
$this->assertEquals([
'__PHP_Incomplete_Class' => 'Monolog\\TestClass',
], $result['context']['object']);
}
private function throwHelper($arg)
{
throw new \RuntimeException('Thrown');
}
}
class TestFooNorm
{
public $foo = 'fooValue';
}
class TestBarNorm
{
public function __toString()
{
return 'bar';
}
}
class TestStreamFoo
{
public $foo;
public $resource;
public function __construct($resource)
{
$this->resource = $resource;
$this->foo = 'BAR';
}
public function __toString()
{
fseek($this->resource, 0);
return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
}
}
class TestToStringError
{
public function __toString()
{
throw new \RuntimeException('Could not convert to string');
}
}
class TestInfoLeak
{
public function __toString()
{
return 'Sensitive information';
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/LogmaticFormatterTest.php | tests/Monolog/Formatter/LogmaticFormatterTest.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\Test\MonologTestCase;
/**
* @author Julien Breux <julien.breux@gmail.com>
*/
class LogmaticFormatterTest extends MonologTestCase
{
/**
* @covers Monolog\Formatter\LogmaticFormatter::format
*/
public function testFormat()
{
$formatter = new LogmaticFormatter();
$formatter->setHostname('testHostname');
$formatter->setAppName('testAppname');
$record = $this->getRecord();
$formatted_decoded = json_decode($formatter->format($record), true);
$this->assertArrayHasKey('hostname', $formatted_decoded);
$this->assertArrayHasKey('appname', $formatted_decoded);
$this->assertEquals('testHostname', $formatted_decoded['hostname']);
$this->assertEquals('testAppname', $formatted_decoded['appname']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/GoogleCloudLoggingFormatterTest.php | tests/Monolog/Formatter/GoogleCloudLoggingFormatterTest.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\Test\MonologTestCase;
use function json_decode;
class GoogleCloudLoggingFormatterTest extends MonologTestCase
{
/**
* @test
*
* @covers \Monolog\Formatter\JsonFormatter
* @covers \Monolog\Formatter\GoogleCloudLoggingFormatter::normalizeRecord
*/
public function formatProvidesRfc3339Timestamps(): void
{
$formatter = new GoogleCloudLoggingFormatter();
$record = $this->getRecord();
$formatted_decoded = json_decode($formatter->format($record), true);
$this->assertArrayNotHasKey("datetime", $formatted_decoded);
$this->assertArrayHasKey("time", $formatted_decoded);
$this->assertSame($record->datetime->format(DateTimeInterface::RFC3339_EXTENDED), $formatted_decoded["time"]);
}
/**
* @test
*
* @covers \Monolog\Formatter\JsonFormatter
* @covers \Monolog\Formatter\GoogleCloudLoggingFormatter::normalizeRecord
*/
public function formatIntroducesLogSeverity(): void
{
$formatter = new GoogleCloudLoggingFormatter();
$record = $this->getRecord();
$formatted_decoded = json_decode($formatter->format($record), true);
$this->assertArrayNotHasKey("level", $formatted_decoded);
$this->assertArrayNotHasKey("level_name", $formatted_decoded);
$this->assertArrayHasKey("severity", $formatted_decoded);
$this->assertSame($record->level->getName(), $formatted_decoded["severity"]);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/GelfMessageFormatterTest.php | tests/Monolog/Formatter/GelfMessageFormatterTest.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\Test\MonologTestCase;
class GelfMessageFormatterTest extends MonologTestCase
{
public function setUp(): void
{
if (!class_exists('\Gelf\Message')) {
$this->markTestSkipped("graylog2/gelf-php is not installed");
}
}
/**
* @covers Monolog\Formatter\GelfMessageFormatter::format
*/
public function testDefaultFormatter()
{
$formatter = new GelfMessageFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
datetime: new \DateTimeImmutable("@0"),
);
$message = $formatter->format($record);
$this->assertInstanceOf('Gelf\Message', $message);
$this->assertEquals(0, $message->getTimestamp());
$this->assertEquals('log', $message->getShortMessage());
$this->assertEquals('meh', $message->getAdditional('facility'));
$this->assertEquals(false, $message->hasAdditional('line'));
$this->assertEquals(false, $message->hasAdditional('file'));
$this->assertEquals($this->isLegacy() ? 3 : 'error', $message->getLevel());
$this->assertNotEmpty($message->getHost());
$formatter = new GelfMessageFormatter('mysystem');
$message = $formatter->format($record);
$this->assertInstanceOf('Gelf\Message', $message);
$this->assertEquals('mysystem', $message->getHost());
}
/**
* @covers Monolog\Formatter\GelfMessageFormatter::format
*/
public function testFormatWithFileAndLine()
{
$formatter = new GelfMessageFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
datetime: new \DateTimeImmutable("@0"),
extra: ['file' => 'test', 'line' => 14, 0 => 'foo'],
);
$message = $formatter->format($record);
$this->assertInstanceOf('Gelf\Message', $message);
$this->assertEquals('test', $message->getAdditional('file'));
$this->assertEquals(14, $message->getAdditional('line'));
}
/**
* @covers Monolog\Formatter\GelfMessageFormatter::format
*/
public function testFormatWithContext()
{
$formatter = new GelfMessageFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger', 'trueBool' => true, 'falseBool' => false],
datetime: new \DateTimeImmutable("@0"),
extra: ['key' => 'pair'],
);
$message = $formatter->format($record);
$this->assertInstanceOf('Gelf\Message', $message);
$message_array = $message->toArray();
$this->assertArrayHasKey('_ctxt_from', $message_array);
$this->assertEquals('logger', $message_array['_ctxt_from']);
$this->assertArrayHasKey('_ctxt_trueBool', $message_array);
$this->assertEquals(1, $message_array['_ctxt_trueBool']);
$this->assertArrayHasKey('_ctxt_falseBool', $message_array);
$this->assertEquals(0, $message_array['_ctxt_falseBool']);
// Test with extraPrefix
$formatter = new GelfMessageFormatter(null, null, 'CTX');
$message = $formatter->format($record);
$this->assertInstanceOf('Gelf\Message', $message);
$message_array = $message->toArray();
$this->assertArrayHasKey('_CTXfrom', $message_array);
$this->assertEquals('logger', $message_array['_CTXfrom']);
$this->assertArrayHasKey('_CTXtrueBool', $message_array);
$this->assertEquals(1, $message_array['_CTXtrueBool']);
$this->assertArrayHasKey('_CTXfalseBool', $message_array);
$this->assertEquals(0, $message_array['_CTXfalseBool']);
}
/**
* @covers Monolog\Formatter\GelfMessageFormatter::format
*/
public function testFormatWithContextContainingException()
{
$formatter = new GelfMessageFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger', 'exception' => [
'class' => '\Exception',
'file' => '/some/file/in/dir.php:56',
'trace' => ['/some/file/1.php:23', '/some/file/2.php:3'],
]],
datetime: new \DateTimeImmutable("@0"),
);
$message = $formatter->format($record);
$this->assertInstanceOf('Gelf\Message', $message);
$this->assertEquals("/some/file/in/dir.php", $message->getAdditional('file'));
$this->assertEquals("56", $message->getAdditional('line'));
}
/**
* @covers Monolog\Formatter\GelfMessageFormatter::format
*/
public function testFormatWithExtra()
{
$formatter = new GelfMessageFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
datetime: new \DateTimeImmutable("@0"),
extra: ['key' => 'pair', 'trueBool' => true, 'falseBool' => false],
);
$message = $formatter->format($record);
$this->assertInstanceOf('Gelf\Message', $message);
$message_array = $message->toArray();
$this->assertArrayHasKey('_key', $message_array);
$this->assertEquals('pair', $message_array['_key']);
$this->assertArrayHasKey('_trueBool', $message_array);
$this->assertEquals(1, $message_array['_trueBool']);
$this->assertArrayHasKey('_falseBool', $message_array);
$this->assertEquals(0, $message_array['_falseBool']);
// Test with extraPrefix
$formatter = new GelfMessageFormatter(null, 'EXT');
$message = $formatter->format($record);
$this->assertInstanceOf('Gelf\Message', $message);
$message_array = $message->toArray();
$this->assertArrayHasKey('_EXTkey', $message_array);
$this->assertEquals('pair', $message_array['_EXTkey']);
$this->assertArrayHasKey('_EXTtrueBool', $message_array);
$this->assertEquals(1, $message_array['_EXTtrueBool']);
$this->assertArrayHasKey('_EXTfalseBool', $message_array);
$this->assertEquals(0, $message_array['_EXTfalseBool']);
}
public function testFormatWithLargeData()
{
$formatter = new GelfMessageFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['exception' => str_repeat(' ', 32767)],
datetime: new \DateTimeImmutable("@0"),
extra: ['key' => str_repeat(' ', 32767)],
);
$message = $formatter->format($record);
$messageArray = $message->toArray();
// 200 for padding + metadata
$length = 200;
foreach ($messageArray as $key => $value) {
if (!\in_array($key, ['level', 'timestamp']) && \is_string($value)) {
$length += \strlen($value);
}
}
$this->assertLessThanOrEqual(65792, $length, 'The message length is no longer than the maximum allowed length');
}
public function testFormatWithUnlimitedLength()
{
$formatter = new GelfMessageFormatter('LONG_SYSTEM_NAME', null, 'ctxt_', PHP_INT_MAX);
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['exception' => str_repeat(' ', 32767 * 2)],
datetime: new \DateTimeImmutable("@0"),
extra: ['key' => str_repeat(' ', 32767 * 2)],
);
$message = $formatter->format($record);
$messageArray = $message->toArray();
// 200 for padding + metadata
$length = 200;
foreach ($messageArray as $key => $value) {
if (!\in_array($key, ['level', 'timestamp'])) {
$length += \strlen($value);
}
}
$this->assertGreaterThanOrEqual(131289, $length, 'The message should not be truncated');
}
public function testFormatWithLargeCyrillicData()
{
$formatter = new GelfMessageFormatter();
$record = $this->getRecord(
Level::Error,
str_repeat('в', 32767),
channel: 'meh',
context: ['exception' => str_repeat('а', 32767)],
datetime: new \DateTimeImmutable("@0"),
extra: ['key' => str_repeat('б', 32767)],
);
$message = $formatter->format($record);
$messageArray = $message->toArray();
$messageString = json_encode($messageArray);
$this->assertIsString($messageString);
}
private function isLegacy()
{
return interface_exists('\Gelf\IMessagePublisher');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/ChromePHPFormatterTest.php | tests/Monolog/Formatter/ChromePHPFormatterTest.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\Test\MonologTestCase;
class ChromePHPFormatterTest extends MonologTestCase
{
/**
* @covers Monolog\Formatter\ChromePHPFormatter::format
*/
public function testDefaultFormat()
{
$formatter = new ChromePHPFormatter();
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
datetime: new \DateTimeImmutable("@0"),
extra: ['ip' => '127.0.0.1'],
);
$message = $formatter->format($record);
$this->assertEquals(
[
'meh',
[
'message' => 'log',
'context' => ['from' => 'logger'],
'extra' => ['ip' => '127.0.0.1'],
],
'unknown',
'error',
],
$message
);
}
/**
* @covers Monolog\Formatter\ChromePHPFormatter::format
*/
public function testFormatWithFileAndLine()
{
$formatter = new ChromePHPFormatter();
$record = $this->getRecord(
Level::Critical,
'log',
channel: 'meh',
context: ['from' => 'logger'],
datetime: new \DateTimeImmutable("@0"),
extra: ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14],
);
$message = $formatter->format($record);
$this->assertEquals(
[
'meh',
[
'message' => 'log',
'context' => ['from' => 'logger'],
'extra' => ['ip' => '127.0.0.1'],
],
'test : 14',
'error',
],
$message
);
}
/**
* @covers Monolog\Formatter\ChromePHPFormatter::format
*/
public function testFormatWithoutContext()
{
$formatter = new ChromePHPFormatter();
$record = $this->getRecord(
Level::Debug,
'log',
channel: 'meh',
datetime: new \DateTimeImmutable("@0"),
);
$message = $formatter->format($record);
$this->assertEquals(
[
'meh',
'log',
'unknown',
'log',
],
$message
);
}
/**
* @covers Monolog\Formatter\ChromePHPFormatter::formatBatch
*/
public function testBatchFormatThrowException()
{
$formatter = new ChromePHPFormatter();
$records = [
$this->getRecord(
Level::Info,
'log',
channel: 'meh',
datetime: new \DateTimeImmutable("@0"),
),
$this->getRecord(
Level::Warning,
'log2',
channel: 'foo',
datetime: new \DateTimeImmutable("@0"),
),
];
$this->assertEquals(
[
[
'meh',
'log',
'unknown',
'info',
],
[
'foo',
'log2',
'unknown',
'warn',
],
],
$formatter->formatBatch($records)
);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/LogglyFormatterTest.php | tests/Monolog/Formatter/LogglyFormatterTest.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\Test\MonologTestCase;
class LogglyFormatterTest extends MonologTestCase
{
/**
* @covers Monolog\Formatter\LogglyFormatter::__construct
*/
public function testConstruct()
{
$formatter = new LogglyFormatter();
$this->assertEquals(LogglyFormatter::BATCH_MODE_NEWLINES, $formatter->getBatchMode());
$formatter = new LogglyFormatter(LogglyFormatter::BATCH_MODE_JSON);
$this->assertEquals(LogglyFormatter::BATCH_MODE_JSON, $formatter->getBatchMode());
}
/**
* @covers Monolog\Formatter\LogglyFormatter::format
*/
public function testFormat()
{
$formatter = new LogglyFormatter();
$record = $this->getRecord();
$formatted_decoded = json_decode($formatter->format($record), true);
$this->assertArrayNotHasKey("datetime", $formatted_decoded);
$this->assertArrayHasKey("timestamp", $formatted_decoded);
$this->assertEquals($record->datetime->format('Y-m-d\TH:i:s.uO'), $formatted_decoded["timestamp"]);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/ElasticaFormatterTest.php | tests/Monolog/Formatter/ElasticaFormatterTest.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\Test\MonologTestCase;
class ElasticaFormatterTest extends MonologTestCase
{
public function setUp(): void
{
if (!class_exists("Elastica\Document")) {
$this->markTestSkipped("ruflin/elastica not installed");
}
}
/**
* @covers Monolog\Formatter\ElasticaFormatter::__construct
* @covers Monolog\Formatter\ElasticaFormatter::format
* @covers Monolog\Formatter\ElasticaFormatter::getDocument
*/
public function testFormat()
{
// test log message
$msg = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['foo' => 7, 'bar', 'class' => new \stdClass],
datetime: new \DateTimeImmutable("@0"),
);
// expected values
$expected = $msg->toArray();
$expected['datetime'] = '1970-01-01T00:00:00.000000+00:00';
$expected['context'] = [
'class' => ['stdClass' => []],
'foo' => 7,
0 => 'bar',
];
// format log message
$formatter = new ElasticaFormatter('my_index', 'doc_type');
$doc = $formatter->format($msg);
$this->assertInstanceOf('Elastica\Document', $doc);
// Document parameters
$this->assertEquals('my_index', $doc->getIndex());
if (method_exists($doc, 'getType')) {
$this->assertEquals('doc_type', $doc->getType());
}
// Document data values
$data = $doc->getData();
foreach (array_keys($expected) as $key) {
$this->assertEquals($expected[$key], $data[$key]);
}
}
/**
* @covers Monolog\Formatter\ElasticaFormatter::getIndex
* @covers Monolog\Formatter\ElasticaFormatter::getType
*/
public function testGetters()
{
$formatter = new ElasticaFormatter('my_index', 'doc_type');
$this->assertEquals('my_index', $formatter->getIndex());
$this->assertEquals('doc_type', $formatter->getType());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/MongoDBFormatterTest.php | tests/Monolog/Formatter/MongoDBFormatterTest.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\ObjectId;
use MongoDB\BSON\Regex;
use MongoDB\BSON\UTCDateTime;
use Monolog\Level;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
/**
* @author Florian Plattner <me@florianplattner.de>
*/
#[RequiresPhpExtension('mongodb')]
class MongoDBFormatterTest extends \Monolog\Test\MonologTestCase
{
public static function constructArgumentProvider()
{
return [
[1, true, 1, true],
[0, false, 0, false],
];
}
#[DataProvider('constructArgumentProvider')]
public function testConstruct($traceDepth, $traceAsString, $expectedTraceDepth, $expectedTraceAsString)
{
$formatter = new MongoDBFormatter($traceDepth, $traceAsString);
$reflTrace = new \ReflectionProperty($formatter, 'exceptionTraceAsString');
$this->assertEquals($expectedTraceAsString, $reflTrace->getValue($formatter));
$reflDepth = new \ReflectionProperty($formatter, 'maxNestingLevel');
$this->assertEquals($expectedTraceDepth, $reflDepth->getValue($formatter));
}
public function testSimpleFormat()
{
$record = $this->getRecord(
message: 'some log message',
level: Level::Warning,
channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
);
$formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record);
$this->assertCount(7, $formattedRecord);
$this->assertEquals('some log message', $formattedRecord['message']);
$this->assertEquals([], $formattedRecord['context']);
$this->assertEquals(Level::Warning->value, $formattedRecord['level']);
$this->assertEquals(Level::Warning->getName(), $formattedRecord['level_name']);
$this->assertEquals('test', $formattedRecord['channel']);
$this->assertInstanceOf(UTCDateTime::class, $formattedRecord['datetime']);
$this->assertEquals('1453410690123', $formattedRecord['datetime']->__toString());
$this->assertEquals([], $formattedRecord['extra']);
}
public function testRecursiveFormat()
{
$someObject = new \stdClass();
$someObject->foo = 'something';
$someObject->bar = 'stuff';
$record = $this->getRecord(
message: 'some log message',
context: [
'stuff' => new \DateTimeImmutable('1969-01-21T21:11:30.213000+00:00'),
'some_object' => $someObject,
'context_string' => 'some string',
'context_int' => 123456,
'except' => new \Exception('exception message', 987),
],
level: Level::Warning,
channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.213000+00:00'),
);
$formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record);
$this->assertCount(5, $formattedRecord['context']);
$this->assertInstanceOf(UTCDateTime::class, $formattedRecord['context']['stuff']);
$this->assertEquals('-29731710213', $formattedRecord['context']['stuff']->__toString());
$this->assertEquals(
[
'foo' => 'something',
'bar' => 'stuff',
'class' => 'stdClass',
],
$formattedRecord['context']['some_object']
);
$this->assertEquals('some string', $formattedRecord['context']['context_string']);
$this->assertEquals(123456, $formattedRecord['context']['context_int']);
$this->assertCount(5, $formattedRecord['context']['except']);
$this->assertEquals('exception message', $formattedRecord['context']['except']['message']);
$this->assertEquals(987, $formattedRecord['context']['except']['code']);
$this->assertIsString($formattedRecord['context']['except']['file']);
$this->assertIsInt($formattedRecord['context']['except']['code']);
$this->assertIsString($formattedRecord['context']['except']['trace']);
$this->assertEquals('Exception', $formattedRecord['context']['except']['class']);
}
public function testFormatDepthArray()
{
$record = $this->getRecord(
message: 'some log message',
context: [
'nest2' => [
'property' => 'anything',
'nest3' => [
'nest4' => 'value',
'property' => 'nothing',
],
],
],
level: Level::Warning,
channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
);
$formatter = new MongoDBFormatter(2);
$formattedResult = $formatter->format($record);
$this->assertEquals(
[
'nest2' => [
'property' => 'anything',
'nest3' => '[...]',
],
],
$formattedResult['context']
);
}
public function testFormatDepthArrayInfiniteNesting()
{
$record = $this->getRecord(
message: 'some log message',
context: [
'nest2' => [
'property' => 'something',
'nest3' => [
'property' => 'anything',
'nest4' => [
'property' => 'nothing',
],
],
],
],
level: Level::Warning,
channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
);
$formatter = new MongoDBFormatter(0);
$formattedResult = $formatter->format($record);
$this->assertEquals(
[
'nest2' => [
'property' => 'something',
'nest3' => [
'property' => 'anything',
'nest4' => [
'property' => 'nothing',
],
],
],
],
$formattedResult['context']
);
}
public function testFormatDepthObjects()
{
$someObject = new \stdClass();
$someObject->property = 'anything';
$someObject->nest3 = new \stdClass();
$someObject->nest3->property = 'nothing';
$someObject->nest3->nest4 = 'invisible';
$record = $this->getRecord(
message: 'some log message',
context: [
'nest2' => $someObject,
],
level: Level::Warning,
channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
);
$formatter = new MongoDBFormatter(2, true);
$formattedResult = $formatter->format($record);
$this->assertEquals(
[
'nest2' => [
'property' => 'anything',
'nest3' => '[...]',
'class' => 'stdClass',
],
],
$formattedResult['context']
);
}
public function testFormatDepthException()
{
$record = $this->getRecord(
message: 'some log message',
context: [
'nest2' => new \Exception('exception message', 987),
],
level: Level::Warning,
channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
);
$formatter = new MongoDBFormatter(2, false);
$formattedRecord = $formatter->format($record);
$this->assertEquals('exception message', $formattedRecord['context']['nest2']['message']);
$this->assertEquals(987, $formattedRecord['context']['nest2']['code']);
$this->assertEquals('[...]', $formattedRecord['context']['nest2']['trace']);
}
public function testBsonTypes()
{
$record = $this->getRecord(
message: 'some log message',
context: [
'objectid' => new ObjectId(),
'nest' => [
'timestamp' => new UTCDateTime(),
'regex' => new Regex('pattern'),
],
],
level: Level::Warning,
channel: 'test',
datetime: new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
);
$formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record);
$this->assertInstanceOf(ObjectId::class, $formattedRecord['context']['objectid']);
$this->assertInstanceOf(UTCDateTime::class, $formattedRecord['context']['nest']['timestamp']);
$this->assertInstanceOf(Regex::class, $formattedRecord['context']['nest']['regex']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/LineFormatterTest.php | tests/Monolog/Formatter/LineFormatterTest.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\Test\MonologTestCase;
use Monolog\Level;
use PHPUnit\Framework\Attributes\DataProvider;
use RuntimeException;
/**
* @covers Monolog\Formatter\LineFormatter
*/
class LineFormatterTest extends MonologTestCase
{
public function testDefFormatWithString()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord(
Level::Warning,
'foo',
channel: 'log',
));
$this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
}
public function testDefFormatWithArrayContext()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord(
Level::Error,
'foo',
channel: 'meh',
context: [
'foo' => 'bar',
'baz' => 'qux',
'bool' => false,
'null' => null,
],
));
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message);
}
public function testDefFormatExtras()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord(
Level::Error,
'log',
channel: 'meh',
extra: ['ip' => '127.0.0.1'],
));
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message);
}
public function testFormatExtras()
{
$formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d');
$message = $formatter->format($this->getRecord(
Level::Error,
'log',
channel: 'meh',
extra: ['ip' => '127.0.0.1', 'file' => 'test'],
));
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message);
}
public function testContextAndExtraOptionallyNotShownIfEmpty()
{
$formatter = new LineFormatter(null, 'Y-m-d', false, true);
$message = $formatter->format($this->getRecord(
Level::Error,
'log',
channel: 'meh',
));
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log '."\n", $message);
}
public function testContextAndExtraReplacement()
{
$formatter = new LineFormatter('%context.foo% => %extra.foo%');
$message = $formatter->format($this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['foo' => 'bar'],
extra: ['foo' => 'xbar'],
));
$this->assertEquals('bar => xbar', $message);
}
public function testDefFormatWithObject()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord(
Level::Error,
'foobar',
channel: 'meh',
context: [],
extra: ['foo' => new TestFoo, 'bar' => new TestBar, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
));
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":{"Monolog\\\\Formatter\\\\TestFoo":{"foo":"fooValue"}},"bar":{"Monolog\\\\Formatter\\\\TestBar":"bar"},"baz":[],"res":"[resource(stream)]"}'."\n", $message);
}
public function testDefFormatWithException()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord(
Level::Critical,
'foobar',
channel: 'core',
context: ['exception' => new \RuntimeException('Foo')],
));
$path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
}
public function testDefFormatWithExceptionAndStacktrace()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$formatter->includeStacktraces();
$message = $formatter->format($this->getRecord(
Level::Critical,
'foobar',
channel: 'core',
context: ['exception' => new \RuntimeException('Foo')],
));
$path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertMatchesRegularExpression('{^\['.date('Y-m-d').'] core\.CRITICAL: foobar \{"exception":"\[object] \(RuntimeException\(code: 0\): Foo at '.preg_quote(substr($path, 1, -1)).':'.(__LINE__ - 5).'\)\n\[stacktrace]\n#0}', $message);
}
public function testInlineLineBreaksRespectsEscapedBackslashes()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$formatter->allowInlineLineBreaks();
self::assertSame('{"test":"foo'."\n".'bar\\\\name-with-n"}', $formatter->stringify(["test" => "foo\nbar\\name-with-n"]));
self::assertSame('["indexed'."\n".'arrays'."\n".'without'."\n".'key","foo'."\n".'bar\\\\name-with-n"]', $formatter->stringify(["indexed\narrays\nwithout\nkey", "foo\nbar\\name-with-n"]));
self::assertSame('[{"first":"multi-dimensional'."\n".'arrays"},{"second":"foo'."\n".'bar\\\\name-with-n"}]', $formatter->stringify([["first" => "multi-dimensional\narrays"], ["second" => "foo\nbar\\name-with-n"]]));
}
public function testDefFormatWithExceptionAndStacktraceParserFull()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$formatter->includeStacktraces(true, function ($line) {
return $line;
});
$message = $formatter->format($this->getRecord(Level::Critical, context: ['exception' => new \RuntimeException('Foo')]));
$trace = explode('[stacktrace]', $message, 2)[1];
$this->assertStringContainsString('TestSuite.php', $trace);
$this->assertStringContainsString('TestRunner.php', $trace);
}
public function testDefFormatWithExceptionAndStacktraceParserCustom()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$formatter->includeStacktraces(true, function ($line) {
if (strpos($line, 'TestSuite.php') === false) {
return $line;
}
});
$message = $formatter->format($this->getRecord(Level::Critical, context: ['exception' => new \RuntimeException('Foo')]));
$trace = explode('[stacktrace]', $message, 2)[1];
$this->assertStringNotContainsString('TestSuite.php', $trace);
$this->assertStringContainsString('TestRunner.php', $trace);
}
public function testDefFormatWithExceptionAndStacktraceParserEmpty()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$formatter->includeStacktraces(true, function ($line) {
return null;
});
$message = $formatter->format($this->getRecord(Level::Critical, context: ['exception' => new \RuntimeException('Foo')]));
$this->assertStringNotContainsString('[stacktrace]', $message);
$this->assertStringEndsWith('"} []' . PHP_EOL, $message);
}
public function testDefFormatWithPreviousException()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$previous = new \LogicException('Wut?');
$message = $formatter->format($this->getRecord(
Level::Critical,
'foobar',
channel: 'core',
context: ['exception' => new \RuntimeException('Foo', 0, $previous)],
));
$path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 5).')\n[previous exception] [object] (LogicException(code: 0): Wut? at '.substr($path, 1, -1).':'.(__LINE__ - 10).')"} []'."\n", $message);
}
public function testDefFormatWithSoapFaultException()
{
if (!class_exists('SoapFault')) {
$this->markTestSkipped('Requires the soap extension');
}
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord(
Level::Critical,
'foobar',
channel: 'core',
context: ['exception' => new \SoapFault('foo', 'bar', 'hello', 'world')],
));
$path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (SoapFault(code: 0 faultcode: foo faultactor: hello detail: world): bar at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
$message = $formatter->format($this->getRecord(
Level::Critical,
'foobar',
channel: 'core',
context: ['exception' => new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world'])],
));
$path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (SoapFault(code: 0 faultcode: foo faultactor: hello detail: {\"bar\":{\"biz\":\"baz\"},\"foo\":\"world\"}): bar at '.substr($path, 1, -1).':'.(__LINE__ - 5).')"} []'."\n", $message);
}
public function testBatchFormat()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->formatBatch([
$this->getRecord(
Level::Critical,
'bar',
channel: 'test',
),
$this->getRecord(
Level::Warning,
'foo',
channel: 'log',
),
]);
$this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
}
public function testFormatShouldStripInlineLineBreaks()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format($this->getRecord(message: "foo\nbar"));
$this->assertMatchesRegularExpression('/foo bar/', $message);
}
public function testFormatShouldNotStripInlineLineBreaksWhenFlagIsSet()
{
$formatter = new LineFormatter(null, 'Y-m-d', true);
$message = $formatter->format($this->getRecord(message: "foo\nbar"));
$this->assertMatchesRegularExpression('/foo\nbar/', $message);
}
public function testIndentStackTraces(): void
{
$formatter = new LineFormatter();
$formatter->includeStacktraces();
//$formatter->allowInlineLineBreaks();
$formatter->indentStackTraces(' ');
$message = $formatter->format($this->getRecord(message: "foo", context: ['exception' => new RuntimeException('lala')]));
$this->assertStringContainsString(' [stacktrace]', $message);
$this->assertStringContainsString(' #0', $message);
$this->assertStringContainsString(' #1', $message);
}
public function testBasePath(): void
{
$formatter = new LineFormatter();
$formatter->includeStacktraces();
$formatter->setBasePath(\dirname(\dirname(\dirname(__DIR__))));
$formatter->indentStackTraces(' ');
$message = $formatter->format($this->getRecord(message: "foo", context: ['exception' => new RuntimeException('lala')]));
$this->assertStringContainsString(' [stacktrace]', $message);
$this->assertStringContainsString(' #0 vendor/phpunit/phpunit/src/Framework/TestCase.php', $message);
$this->assertStringContainsString(' #1 vendor/phpunit/phpunit/', $message);
}
#[DataProvider('providerMaxLevelNameLength')]
public function testMaxLevelNameLength(?int $maxLength, Level $logLevel, string $expectedLevelName): void
{
$formatter = new LineFormatter();
$formatter->setMaxLevelNameLength($maxLength);
$message = $formatter->format($this->getRecord(message: "foo\nbar", level: $logLevel));
$this->assertStringContainsString("test.$expectedLevelName:", $message);
}
public static function providerMaxLevelNameLength(): array
{
return [
'info_no_max_length' => [
'maxLength' => null,
'logLevel' => Level::Info,
'expectedLevelName' => 'INFO',
],
'error_max_length_3' => [
'maxLength' => 3,
'logLevel' => Level::Error,
'expectedLevelName' => 'ERR',
],
'debug_max_length_2' => [
'maxLength' => 2,
'logLevel' => Level::Debug,
'expectedLevelName' => 'DE',
],
];
}
}
class TestFoo
{
public string $foo = 'fooValue';
}
class TestBar
{
public function __toString()
{
return 'bar';
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Formatter/LogstashFormatterTest.php | tests/Monolog/Formatter/LogstashFormatterTest.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\Test\MonologTestCase;
class LogstashFormatterTest extends MonologTestCase
{
/**
* @covers Monolog\Formatter\LogstashFormatter::format
*/
public function testDefaultFormatterV1()
{
$formatter = new LogstashFormatter('test', 'hostname');
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
datetime: new \DateTimeImmutable("@0"),
);
$message = json_decode($formatter->format($record), true);
$this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']);
$this->assertEquals("1", $message['@version']);
$this->assertEquals('log', $message['message']);
$this->assertEquals('meh', $message['channel']);
$this->assertEquals(Level::Error->getName(), $message['level']);
$this->assertEquals(Level::Error->value, $message['monolog_level']);
$this->assertEquals('test', $message['type']);
$this->assertEquals('hostname', $message['host']);
$formatter = new LogstashFormatter('mysystem');
$message = json_decode($formatter->format($record), true);
$this->assertEquals('mysystem', $message['type']);
}
/**
* @covers Monolog\Formatter\LogstashFormatter::format
*/
public function testFormatWithFileAndLineV1()
{
$formatter = new LogstashFormatter('test');
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
datetime: new \DateTimeImmutable("@0"),
extra: ['file' => 'test', 'line' => 14],
);
$message = json_decode($formatter->format($record), true);
$this->assertEquals('test', $message['extra']['file']);
$this->assertEquals(14, $message['extra']['line']);
}
/**
* @covers Monolog\Formatter\LogstashFormatter::format
*/
public function testFormatWithContextV1()
{
$formatter = new LogstashFormatter('test');
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
datetime: new \DateTimeImmutable("@0"),
extra: ['key' => 'pair'],
);
$message = json_decode($formatter->format($record), true);
$this->assertArrayHasKey('context', $message);
$this->assertArrayHasKey('from', $message['context']);
$this->assertEquals('logger', $message['context']['from']);
// Test with extraPrefix
$formatter = new LogstashFormatter('test', null, 'extra', 'CTX');
$message = json_decode($formatter->format($record), true);
$this->assertArrayHasKey('CTX', $message);
$this->assertArrayHasKey('from', $message['CTX']);
$this->assertEquals('logger', $message['CTX']['from']);
}
/**
* @covers Monolog\Formatter\LogstashFormatter::format
*/
public function testFormatWithExtraV1()
{
$formatter = new LogstashFormatter('test');
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
datetime: new \DateTimeImmutable("@0"),
extra: ['key' => 'pair'],
);
$message = json_decode($formatter->format($record), true);
$this->assertArrayHasKey('extra', $message);
$this->assertArrayHasKey('key', $message['extra']);
$this->assertEquals('pair', $message['extra']['key']);
// Test with extraPrefix
$formatter = new LogstashFormatter('test', null, 'EXTRA');
$message = json_decode($formatter->format($record), true);
$this->assertArrayHasKey('EXTRA', $message);
$this->assertArrayHasKey('key', $message['EXTRA']);
$this->assertEquals('pair', $message['EXTRA']['key']);
}
public function testFormatWithApplicationNameV1()
{
$formatter = new LogstashFormatter('app', 'test');
$record = $this->getRecord(
Level::Error,
'log',
channel: 'meh',
context: ['from' => 'logger'],
datetime: new \DateTimeImmutable("@0"),
extra: ['key' => 'pair'],
);
$message = json_decode($formatter->format($record), true);
$this->assertArrayHasKey('type', $message);
$this->assertEquals('app', $message['type']);
}
public function testFormatWithLatin9Data()
{
$formatter = new LogstashFormatter('test', 'hostname');
$record = $this->getRecord(
Level::Error,
'log',
channel: '¯\_(ツ)_/¯',
datetime: new \DateTimeImmutable("@0"),
extra: [
'user_agent' => "\xD6WN; FBCR/OrangeEspa\xF1a; Vers\xE3o/4.0; F\xE4rist",
],
);
$message = json_decode($formatter->format($record), true);
$this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']);
$this->assertEquals('log', $message['message']);
$this->assertEquals('¯\_(ツ)_/¯', $message['channel']);
$this->assertEquals('ERROR', $message['level']);
$this->assertEquals('test', $message['type']);
$this->assertEquals('hostname', $message['host']);
$this->assertEquals('�WN; FBCR/OrangeEspa�a; Vers�o/4.0; F�rist', $message['extra']['user_agent']);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/SymfonyMailerHandlerTest.php | tests/Monolog/Handler/SymfonyMailerHandlerTest.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\Logger;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
class SymfonyMailerHandlerTest extends \Monolog\Test\MonologTestCase
{
/** @var MailerInterface&MockObject */
private $mailer;
public function setUp(): void
{
$this->mailer = $this
->getMockBuilder(MailerInterface::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->mailer);
}
public function testMessageCreationIsLazyWhenUsingCallback()
{
$this->mailer->expects($this->never())
->method('send');
$callback = function () {
throw new \RuntimeException('Email creation callback should not have been called in this test');
};
$handler = new SymfonyMailerHandler($this->mailer, $callback);
$records = [
$this->getRecord(Logger::DEBUG),
$this->getRecord(Logger::INFO),
];
$handler->handleBatch($records);
}
public function testMessageCanBeCustomizedGivenLoggedData()
{
// Wire Mailer to expect a specific Email with a customized Subject
$expectedMessage = new Email();
$this->mailer->expects($this->once())
->method('send')
->with($this->callback(function ($value) use ($expectedMessage) {
return $value instanceof Email
&& $value->getSubject() === 'Emergency'
&& $value === $expectedMessage;
}));
// Callback dynamically changes subject based on number of logged records
$callback = function ($content, array $records) use ($expectedMessage) {
$subject = \count($records) > 0 ? 'Emergency' : 'Normal';
return $expectedMessage->subject($subject);
};
$handler = new SymfonyMailerHandler($this->mailer, $callback);
// Logging 1 record makes this an Emergency
$records = [
$this->getRecord(Logger::EMERGENCY),
];
$handler->handleBatch($records);
}
public function testMessageSubjectFormatting()
{
// Wire Mailer to expect a specific Email with a customized Subject
$messageTemplate = new Email();
$messageTemplate->subject('Alert: %level_name% %message%');
$receivedMessage = null;
$this->mailer->expects($this->once())
->method('send')
->with($this->callback(function ($value) use (&$receivedMessage) {
$receivedMessage = $value;
return true;
}));
$handler = new SymfonyMailerHandler($this->mailer, $messageTemplate);
$records = [
$this->getRecord(Logger::EMERGENCY),
];
$handler->handleBatch($records);
$this->assertEquals('Alert: EMERGENCY test', $receivedMessage->getSubject());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/FlowdockHandlerTest.php | tests/Monolog/Handler/FlowdockHandlerTest.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\Formatter\FlowdockFormatter;
use Monolog\Level;
/**
* @author Dominik Liebler <liebler.dominik@gmail.com>
* @see https://www.hipchat.com/docs/api
*/
class FlowdockHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @var resource
*/
private $res;
private FlowdockHandler $handler;
public function setUp(): void
{
if (!\extension_loaded('openssl')) {
$this->markTestSkipped('This test requires openssl to run');
}
}
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
unset($this->handler);
}
public function testWriteHeader()
{
$this->createHandler();
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/POST \/v1\/messages\/team_inbox\/.* HTTP\/1.1\\r\\nHost: api.flowdock.com\\r\\nContent-Type: application\/json\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
return $content;
}
/**
* @depends testWriteHeader
*/
public function testWriteContent($content)
{
$this->assertMatchesRegularExpression('/"source":"test_source"/', $content);
$this->assertMatchesRegularExpression('/"from_address":"source@test\.com"/', $content);
}
private function createHandler($token = 'myToken')
{
$constructorArgs = [$token, Level::Debug];
$this->res = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder('Monolog\Handler\FlowdockHandler')
->setConstructorArgs($constructorArgs)
->onlyMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
->getMock();
$reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setValue($this->handler, 'localhost:1234');
$this->handler->expects($this->any())
->method('fsockopen')
->willReturn($this->res);
$this->handler->expects($this->any())
->method('streamSetTimeout')
->willReturn(true);
$this->handler->expects($this->any())
->method('closeSocket');
$this->handler->setFormatter(new FlowdockFormatter('test_source', 'source@test.com'));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/RedisPubSubHandlerTest.php | tests/Monolog/Handler/RedisPubSubHandlerTest.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\Formatter\LineFormatter;
class RedisPubSubHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testConstructorShouldWorkWithPredis()
{
$redis = $this->createMock('Predis\Client');
$this->assertInstanceof('Monolog\Handler\RedisPubSubHandler', new RedisPubSubHandler($redis, 'key'));
}
public function testConstructorShouldWorkWithRedis()
{
if (!class_exists('Redis')) {
$this->markTestSkipped('The redis ext is required to run this test');
}
$redis = $this->createMock('Redis');
$this->assertInstanceof('Monolog\Handler\RedisPubSubHandler', new RedisPubSubHandler($redis, 'key'));
}
public function testPredisHandle()
{
$redis = $this->getMockBuilder('Predis\Client')->getMock();
$redis->expects($this->atLeastOnce())
->method('__call')
->with(self::equalTo('publish'), self::equalTo(['key', 'test']));
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass(), 'foo' => 34]);
$handler = new RedisPubSubHandler($redis, 'key');
$handler->setFormatter(new LineFormatter("%message%"));
$handler->handle($record);
}
public function testRedisHandle()
{
if (!class_exists('Redis')) {
$this->markTestSkipped('The redis ext is required to run this test');
}
$redis = $this->createPartialMock('Redis', ['publish']);
$redis->expects($this->once())
->method('publish')
->with('key', 'test');
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass(), 'foo' => 34]);
$handler = new RedisPubSubHandler($redis, 'key');
$handler->setFormatter(new LineFormatter("%message%"));
$handler->handle($record);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/ExceptionTestHandler.php | tests/Monolog/Handler/ExceptionTestHandler.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 Exception;
use Monolog\LogRecord;
class ExceptionTestHandler extends TestHandler
{
/**
* @inheritDoc
*/
protected function write(LogRecord $record): void
{
throw new Exception("ExceptionTestHandler::handle");
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/ProcessHandlerTest.php | tests/Monolog/Handler/ProcessHandlerTest.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 PHPUnit\Framework\Attributes\DataProvider;
class ProcessHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* Dummy command to be used by tests that should not fail due to the command.
*
* @var string
*/
const DUMMY_COMMAND = 'php -r "echo fgets(STDIN);"';
/**
* @covers Monolog\Handler\ProcessHandler::__construct
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
* @covers Monolog\Handler\ProcessHandler::write
* @covers Monolog\Handler\ProcessHandler::ensureProcessIsStarted
* @covers Monolog\Handler\ProcessHandler::startProcess
* @covers Monolog\Handler\ProcessHandler::handleStartupErrors
*/
public function testWriteOpensProcessAndWritesToStdInOfProcess()
{
$fixtures = [
'chuck norris',
'foobar1337',
];
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->onlyMethods(['writeProcessInput']);
$mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
$handler = $mockBuilder->getMock();
$matcher = $this->exactly(2);
$handler->expects($matcher)
->method('writeProcessInput')
->willReturnCallback(function () use ($matcher, $fixtures) {
match ($matcher->numberOfInvocations()) {
1 => $this->stringContains($fixtures[0]),
2 => $this->stringContains($fixtures[1]),
};
})
;
/** @var ProcessHandler $handler */
$handler->handle($this->getRecord(Level::Warning, $fixtures[0]));
$handler->handle($this->getRecord(Level::Error, $fixtures[1]));
}
/**
* Data provider for invalid commands.
*/
public static function invalidCommandProvider(): array
{
return [
[1337, 'TypeError'],
['', 'InvalidArgumentException'],
[null, 'TypeError'],
[fopen('php://input', 'r'), 'TypeError'],
];
}
/**
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand
*/
#[DataProvider('invalidCommandProvider')]
public function testConstructWithInvalidCommandThrowsInvalidArgumentException(mixed $invalidCommand, string $expectedExcep)
{
$this->expectException($expectedExcep);
new ProcessHandler($invalidCommand, Level::Debug);
}
/**
* Data provider for invalid CWDs.
*/
public static function invalidCwdProvider(): array
{
return [
[1337, 'TypeError'],
['', 'InvalidArgumentException'],
[fopen('php://input', 'r'), 'TypeError'],
];
}
/**
* @param mixed $invalidCwd
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
*/
#[DataProvider('invalidCwdProvider')]
public function testConstructWithInvalidCwdThrowsInvalidArgumentException($invalidCwd, $expectedExcep)
{
$this->expectException($expectedExcep);
new ProcessHandler(self::DUMMY_COMMAND, Level::Debug, true, $invalidCwd);
}
/**
* @covers Monolog\Handler\ProcessHandler::__construct
* @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
*/
public function testConstructWithValidCwdWorks()
{
$handler = new ProcessHandler(self::DUMMY_COMMAND, Level::Debug, true, sys_get_temp_dir());
$this->assertInstanceOf(
'Monolog\Handler\ProcessHandler',
$handler,
'Constructed handler is not a ProcessHandler.'
);
}
/**
* @covers Monolog\Handler\ProcessHandler::handleStartupErrors
*/
public function testStartupWithFailingToSelectErrorStreamThrowsUnexpectedValueException()
{
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->onlyMethods(['selectErrorStream']);
$mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
$handler = $mockBuilder->getMock();
$handler->expects($this->once())
->method('selectErrorStream')
->willReturn(false);
$this->expectException(\UnexpectedValueException::class);
/** @var ProcessHandler $handler */
$handler->handle($this->getRecord(Level::Warning, 'stream failing, whoops'));
}
/**
* @covers Monolog\Handler\ProcessHandler::handleStartupErrors
* @covers Monolog\Handler\ProcessHandler::selectErrorStream
*/
public function testStartupWithErrorsThrowsUnexpectedValueException()
{
$handler = new ProcessHandler('>&2 echo "some fake error message"');
$this->expectException(\UnexpectedValueException::class);
$handler->handle($this->getRecord(Level::Warning, 'some warning in the house'));
}
/**
* @covers Monolog\Handler\ProcessHandler::write
*/
public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentException()
{
$mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
$mockBuilder->onlyMethods(['readProcessErrors']);
$mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
$handler = $mockBuilder->getMock();
$handler->expects($this->exactly(2))
->method('readProcessErrors')
->willReturnOnConsecutiveCalls('', 'some fake error message here');
$this->expectException(\UnexpectedValueException::class);
/** @var ProcessHandler $handler */
$handler->handle($this->getRecord(Level::Warning, 'some test stuff'));
}
/**
* @covers Monolog\Handler\ProcessHandler::close
*/
public function testCloseClosesProcess()
{
$class = new \ReflectionClass('Monolog\Handler\ProcessHandler');
$property = $class->getProperty('process');
$handler = new ProcessHandler(self::DUMMY_COMMAND);
$handler->handle($this->getRecord(Level::Warning, '21 is only the half truth'));
$process = $property->getValue($handler);
$this->assertTrue(\is_resource($process), 'Process is not running although it should.');
$handler->close();
$process = $property->getValue($handler);
$this->assertFalse(\is_resource($process), 'Process is still running although it should not.');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/AmqpHandlerTest.php | tests/Monolog/Handler/AmqpHandlerTest.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 PhpAmqpLib\Message\AMQPMessage;
/**
* @covers Monolog\Handler\RotatingFileHandler
*/
class AmqpHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testHandleAmqpExt()
{
if (!class_exists('AMQPConnection') || !class_exists('AMQPExchange')) {
$this->markTestSkipped("amqp-php not installed");
}
if (!class_exists('AMQPChannel')) {
$this->markTestSkipped("Please update AMQP to version >= 1.0");
}
$messages = [];
$exchange = $this->getMockBuilder('AMQPExchange')
->onlyMethods(['publish', 'setName'])
->disableOriginalConstructor()
->getMock();
$exchange->expects($this->any())
->method('publish')
->willReturnCallback(function ($message, $routing_key, $flags = 0, $attributes = []) use (&$messages) {
$messages[] = [$message, $routing_key, $flags, $attributes];
})
;
$handler = new AmqpHandler($exchange);
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$expected = [
[
'message' => 'test',
'context' => [
'data' => [],
'foo' => 34,
],
'level' => 300,
'level_name' => 'WARNING',
'channel' => 'test',
'extra' => [],
],
'warning.test',
0,
[
'delivery_mode' => 2,
'content_type' => 'application/json',
],
];
$handler->handle($record);
$this->assertCount(1, $messages);
$messages[0][0] = json_decode($messages[0][0], true);
unset($messages[0][0]['datetime']);
$this->assertEquals($expected, $messages[0]);
}
public function testHandlePhpAmqpLib()
{
if (!class_exists('PhpAmqpLib\Channel\AMQPChannel')) {
$this->markTestSkipped("php-amqplib not installed");
}
$messages = [];
$methodsToMock = ['basic_publish'];
if (method_exists('PhpAmqpLib\Channel\AMQPChannel', '__destruct')) {
$methodsToMock[] = '__destruct';
}
$exchange = $this->getMockBuilder('PhpAmqpLib\Channel\AMQPChannel')
->onlyMethods($methodsToMock)
->disableOriginalConstructor()
->getMock();
$exchange->expects($this->any())
->method('basic_publish')
->willReturnCallback(function (AMQPMessage $msg, $exchange = "", $routing_key = "", $mandatory = false, $immediate = false, $ticket = null) use (&$messages) {
$messages[] = [$msg, $exchange, $routing_key, $mandatory, $immediate, $ticket];
})
;
$handler = new AmqpHandler($exchange, 'log');
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$expected = [
[
'message' => 'test',
'context' => [
'data' => [],
'foo' => 34,
],
'level' => 300,
'level_name' => 'WARNING',
'channel' => 'test',
'extra' => [],
],
'log',
'warning.test',
false,
false,
null,
[
'delivery_mode' => 2,
'content_type' => 'application/json',
],
];
$handler->handle($record);
$this->assertCount(1, $messages);
/* @var $msg AMQPMessage */
$msg = $messages[0][0];
$messages[0][0] = json_decode($msg->body, true);
$messages[0][] = $msg->get_properties();
unset($messages[0][0]['datetime']);
$this->assertEquals($expected, $messages[0]);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/SlackHandlerTest.php | tests/Monolog/Handler/SlackHandlerTest.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\Formatter\LineFormatter;
use Monolog\Handler\Slack\SlackRecord;
use PHPUnit\Framework\Attributes\DataProvider;
/**
* @author Greg Kedzierski <greg@gregkedzierski.com>
* @see https://api.slack.com/
*/
class SlackHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @var resource
*/
private $res;
private SlackHandler $handler;
public function setUp(): void
{
if (!\extension_loaded('openssl')) {
$this->markTestSkipped('This test requires openssl to run');
}
}
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
unset($this->handler);
}
public function testWriteHeader()
{
$this->createHandler();
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('{POST /api/chat.postMessage HTTP/1.1\\r\\nHost: slack.com\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content);
}
public function testWriteContent()
{
$this->createHandler();
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/username=Monolog/', $content);
$this->assertMatchesRegularExpression('/channel=channel1/', $content);
$this->assertMatchesRegularExpression('/token=myToken/', $content);
$this->assertMatchesRegularExpression('/attachments/', $content);
}
public function testWriteContentUsesFormatterIfProvided()
{
$this->createHandler('myToken', 'channel1', 'Monolog', false);
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->createHandler('myToken', 'channel1', 'Monolog', false);
$this->handler->setFormatter(new LineFormatter('foo--%message%'));
$this->handler->handle($this->getRecord(Level::Critical, 'test2'));
fseek($this->res, 0);
$content2 = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/text=test1/', $content);
$this->assertMatchesRegularExpression('/text=foo--test2/', $content2);
}
public function testWriteContentWithEmoji()
{
$this->createHandler('myToken', 'channel1', 'Monolog', true, 'alien');
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/icon_emoji=%3Aalien%3A/', $content);
}
#[DataProvider('provideLevelColors')]
public function testWriteContentWithColors($level, $expectedColor)
{
$this->createHandler();
$this->handler->handle($this->getRecord($level, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/%22color%22%3A%22'.$expectedColor.'/', $content);
}
public function testWriteContentWithPlainTextMessage()
{
$this->createHandler('myToken', 'channel1', 'Monolog', false);
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/text=test1/', $content);
}
public static function provideLevelColors()
{
return [
[Level::Debug, urlencode(SlackRecord::COLOR_DEFAULT)],
[Level::Info, SlackRecord::COLOR_GOOD],
[Level::Notice, SlackRecord::COLOR_GOOD],
[Level::Warning, SlackRecord::COLOR_WARNING],
[Level::Error, SlackRecord::COLOR_DANGER],
[Level::Critical, SlackRecord::COLOR_DANGER],
[Level::Alert, SlackRecord::COLOR_DANGER],
[Level::Emergency,SlackRecord::COLOR_DANGER],
];
}
private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false)
{
$constructorArgs = [$token, $channel, $username, $useAttachment, $iconEmoji, Level::Debug, true, $useShortAttachment, $includeExtra];
$this->res = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder('Monolog\Handler\SlackHandler')
->setConstructorArgs($constructorArgs)
->onlyMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
->getMock();
$reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setValue($this->handler, 'localhost:1234');
$this->handler->expects($this->any())
->method('fsockopen')
->willReturn($this->res);
$this->handler->expects($this->any())
->method('streamSetTimeout')
->willReturn(true);
$this->handler->expects($this->any())
->method('closeSocket');
$this->handler->setFormatter($this->getIdentityFormatter());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/BufferHandlerTest.php | tests/Monolog/Handler/BufferHandlerTest.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;
class BufferHandlerTest extends \Monolog\Test\MonologTestCase
{
private TestHandler $shutdownCheckHandler;
/**
* @covers Monolog\Handler\BufferHandler::__construct
* @covers Monolog\Handler\BufferHandler::handle
* @covers Monolog\Handler\BufferHandler::close
*/
public function testHandleBuffers()
{
$test = new TestHandler();
$handler = new BufferHandler($test);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$this->assertFalse($test->hasDebugRecords());
$this->assertFalse($test->hasInfoRecords());
$handler->close();
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(2, $test->getRecords());
}
/**
* @covers Monolog\Handler\BufferHandler::close
* @covers Monolog\Handler\BufferHandler::flush
*/
public function testPropagatesRecordsAtEndOfRequest()
{
$test = new TestHandler();
$handler = new BufferHandler($test);
$handler->handle($this->getRecord(Level::Warning));
$handler->handle($this->getRecord(Level::Debug));
$this->shutdownCheckHandler = $test;
register_shutdown_function([$this, 'checkPropagation']);
}
public function checkPropagation()
{
if (!$this->shutdownCheckHandler->hasWarningRecords() || !$this->shutdownCheckHandler->hasDebugRecords()) {
echo '!!! BufferHandlerTest::testPropagatesRecordsAtEndOfRequest failed to verify that the messages have been propagated' . PHP_EOL;
exit(1);
}
}
/**
* @covers Monolog\Handler\BufferHandler::handle
*/
public function testHandleBufferLimit()
{
$test = new TestHandler();
$handler = new BufferHandler($test, 2);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$handler->handle($this->getRecord(Level::Warning));
$handler->close();
$this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertFalse($test->hasDebugRecords());
}
/**
* @covers Monolog\Handler\BufferHandler::handle
*/
public function testHandleBufferLimitWithFlushOnOverflow()
{
$test = new TestHandler();
$handler = new BufferHandler($test, 3, Level::Debug, true, true);
// send two records
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Debug));
$this->assertFalse($test->hasDebugRecords());
$this->assertCount(0, $test->getRecords());
// overflow
$handler->handle($this->getRecord(Level::Info));
$this->assertTrue($test->hasDebugRecords());
$this->assertCount(3, $test->getRecords());
// should buffer again
$handler->handle($this->getRecord(Level::Warning));
$this->assertCount(3, $test->getRecords());
$handler->close();
$this->assertCount(5, $test->getRecords());
$this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasInfoRecords());
}
/**
* @covers Monolog\Handler\BufferHandler::handle
*/
public function testHandleLevel()
{
$test = new TestHandler();
$handler = new BufferHandler($test, 0, Level::Info);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$handler->handle($this->getRecord(Level::Warning));
$handler->handle($this->getRecord(Level::Debug));
$handler->close();
$this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertFalse($test->hasDebugRecords());
}
/**
* @covers Monolog\Handler\BufferHandler::flush
*/
public function testFlush()
{
$test = new TestHandler();
$handler = new BufferHandler($test, 0);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$handler->flush();
$this->assertTrue($test->hasInfoRecords());
$this->assertTrue($test->hasDebugRecords());
$this->assertFalse($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\BufferHandler::handle
*/
public function testHandleUsesProcessors()
{
$test = new TestHandler();
$handler = new BufferHandler($test);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->handle($this->getRecord(Level::Warning));
$handler->flush();
$this->assertTrue($test->hasWarningRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
}
public function testSetHandler()
{
$testOriginal = new TestHandler();
$handler = new BufferHandler($testOriginal);
$handler->handle($this->getRecord(Level::Info));
$testNew = new TestHandler();
$handler->setHandler($testNew);
$handler->handle($this->getRecord(Level::Debug));
$handler->close();
$this->assertFalse($testOriginal->hasInfoRecords());
$this->assertFalse($testOriginal->hasDebugRecords());
$this->assertTrue($testNew->hasInfoRecords());
$this->assertTrue($testNew->hasDebugRecords());
$this->assertCount(2, $testNew->getRecords());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/ErrorLogHandlerTest.php | tests/Monolog/Handler/ErrorLogHandlerTest.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\Formatter\LineFormatter;
function error_log()
{
$GLOBALS['error_log'][] = \func_get_args();
}
class ErrorLogHandlerTest extends \Monolog\Test\MonologTestCase
{
protected function setUp(): void
{
$GLOBALS['error_log'] = [];
}
/**
* @covers Monolog\Handler\ErrorLogHandler::__construct
*/
public function testShouldNotAcceptAnInvalidTypeOnConstructor()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('The given message type "42" is not supported');
new ErrorLogHandler(42);
}
/**
* @covers Monolog\Handler\ErrorLogHandler::write
*/
public function testShouldLogMessagesUsingErrorLogFunction()
{
$type = ErrorLogHandler::OPERATING_SYSTEM;
$handler = new ErrorLogHandler($type);
$handler->setFormatter(new LineFormatter('%channel%.%level_name%: %message% %context% %extra%', null, true));
$handler->handle($this->getRecord(Level::Error, "Foo\nBar\r\n\r\nBaz"));
$this->assertSame("test.ERROR: Foo\nBar\r\n\r\nBaz [] []", $GLOBALS['error_log'][0][0]);
$this->assertSame($GLOBALS['error_log'][0][1], $type);
$handler = new ErrorLogHandler($type, Level::Debug, true, true);
$handler->setFormatter(new LineFormatter(null, null, true));
$handler->handle($this->getRecord(Level::Error, "Foo\nBar\r\n\r\nBaz"));
$this->assertStringMatchesFormat('[%s] test.ERROR: Foo', $GLOBALS['error_log'][1][0]);
$this->assertSame($GLOBALS['error_log'][1][1], $type);
$this->assertStringMatchesFormat('Bar', $GLOBALS['error_log'][2][0]);
$this->assertSame($GLOBALS['error_log'][2][1], $type);
$this->assertStringMatchesFormat('Baz [] []', $GLOBALS['error_log'][3][0]);
$this->assertSame($GLOBALS['error_log'][3][1], $type);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/ElasticaHandlerTest.php | tests/Monolog/Handler/ElasticaHandlerTest.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\Formatter\ElasticaFormatter;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Level;
use Elastica\Client;
use Elastica\Request;
use Elastica\Response;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
#[Group('Elastica')]
class ElasticaHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @var Client mock
*/
protected Client $client;
/**
* @var array Default handler options
*/
protected array $options = [
'index' => 'my_index',
'type' => 'doc_type',
];
public function setUp(): void
{
// Elastica lib required
if (!class_exists("Elastica\Client")) {
$this->markTestSkipped("ruflin/elastica not installed");
}
// base mock Elastica Client object
$this->client = $this->getMockBuilder('Elastica\Client')
->onlyMethods(['addDocuments'])
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->client);
}
/**
* @covers Monolog\Handler\ElasticaHandler::write
* @covers Monolog\Handler\ElasticaHandler::handleBatch
* @covers Monolog\Handler\ElasticaHandler::bulkSend
* @covers Monolog\Handler\ElasticaHandler::getDefaultFormatter
*/
public function testHandle()
{
// log message
$msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
// format expected result
$formatter = new ElasticaFormatter($this->options['index'], $this->options['type']);
$expected = [$formatter->format($msg)];
// setup ES client mock
$this->client->expects($this->any())
->method('addDocuments')
->with($expected);
// perform tests
$handler = new ElasticaHandler($this->client, $this->options);
$handler->handle($msg);
$handler->handleBatch([$msg]);
}
/**
* @covers Monolog\Handler\ElasticaHandler::setFormatter
*/
public function testSetFormatter()
{
$handler = new ElasticaHandler($this->client);
$formatter = new ElasticaFormatter('index_new', 'type_new');
$handler->setFormatter($formatter);
$this->assertInstanceOf('Monolog\Formatter\ElasticaFormatter', $handler->getFormatter());
$this->assertEquals('index_new', $handler->getFormatter()->getIndex());
$this->assertEquals('type_new', $handler->getFormatter()->getType());
}
/**
* @covers Monolog\Handler\ElasticaHandler::setFormatter
*/
public function testSetFormatterInvalid()
{
$handler = new ElasticaHandler($this->client);
$formatter = new NormalizerFormatter();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('ElasticaHandler is only compatible with ElasticaFormatter');
$handler->setFormatter($formatter);
}
/**
* @covers Monolog\Handler\ElasticaHandler::__construct
* @covers Monolog\Handler\ElasticaHandler::getOptions
*/
public function testOptions()
{
$expected = [
'index' => $this->options['index'],
'type' => $this->options['type'],
'ignore_error' => false,
];
$handler = new ElasticaHandler($this->client, $this->options);
$this->assertEquals($expected, $handler->getOptions());
}
/**
* @covers Monolog\Handler\ElasticaHandler::bulkSend
*/
#[DataProvider('providerTestConnectionErrors')]
public function testConnectionErrors($ignore, $expectedError)
{
$clientOpts = ['host' => '127.0.0.1', 'port' => 1];
$client = new Client($clientOpts);
$handlerOpts = ['ignore_error' => $ignore];
$handler = new ElasticaHandler($client, $handlerOpts);
if ($expectedError) {
$this->expectException($expectedError[0]);
$this->expectExceptionMessage($expectedError[1]);
$handler->handle($this->getRecord());
} else {
$this->assertFalse($handler->handle($this->getRecord()));
}
}
public static function providerTestConnectionErrors(): array
{
return [
[false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
[true, false],
];
}
/**
* Integration test using localhost Elastic Search server version 7+
*
* @covers Monolog\Handler\ElasticaHandler::__construct
* @covers Monolog\Handler\ElasticaHandler::handleBatch
* @covers Monolog\Handler\ElasticaHandler::bulkSend
* @covers Monolog\Handler\ElasticaHandler::getDefaultFormatter
*/
public function testHandleIntegrationNewESVersion()
{
$msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
$expected = (array) $msg;
$expected['datetime'] = $msg['datetime']->format(\DateTime::ATOM);
$expected['context'] = [
'class' => '[object] (stdClass: {})',
'foo' => 7,
0 => 'bar',
];
$clientOpts = ['url' => 'http://elastic:changeme@127.0.0.1:9200'];
$client = new Client($clientOpts);
$handler = new ElasticaHandler($client, $this->options);
try {
$handler->handleBatch([$msg]);
} catch (\RuntimeException $e) {
$this->markTestSkipped("Cannot connect to Elastic Search server on localhost");
}
// check document id from ES server response
$documentId = $this->getCreatedDocId($client->getLastResponse());
$this->assertNotEmpty($documentId, 'No elastic document id received');
// retrieve document source from ES and validate
$document = $this->getDocSourceFromElastic(
$client,
$this->options['index'],
null,
$documentId
);
$this->assertEquals($expected, $document);
// remove test index from ES
$client->request("/{$this->options['index']}", Request::DELETE);
}
/**
* Return last created document id from ES response
* @param Response $response Elastica Response object
*/
protected function getCreatedDocId(Response $response): ?string
{
$data = $response->getData();
if (!empty($data['items'][0]['index']['_id'])) {
return $data['items'][0]['index']['_id'];
}
var_dump('Unexpected response: ', $data);
return null;
}
/**
* Retrieve document by id from Elasticsearch
* @param Client $client Elastica client
* @param ?string $type
*/
protected function getDocSourceFromElastic(Client $client, string $index, $type, string $documentId): array
{
if ($type === null) {
$path = "/{$index}/_doc/{$documentId}";
} else {
$path = "/{$index}/{$type}/{$documentId}";
}
$resp = $client->request($path, Request::GET);
$data = $resp->getData();
if (!empty($data['_source'])) {
return $data['_source'];
}
return [];
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/InsightOpsHandlerTest.php | tests/Monolog/Handler/InsightOpsHandlerTest.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 PHPUnit\Framework\MockObject\MockObject;
/**
* @author Robert Kaufmann III <rok3@rok3.me>
* @author Gabriel Machado <gabriel.ms1@hotmail.com>
*/
class InsightOpsHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @var resource
*/
private $resource;
private InsightOpsHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->resource);
unset($this->handler);
}
public function testWriteContent()
{
$this->createHandler();
$this->handler->handle($this->getRecord(Level::Critical, 'Critical write test'));
fseek($this->resource, 0);
$content = fread($this->resource, 1024);
$this->assertMatchesRegularExpression('/testToken \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}\+00:00\] test.CRITICAL: Critical write test/', $content);
}
public function testWriteBatchContent()
{
$this->createHandler();
$this->handler->handleBatch($this->getMultipleRecords());
fseek($this->resource, 0);
$content = fread($this->resource, 1024);
$this->assertMatchesRegularExpression('/(testToken \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}\+00:00\] .* \[\] \[\]\n){3}/', $content);
}
private function createHandler()
{
$useSSL = \extension_loaded('openssl');
$args = ['testToken', 'us', $useSSL, Level::Debug, true];
$this->resource = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder(InsightOpsHandler::class)
->onlyMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
->setConstructorArgs($args)
->getMock();
$reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setValue($this->handler, 'localhost:1234');
$this->handler->expects($this->any())
->method('fsockopen')
->willReturn($this->resource);
$this->handler->expects($this->any())
->method('streamSetTimeout')
->willReturn(true);
$this->handler->expects($this->any())
->method('closeSocket');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/SocketHandlerTest.php | tests/Monolog/Handler/SocketHandlerTest.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 PHPUnit\Framework\MockObject\MockObject;
/**
* @author Pablo de Leon Belloc <pablolb@gmail.com>
*/
class SocketHandlerTest extends \Monolog\Test\MonologTestCase
{
private SocketHandler&MockObject $handler;
/**
* @var resource
*/
private $res;
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
unset($this->handler);
}
public function testInvalidHostname()
{
$this->expectException(\UnexpectedValueException::class);
$handler = $this->createHandler('garbage://here');
$handler->handle($this->getRecord(Level::Warning, 'data'));
}
public function testBadConnectionTimeout()
{
$this->expectException(\InvalidArgumentException::class);
$handler = $this->createHandler('localhost:1234');
$handler->setConnectionTimeout(-1);
}
public function testSetConnectionTimeout()
{
$handler = $this->createHandler('localhost:1234');
$handler->setConnectionTimeout(10.1);
$this->assertEquals(10.1, $handler->getConnectionTimeout());
}
public function testBadTimeout()
{
$this->expectException(\InvalidArgumentException::class);
$handler = $this->createHandler('localhost:1234');
$handler->setTimeout(-1);
}
public function testSetTimeout()
{
$handler = $this->createHandler('localhost:1234');
$handler->setTimeout(10.25);
$this->assertEquals(10.25, $handler->getTimeout());
}
public function testSetWritingTimeout()
{
$handler = $this->createHandler('localhost:1234');
$handler->setWritingTimeout(10.25);
$this->assertEquals(10.25, $handler->getWritingTimeout());
}
public function testSetChunkSize()
{
$handler = $this->createHandler('localhost:1234');
$handler->setChunkSize(1025);
$this->assertEquals(1025, $handler->getChunkSize());
}
public function testSetConnectionString()
{
$handler = $this->createHandler('tcp://localhost:9090');
$this->assertEquals('tcp://localhost:9090', $handler->getConnectionString());
}
public function testExceptionIsThrownOnFsockopenError()
{
$this->setMockHandler(['fsockopen']);
$this->handler->expects($this->once())
->method('fsockopen')
->willReturn(false);
$this->expectException(\UnexpectedValueException::class);
$this->writeRecord('Hello world');
}
public function testExceptionIsThrownOnPfsockopenError()
{
$this->setMockHandler(['pfsockopen']);
$this->handler->expects($this->once())
->method('pfsockopen')
->willReturn(false);
$this->handler->setPersistent(true);
$this->expectException(\UnexpectedValueException::class);
$this->writeRecord('Hello world');
}
public function testExceptionIsThrownIfCannotSetTimeout()
{
$this->setMockHandler(['streamSetTimeout']);
$this->handler->expects($this->once())
->method('streamSetTimeout')
->willReturn(false);
$this->expectException(\UnexpectedValueException::class);
$this->writeRecord('Hello world');
}
public function testExceptionIsThrownIfCannotSetChunkSize()
{
$this->setMockHandler(['streamSetChunkSize']);
$this->handler->setChunkSize(8192);
$this->handler->expects($this->once())
->method('streamSetChunkSize')
->willReturn(false);
$this->expectException(\UnexpectedValueException::class);
$this->writeRecord('Hello world');
}
public function testWriteFailsOnIfFwriteReturnsFalse()
{
$this->setMockHandler(['fwrite']);
$callback = function ($arg) {
$map = [
'Hello world' => 6,
'world' => false,
];
return $map[$arg];
};
$this->handler->expects($this->exactly(2))
->method('fwrite')
->willReturnCallback($callback);
$this->expectException(\RuntimeException::class);
$this->writeRecord('Hello world');
}
public function testWriteFailsIfStreamTimesOut()
{
$this->setMockHandler(['fwrite', 'streamGetMetadata']);
$callback = function ($arg) {
$map = [
'Hello world' => 6,
'world' => 5,
];
return $map[$arg];
};
$this->handler->expects($this->exactly(1))
->method('fwrite')
->willReturnCallback($callback);
$this->handler->expects($this->exactly(1))
->method('streamGetMetadata')
->willReturn(['timed_out' => true]);
$this->expectException(\RuntimeException::class);
$this->writeRecord('Hello world');
}
public function testWriteFailsOnIncompleteWrite()
{
$this->setMockHandler(['fwrite', 'streamGetMetadata']);
$res = $this->res;
$callback = function ($string) use ($res) {
fclose($res);
return \strlen('Hello');
};
$this->handler->expects($this->exactly(1))
->method('fwrite')
->willReturnCallback($callback);
$this->handler->expects($this->exactly(1))
->method('streamGetMetadata')
->willReturn(['timed_out' => false]);
$this->expectException(\RuntimeException::class);
$this->writeRecord('Hello world');
}
public function testWriteWithMemoryFile()
{
$this->setMockHandler();
$this->writeRecord('test1');
$this->writeRecord('test2');
$this->writeRecord('test3');
fseek($this->res, 0);
$this->assertEquals('test1test2test3', fread($this->res, 1024));
}
public function testWriteWithMock()
{
$this->setMockHandler(['fwrite']);
$callback = function ($arg) {
$map = [
'Hello world' => 6,
'world' => 5,
];
return $map[$arg];
};
$this->handler->expects($this->exactly(2))
->method('fwrite')
->willReturnCallback($callback);
$this->writeRecord('Hello world');
}
public function testClose()
{
$this->setMockHandler();
$this->writeRecord('Hello world');
$this->assertIsResource($this->res);
$this->handler->close();
$this->assertFalse(\is_resource($this->res), "Expected resource to be closed after closing handler");
}
public function testCloseDoesNotClosePersistentSocket()
{
$this->setMockHandler();
$this->handler->setPersistent(true);
$this->writeRecord('Hello world');
$this->assertTrue(\is_resource($this->res));
$this->handler->close();
$this->assertTrue(\is_resource($this->res));
}
public function testAvoidInfiniteLoopWhenNoDataIsWrittenForAWritingTimeoutSeconds()
{
$this->setMockHandler(['fwrite', 'streamGetMetadata']);
$this->handler->expects($this->any())
->method('fwrite')
->willReturn(0);
$this->handler->expects($this->any())
->method('streamGetMetadata')
->willReturn(['timed_out' => false]);
$this->handler->setWritingTimeout(1);
$this->expectException(\RuntimeException::class);
$this->writeRecord('Hello world');
}
private function createHandler(string $connectionString): SocketHandler
{
$handler = new SocketHandler($connectionString);
$handler->setFormatter($this->getIdentityFormatter());
return $handler;
}
private function writeRecord($string)
{
$this->handler->handle($this->getRecord(Level::Warning, $string));
}
private function setMockHandler(array $methods = [])
{
$this->res = fopen('php://memory', 'a');
$defaultMethods = ['fsockopen', 'pfsockopen', 'streamSetTimeout', 'streamSetChunkSize'];
$newMethods = array_diff($methods, $defaultMethods);
$finalMethods = array_merge($defaultMethods, $newMethods);
$this->handler = $this->getMockBuilder('Monolog\Handler\SocketHandler')
->onlyMethods($finalMethods)
->setConstructorArgs(['localhost:1234'])
->getMock();
if (!\in_array('fsockopen', $methods)) {
$this->handler->expects($this->any())
->method('fsockopen')
->willReturn($this->res);
}
if (!\in_array('pfsockopen', $methods)) {
$this->handler->expects($this->any())
->method('pfsockopen')
->willReturn($this->res);
}
if (!\in_array('streamSetTimeout', $methods)) {
$this->handler->expects($this->any())
->method('streamSetTimeout')
->willReturn(true);
}
if (!\in_array('streamSetChunkSize', $methods)) {
$this->handler->expects($this->any())
->method('streamSetChunkSize')
->willReturn(8192);
}
$this->handler->setFormatter($this->getIdentityFormatter());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/TelegramBotHandlerTest.php | tests/Monolog/Handler/TelegramBotHandlerTest.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 PHPUnit\Framework\MockObject\MockObject;
/**
* @author Mazur Alexandr <alexandrmazur96@gmail.com>
* @link https://core.telegram.org/bots/api
*/
class TelegramBotHandlerTest extends \Monolog\Test\MonologTestCase
{
private TelegramBotHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->handler);
}
public function testSendTelegramRequest(): void
{
$this->createHandler();
$this->handler->handle($this->getRecord());
}
private function createHandler(
string $apiKey = 'testKey',
string $channel = 'testChannel',
string $parseMode = 'Markdown',
bool $disableWebPagePreview = false,
bool $disableNotification = true,
int $topic = 1
): void {
$constructorArgs = [$apiKey, $channel, Level::Debug, true, $parseMode, $disableWebPagePreview, $disableNotification, $topic];
$this->handler = $this->getMockBuilder(TelegramBotHandler::class)
->setConstructorArgs($constructorArgs)
->onlyMethods(['send'])
->getMock();
$this->handler->expects($this->atLeast(1))
->method('send');
}
public function testSetInvalidParseMode(): void
{
$this->expectException(\InvalidArgumentException::class);
$handler = new TelegramBotHandler('testKey', 'testChannel');
$handler->setParseMode('invalid parse mode');
}
public function testSetParseMode(): void
{
$handler = new TelegramBotHandler('testKey', 'testChannel');
$handler->setParseMode('HTML');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php | tests/Monolog/Handler/WhatFailureGroupHandlerTest.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\LogRecord;
use Monolog\Level;
class WhatFailureGroupHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\WhatFailureGroupHandler::__construct
*/
public function testConstructorOnlyTakesHandler()
{
$this->expectException(\InvalidArgumentException::class);
new WhatFailureGroupHandler([new TestHandler(), "foo"]);
}
/**
* @covers Monolog\Handler\WhatFailureGroupHandler::__construct
* @covers Monolog\Handler\WhatFailureGroupHandler::handle
*/
public function testHandle()
{
$testHandlers = [new TestHandler(), new TestHandler()];
$handler = new WhatFailureGroupHandler($testHandlers);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(2, $test->getRecords());
}
}
/**
* @covers Monolog\Handler\WhatFailureGroupHandler::handleBatch
*/
public function testHandleBatch()
{
$testHandlers = [new TestHandler(), new TestHandler()];
$handler = new WhatFailureGroupHandler($testHandlers);
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(2, $test->getRecords());
}
}
/**
* @covers Monolog\Handler\WhatFailureGroupHandler::isHandling
*/
public function testIsHandling()
{
$testHandlers = [new TestHandler(Level::Error), new TestHandler(Level::Warning)];
$handler = new WhatFailureGroupHandler($testHandlers);
$this->assertTrue($handler->isHandling($this->getRecord(Level::Error)));
$this->assertTrue($handler->isHandling($this->getRecord(Level::Warning)));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Debug)));
}
/**
* @covers Monolog\Handler\WhatFailureGroupHandler::handle
*/
public function testHandleUsesProcessors()
{
$test = new TestHandler();
$handler = new WhatFailureGroupHandler([$test]);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasWarningRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
}
/**
* @covers Monolog\Handler\WhatFailureGroupHandler::handleBatch
*/
public function testHandleBatchUsesProcessors()
{
$testHandlers = [new TestHandler(), new TestHandler()];
$handler = new WhatFailureGroupHandler($testHandlers);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->pushProcessor(function ($record) {
$record->extra['foo2'] = true;
return $record;
});
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(2, $test->getRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
$this->assertTrue($records[1]['extra']['foo']);
$this->assertTrue($records[0]['extra']['foo2']);
$this->assertTrue($records[1]['extra']['foo2']);
}
}
/**
* @covers Monolog\Handler\WhatFailureGroupHandler::handle
*/
public function testHandleException()
{
$test = new TestHandler();
$exception = new ExceptionTestHandler();
$handler = new WhatFailureGroupHandler([$exception, $test, $exception]);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasWarningRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
}
public function testProcessorsDoNotInterfereBetweenHandlers()
{
$t1 = new TestHandler();
$t2 = new TestHandler();
$handler = new WhatFailureGroupHandler([$t1, $t2]);
$t1->pushProcessor(function (LogRecord $record) {
$record->extra['foo'] = 'bar';
return $record;
});
$handler->handle($this->getRecord());
self::assertSame([], $t2->getRecords()[0]->extra);
}
public function testProcessorsDoNotInterfereBetweenHandlersWithBatch()
{
$t1 = new TestHandler();
$t2 = new TestHandler();
$handler = new WhatFailureGroupHandler([$t1, $t2]);
$t1->pushProcessor(function (LogRecord $record) {
$record->extra['foo'] = 'bar';
return $record;
});
$handler->handleBatch([$this->getRecord()]);
self::assertSame([], $t2->getRecords()[0]->extra);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/PHPConsoleHandlerTest.php | tests/Monolog/Handler/PHPConsoleHandlerTest.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 Exception;
use Monolog\ErrorHandler;
use Monolog\Level;
use Monolog\Logger;
use PhpConsole\Connector;
use PhpConsole\Dispatcher\Debug as DebugDispatcher;
use PhpConsole\Dispatcher\Errors as ErrorDispatcher;
use PhpConsole\Handler as VendorPhpConsoleHandler;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\WithoutErrorHandler;
use PHPUnit\Framework\MockObject\MockObject;
/**
* @covers Monolog\Handler\PHPConsoleHandler
* @author Sergey Barbushin https://www.linkedin.com/in/barbushin
*/
class PHPConsoleHandlerTest extends \Monolog\Test\MonologTestCase
{
protected Connector&MockObject $connector;
protected DebugDispatcher&MockObject $debugDispatcher;
protected ErrorDispatcher&MockObject $errorDispatcher;
protected function setUp(): void
{
// suppress warnings until https://github.com/barbushin/php-console/pull/173 is merged
$previous = error_reporting(0);
if (!class_exists('PhpConsole\Connector')) {
error_reporting($previous);
$this->markTestSkipped('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
}
if (!class_exists('PhpConsole\Handler')) {
error_reporting($previous);
$this->markTestSkipped('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
}
error_reporting($previous);
$this->connector = $this->initConnectorMock();
$this->debugDispatcher = $this->initDebugDispatcherMock($this->connector);
$this->connector->setDebugDispatcher($this->debugDispatcher);
$this->errorDispatcher = $this->initErrorDispatcherMock($this->connector);
$this->connector->setErrorsDispatcher($this->errorDispatcher);
}
public function tearDown(): void
{
parent::tearDown();
unset($this->connector, $this->debugDispatcher, $this->errorDispatcher);
}
protected function initDebugDispatcherMock(Connector $connector)
{
return $this->getMockBuilder('PhpConsole\Dispatcher\Debug')
->disableOriginalConstructor()
->onlyMethods(['dispatchDebug'])
->setConstructorArgs([$connector, $connector->getDumper()])
->getMock();
}
protected function initErrorDispatcherMock(Connector $connector)
{
return $this->getMockBuilder('PhpConsole\Dispatcher\Errors')
->disableOriginalConstructor()
->onlyMethods(['dispatchError', 'dispatchException'])
->setConstructorArgs([$connector, $connector->getDumper()])
->getMock();
}
protected function initConnectorMock()
{
$connector = $this->getMockBuilder('PhpConsole\Connector')
->disableOriginalConstructor()
->onlyMethods([
'sendMessage',
'onShutDown',
'isActiveClient',
'setSourcesBasePath',
'setServerEncoding',
'setPassword',
'enableSslOnlyMode',
'setAllowedIpMasks',
'setHeadersLimit',
'startEvalRequestsListener',
])
->getMock();
$connector->expects($this->any())
->method('isActiveClient')
->willReturn(true);
return $connector;
}
protected function getHandlerDefaultOption($name)
{
$handler = new PHPConsoleHandler([], $this->connector);
$options = $handler->getOptions();
return $options[$name];
}
protected function initLogger($handlerOptions = [], $level = Level::Debug)
{
return new Logger('test', [
new PHPConsoleHandler($handlerOptions, $this->connector, $level),
]);
}
public function testInitWithDefaultConnector()
{
$handler = new PHPConsoleHandler();
$this->assertEquals(spl_object_hash(Connector::getInstance()), spl_object_hash($handler->getConnector()));
}
public function testInitWithCustomConnector()
{
$handler = new PHPConsoleHandler([], $this->connector);
$this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector()));
}
public function testDebug()
{
$this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with($this->equalTo('test'));
$this->initLogger()->debug('test');
}
public function testDebugContextInMessage()
{
$message = 'test';
$tag = 'tag';
$context = [$tag, 'custom' => mt_rand()];
$expectedMessage = $message . ' ' . json_encode(\array_slice($context, 1));
$this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
$this->equalTo($expectedMessage),
$this->equalTo($tag)
);
$this->initLogger()->debug($message, $context);
}
public function testDebugTags($tagsContextKeys = null)
{
$expectedTags = mt_rand();
$logger = $this->initLogger($tagsContextKeys ? ['debugTagsKeysInContext' => $tagsContextKeys] : []);
if (!$tagsContextKeys) {
$tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext');
}
foreach ($tagsContextKeys as $key) {
$debugDispatcher = $this->initDebugDispatcherMock($this->connector);
$debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
$this->anything(),
$this->equalTo($expectedTags)
);
$this->connector->setDebugDispatcher($debugDispatcher);
$logger->debug('test', [$key => $expectedTags]);
}
}
#[WithoutErrorHandler]
public function testError($classesPartialsTraceIgnore = null)
{
$code = E_USER_NOTICE;
$message = 'message';
$file = __FILE__;
$line = __LINE__;
$this->errorDispatcher->expects($this->once())->method('dispatchError')->with(
$this->equalTo($code),
$this->equalTo($message),
$this->equalTo($file),
$this->equalTo($line),
$classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore'))
);
$errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false, false);
$errorHandler->registerErrorHandler([], false, E_USER_WARNING);
$reflMethod = new \ReflectionMethod($errorHandler, 'handleError');
$reflMethod->invoke($errorHandler, $code, $message, $file, $line);
restore_error_handler();
}
public function testException()
{
$e = new Exception();
$this->errorDispatcher->expects($this->once())->method('dispatchException')->with(
$this->equalTo($e)
);
$handler = $this->initLogger();
$handler->log(
\Psr\Log\LogLevel::ERROR,
\sprintf('Uncaught Exception %s: "%s" at %s line %s', \get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
['exception' => $e]
);
}
public function testWrongOptionsThrowsException()
{
$this->expectException(\Exception::class);
new PHPConsoleHandler(['xxx' => 1]);
}
public function testOptionEnabled()
{
$this->debugDispatcher->expects($this->never())->method('dispatchDebug');
$this->initLogger(['enabled' => false])->debug('test');
}
public function testOptionDebugTagsKeysInContext()
{
$this->testDebugTags(['key1', 'key2']);
}
public function testOptionUseOwnErrorsAndExceptionsHandler()
{
$this->initLogger(['useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true]);
$this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleError'], set_error_handler(function () {
}));
$this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleException'], set_exception_handler(function () {
}));
restore_exception_handler();
restore_error_handler();
restore_exception_handler();
restore_error_handler();
}
public static function provideConnectorMethodsOptionsSets()
{
return [
['sourcesBasePath', 'setSourcesBasePath', __DIR__],
['serverEncoding', 'setServerEncoding', 'cp1251'],
['password', 'setPassword', '******'],
['enableSslOnlyMode', 'enableSslOnlyMode', true, false],
['ipMasks', 'setAllowedIpMasks', ['127.0.0.*']],
['headersLimit', 'setHeadersLimit', 2500],
['enableEvalListener', 'startEvalRequestsListener', true, false],
];
}
#[DataProvider('provideConnectorMethodsOptionsSets')]
public function testOptionCallsConnectorMethod($option, $method, $value, $isArgument = true)
{
$expectCall = $this->connector->expects($this->once())->method($method);
if ($isArgument) {
$expectCall->with($value);
}
new PHPConsoleHandler([$option => $value], $this->connector);
}
public function testOptionDetectDumpTraceAndSource()
{
new PHPConsoleHandler(['detectDumpTraceAndSource' => true], $this->connector);
$this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource);
}
public static function provideDumperOptionsValues()
{
return [
['dumperLevelLimit', 'levelLimit', 1001],
['dumperItemsCountLimit', 'itemsCountLimit', 1002],
['dumperItemSizeLimit', 'itemSizeLimit', 1003],
['dumperDumpSizeLimit', 'dumpSizeLimit', 1004],
['dumperDetectCallbacks', 'detectCallbacks', true],
];
}
#[DataProvider('provideDumperOptionsValues')]
public function testDumperOptions($option, $dumperProperty, $value)
{
new PHPConsoleHandler([$option => $value], $this->connector);
$this->assertEquals($value, $this->connector->getDumper()->$dumperProperty);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/NullHandlerTest.php | tests/Monolog/Handler/NullHandlerTest.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;
/**
* @covers Monolog\Handler\NullHandler::handle
*/
class NullHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testHandle()
{
$handler = new NullHandler();
$this->assertTrue($handler->handle($this->getRecord()));
}
public function testHandleLowerLevelRecord()
{
$handler = new NullHandler(Level::Warning);
$this->assertFalse($handler->handle($this->getRecord(Level::Debug)));
}
public function testSerializeRestorePrivate()
{
$handler = new NullHandler(Level::Warning);
self::assertFalse($handler->handle($this->getRecord(Level::Debug)));
self::assertTrue($handler->handle($this->getRecord(Level::Warning)));
$handler = unserialize(serialize($handler));
self::assertFalse($handler->handle($this->getRecord(Level::Debug)));
self::assertTrue($handler->handle($this->getRecord(Level::Warning)));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/RollbarHandlerTest.php | tests/Monolog/Handler/RollbarHandlerTest.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 Exception;
use Monolog\Level;
use PHPUnit\Framework\MockObject\MockObject;
use Rollbar\RollbarLogger;
/**
* @author Erik Johansson <erik.pm.johansson@gmail.com>
* @see https://rollbar.com/docs/notifier/rollbar-php/
*
* @coversDefaultClass Monolog\Handler\RollbarHandler
*
* @requires function \Rollbar\RollbarLogger::__construct
*/
class RollbarHandlerTest extends \Monolog\Test\MonologTestCase
{
private RollbarLogger&MockObject $rollbarLogger;
private array $reportedExceptionArguments;
protected function setUp(): void
{
parent::setUp();
$this->setupRollbarLoggerMock();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->rollbarLogger, $this->reportedExceptionArguments);
}
/**
* When reporting exceptions to Rollbar the
* level has to be set in the payload data
*/
public function testExceptionLogLevel()
{
$handler = $this->createHandler();
$handler->handle($this->getRecord(Level::Debug, context: ['exception' => $e = new Exception()]));
$this->assertEquals('debug', $this->reportedExceptionArguments['payload']['level']);
$this->assertSame($e, $this->reportedExceptionArguments['context']);
}
private function setupRollbarLoggerMock()
{
$config = [
'access_token' => 'ad865e76e7fb496fab096ac07b1dbabb',
'environment' => 'test',
];
$this->rollbarLogger = $this->getMockBuilder(RollbarLogger::class)
->setConstructorArgs([$config])
->onlyMethods(['log'])
->getMock();
$this->rollbarLogger
->expects($this->any())
->method('log')
->willReturnCallback(function ($exception, $context, $payload) {
$this->reportedExceptionArguments = compact('exception', 'context', 'payload');
});
}
private function createHandler(): RollbarHandler
{
return new RollbarHandler($this->rollbarLogger, Level::Debug);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/SamplingHandlerTest.php | tests/Monolog/Handler/SamplingHandlerTest.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;
/**
* @covers Monolog\Handler\SamplingHandler::handle
*/
class SamplingHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testHandle()
{
$testHandler = new TestHandler();
$handler = new SamplingHandler($testHandler, 2);
for ($i = 0; $i < 10000; $i++) {
$handler->handle($this->getRecord());
}
$count = \count($testHandler->getRecords());
// $count should be half of 10k, so between 4k and 6k
$this->assertLessThan(6000, $count);
$this->assertGreaterThan(4000, $count);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/HandlerWrapperTest.php | tests/Monolog/Handler/HandlerWrapperTest.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 PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\MockObject\MockObject;
/**
* @author Alexey Karapetov <alexey@karapetov.com>
*/
class HandlerWrapperTest extends \Monolog\Test\MonologTestCase
{
private HandlerWrapper $wrapper;
private HandlerInterface&MockObject $handler;
public function setUp(): void
{
parent::setUp();
$this->handler = $this->createMock(HandlerInterface::class);
$this->wrapper = new HandlerWrapper($this->handler);
}
public function tearDown(): void
{
parent::tearDown();
unset($this->wrapper);
unset($this->handler);
}
public static function trueFalseDataProvider(): array
{
return [
[true],
[false],
];
}
#[DataProvider('trueFalseDataProvider')]
public function testIsHandling(bool $result)
{
$record = $this->getRecord();
$this->handler->expects($this->once())
->method('isHandling')
->with($record)
->willReturn($result);
$this->assertEquals($result, $this->wrapper->isHandling($record));
}
#[DataProvider('trueFalseDataProvider')]
public function testHandle(bool $result)
{
$record = $this->getRecord();
$this->handler->expects($this->once())
->method('handle')
->with($record)
->willReturn($result);
$this->assertEquals($result, $this->wrapper->handle($record));
}
#[DataProvider('trueFalseDataProvider')]
public function testHandleBatch(bool $result)
{
$records = $this->getMultipleRecords();
$this->handler->expects($this->once())
->method('handleBatch')
->with($records);
$this->wrapper->handleBatch($records);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/LogEntriesHandlerTest.php | tests/Monolog/Handler/LogEntriesHandlerTest.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 PHPUnit\Framework\MockObject\MockObject;
/**
* @author Robert Kaufmann III <rok3@rok3.me>
*/
class LogEntriesHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @var resource
*/
private $res;
private LogEntriesHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
unset($this->handler);
}
public function testWriteContent()
{
$this->createHandler();
$this->handler->handle($this->getRecord(Level::Critical, 'Critical write test'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/testToken \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}\+00:00\] test.CRITICAL: Critical write test/', $content);
}
public function testWriteBatchContent()
{
$records = [
$this->getRecord(),
$this->getRecord(),
$this->getRecord(),
];
$this->createHandler();
$this->handler->handleBatch($records);
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/(testToken \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}\+00:00\] .* \[\] \[\]\n){3}/', $content);
}
private function createHandler()
{
$useSSL = \extension_loaded('openssl');
$args = ['testToken', $useSSL, Level::Debug, true];
$this->res = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder('Monolog\Handler\LogEntriesHandler')
->setConstructorArgs($args)
->onlyMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
->getMock();
$reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setValue($this->handler, 'localhost:1234');
$this->handler->expects($this->any())
->method('fsockopen')
->willReturn($this->res);
$this->handler->expects($this->any())
->method('streamSetTimeout')
->willReturn(true);
$this->handler->expects($this->any())
->method('closeSocket');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/TestHandlerTest.php | tests/Monolog/Handler/TestHandlerTest.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 PHPUnit\Framework\Attributes\DataProvider;
/**
* @covers Monolog\Handler\TestHandler
*/
class TestHandlerTest extends \Monolog\Test\MonologTestCase
{
#[DataProvider('methodProvider')]
public function testHandler($method, Level $level)
{
$handler = new TestHandler;
$record = $this->getRecord($level, 'test'.$method);
$this->assertFalse($handler->hasRecords($level));
$this->assertFalse($handler->hasRecord($record->message, $level));
$this->assertFalse($handler->{'has'.$method}($record->message), 'has'.$method);
$this->assertFalse($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains');
$this->assertFalse($handler->{'has'.$method.'ThatPasses'}(function ($rec) {
return true;
}), 'has'.$method.'ThatPasses');
$this->assertFalse($handler->{'has'.$method.'ThatMatches'}('/test\w+/'));
$this->assertFalse($handler->{'has'.$method.'Records'}(), 'has'.$method.'Records');
$handler->handle($record);
$this->assertFalse($handler->{'has'.$method}('bar'), 'has'.$method);
$this->assertTrue($handler->hasRecords($level));
$this->assertTrue($handler->hasRecord($record->message, $level));
$this->assertTrue($handler->{'has'.$method}($record->message), 'has'.$method);
$this->assertTrue($handler->{'has'.$method}('test'.$method), 'has'.$method);
$this->assertTrue($handler->{'has'.$method.'ThatContains'}('test'), 'has'.$method.'ThatContains');
$this->assertTrue($handler->{'has'.$method.'ThatPasses'}(function ($rec) {
return true;
}), 'has'.$method.'ThatPasses');
$this->assertTrue($handler->{'has'.$method.'ThatMatches'}('/test\w+/'));
$this->assertTrue($handler->{'has'.$method.'Records'}(), 'has'.$method.'Records');
$records = $handler->getRecords();
$records[0]->formatted = null;
$this->assertEquals([$record], $records);
}
public function testHandlerAssertEmptyContext()
{
$handler = new TestHandler;
$record = $this->getRecord(Level::Warning, 'test', []);
$this->assertFalse($handler->hasWarning([
'message' => 'test',
'context' => [],
]));
$handler->handle($record);
$this->assertTrue($handler->hasWarning([
'message' => 'test',
'context' => [],
]));
$this->assertFalse($handler->hasWarning([
'message' => 'test',
'context' => [
'foo' => 'bar',
],
]));
}
public function testHandlerAssertNonEmptyContext()
{
$handler = new TestHandler;
$record = $this->getRecord(Level::Warning, 'test', ['foo' => 'bar']);
$this->assertFalse($handler->hasWarning([
'message' => 'test',
'context' => [
'foo' => 'bar',
],
]));
$handler->handle($record);
$this->assertTrue($handler->hasWarning([
'message' => 'test',
'context' => [
'foo' => 'bar',
],
]));
$this->assertFalse($handler->hasWarning([
'message' => 'test',
'context' => [],
]));
}
public static function methodProvider()
{
return [
['Emergency', Level::Emergency],
['Alert' , Level::Alert],
['Critical' , Level::Critical],
['Error' , Level::Error],
['Warning' , Level::Warning],
['Info' , Level::Info],
['Notice' , Level::Notice],
['Debug' , Level::Debug],
];
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/DynamoDbHandlerTest.php | tests/Monolog/Handler/DynamoDbHandlerTest.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 Aws\DynamoDb\DynamoDbClient;
use PHPUnit\Framework\MockObject\MockObject;
class DynamoDbHandlerTest extends \Monolog\Test\MonologTestCase
{
private DynamoDbClient&MockObject $client;
private bool $isV3;
public function setUp(): void
{
if (!class_exists(DynamoDbClient::class)) {
$this->markTestSkipped('aws/aws-sdk-php not installed');
}
$this->isV3 = \defined('Aws\Sdk::VERSION') && version_compare(\Aws\Sdk::VERSION, '3.0', '>=');
$implementedMethods = ['__call'];
$clientMockBuilder = $this->getMockBuilder(DynamoDbClient::class)
->onlyMethods($implementedMethods)
->disableOriginalConstructor();
$this->client = $clientMockBuilder->getMock();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->client);
}
public function testGetFormatter()
{
$handler = new DynamoDbHandler($this->client, 'foo');
$this->assertInstanceOf('Monolog\Formatter\ScalarFormatter', $handler->getFormatter());
}
public function testHandle()
{
$record = $this->getRecord();
$formatter = $this->createMock('Monolog\Formatter\FormatterInterface');
$formatted = ['foo' => 1, 'bar' => 2];
$handler = new DynamoDbHandler($this->client, 'foo');
$handler->setFormatter($formatter);
if ($this->isV3) {
$expFormatted = ['foo' => ['N' => 1], 'bar' => ['N' => 2]];
} else {
$expFormatted = $formatted;
}
$formatter
->expects($this->once())
->method('format')
->with($record)
->willReturn($formatted);
$this->client
->expects($this->once())
->method('__call')
->with('putItem', [[
'TableName' => 'foo',
'Item' => $expFormatted,
]]);
$handler->handle($record);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php | tests/Monolog/Handler/DoctrineCouchDBHandlerTest.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;
class DoctrineCouchDBHandlerTest extends \Monolog\Test\MonologTestCase
{
protected function setUp(): void
{
if (!class_exists('Doctrine\CouchDB\CouchDBClient')) {
$this->markTestSkipped('The "doctrine/couchdb" package is not installed');
}
}
public function testHandle()
{
$client = $this->getMockBuilder('Doctrine\\CouchDB\\CouchDBClient')
->onlyMethods(['postDocument'])
->disableOriginalConstructor()
->getMock();
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$expected = [
'message' => 'test',
'context' => ['data' => ['stdClass' => []], 'foo' => 34],
'level' => Level::Warning->value,
'level_name' => 'WARNING',
'channel' => 'test',
'datetime' => (string) $record->datetime,
'extra' => [],
];
$client->expects($this->once())
->method('postDocument')
->with($expected);
$handler = new DoctrineCouchDBHandler($client);
$handler->handle($record);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/AbstractHandlerTest.php | tests/Monolog/Handler/AbstractHandlerTest.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;
class AbstractHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\AbstractHandler::__construct
* @covers Monolog\Handler\AbstractHandler::getLevel
* @covers Monolog\Handler\AbstractHandler::setLevel
* @covers Monolog\Handler\AbstractHandler::getBubble
* @covers Monolog\Handler\AbstractHandler::setBubble
*/
public function testConstructAndGetSet()
{
$handler = $this->getMockBuilder('Monolog\Handler\AbstractHandler')->setConstructorArgs([Level::Warning, false])->onlyMethods(['handle'])->getMock();
$this->assertEquals(Level::Warning, $handler->getLevel());
$this->assertEquals(false, $handler->getBubble());
$handler->setLevel(Level::Error);
$handler->setBubble(true);
$this->assertEquals(Level::Error, $handler->getLevel());
$this->assertEquals(true, $handler->getBubble());
}
/**
* @covers Monolog\Handler\AbstractHandler::handleBatch
*/
public function testHandleBatch()
{
$handler = $this->createPartialMock('Monolog\Handler\AbstractHandler', ['handle']);
$handler->expects($this->exactly(2))
->method('handle');
$handler->handleBatch([$this->getRecord(), $this->getRecord()]);
}
/**
* @covers Monolog\Handler\AbstractHandler::isHandling
*/
public function testIsHandling()
{
$handler = $this->getMockBuilder('Monolog\Handler\AbstractHandler')->setConstructorArgs([Level::Warning, false])->onlyMethods(['handle'])->getMock();
$this->assertTrue($handler->isHandling($this->getRecord()));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Debug)));
}
/**
* @covers Monolog\Handler\AbstractHandler::__construct
*/
public function testHandlesPsrStyleLevels()
{
$handler = $this->getMockBuilder('Monolog\Handler\AbstractHandler')->setConstructorArgs(['warning', false])->onlyMethods(['handle'])->getMock();
$this->assertFalse($handler->isHandling($this->getRecord(Level::Debug)));
$handler->setLevel('debug');
$this->assertTrue($handler->isHandling($this->getRecord(Level::Debug)));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/PushoverHandlerTest.php | tests/Monolog/Handler/PushoverHandlerTest.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 PHPUnit\Framework\MockObject\MockObject;
/**
* Almost all examples (expected header, titles, messages) taken from
* https://www.pushover.net/api
* @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com>
* @see https://www.pushover.net/api
*/
class PushoverHandlerTest extends \Monolog\Test\MonologTestCase
{
/** @var resource */
private $res;
private PushoverHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
unset($this->handler);
}
public function testWriteHeader()
{
$this->createHandler();
$this->handler->setHighPriorityLevel(Level::Emergency); // skip priority notifications
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/POST \/1\/messages.json HTTP\/1.1\\r\\nHost: api.pushover.net\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
return $content;
}
/**
* @depends testWriteHeader
*/
public function testWriteContent($content)
{
$this->assertMatchesRegularExpression('/token=myToken&user=myUser&message=test1&title=Monolog×tamp=\d{10}$/', $content);
}
public function testWriteWithComplexTitle()
{
$this->createHandler('myToken', 'myUser', 'Backup finished - SQL1');
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/title=Backup\+finished\+-\+SQL1/', $content);
}
public function testWriteWithComplexMessage()
{
$this->createHandler();
$this->handler->setHighPriorityLevel(Level::Emergency); // skip priority notifications
$this->handler->handle($this->getRecord(Level::Critical, 'Backup of database "example" finished in 16 minutes.'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/message=Backup\+of\+database\+%22example%22\+finished\+in\+16\+minutes\./', $content);
}
public function testWriteWithTooLongMessage()
{
$message = str_pad('test', 520, 'a');
$this->createHandler();
$this->handler->setHighPriorityLevel(Level::Emergency); // skip priority notifications
$this->handler->handle($this->getRecord(Level::Critical, $message));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$expectedMessage = substr($message, 0, 505);
$this->assertMatchesRegularExpression('/message=' . $expectedMessage . '&title/', $content);
}
public function testWriteWithHighPriority()
{
$this->createHandler();
$this->handler->handle($this->getRecord(Level::Critical, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/token=myToken&user=myUser&message=test1&title=Monolog×tamp=\d{10}&priority=1$/', $content);
}
public function testWriteWithEmergencyPriority()
{
$this->createHandler();
$this->handler->handle($this->getRecord(Level::Emergency, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/token=myToken&user=myUser&message=test1&title=Monolog×tamp=\d{10}&priority=2&retry=30&expire=25200$/', $content);
}
public function testWriteToMultipleUsers()
{
$this->createHandler('myToken', ['userA', 'userB']);
$this->handler->handle($this->getRecord(Level::Emergency, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/token=myToken&user=userA&message=test1&title=Monolog×tamp=\d{10}&priority=2&retry=30&expire=25200POST/', $content);
$this->assertMatchesRegularExpression('/token=myToken&user=userB&message=test1&title=Monolog×tamp=\d{10}&priority=2&retry=30&expire=25200$/', $content);
}
private function createHandler($token = 'myToken', $user = 'myUser', $title = 'Monolog')
{
$constructorArgs = [$token, $user, $title];
$this->res = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder(PushoverHandler::class)
->setConstructorArgs($constructorArgs)
->onlyMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
->getMock();
$reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setValue($this->handler, 'localhost:1234');
$this->handler->expects($this->any())
->method('fsockopen')
->willReturn($this->res);
$this->handler->expects($this->any())
->method('streamSetTimeout')
->willReturn(true);
$this->handler->expects($this->any())
->method('closeSocket');
$this->handler->setFormatter($this->getIdentityFormatter());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/UdpSocketTest.php | tests/Monolog/Handler/UdpSocketTest.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\Handler\SyslogUdp\UdpSocket;
/**
* @requires extension sockets
*/
class UdpSocketTest extends \Monolog\Test\MonologTestCase
{
public function testWeDoNotTruncateShortMessages()
{
$socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
->onlyMethods(['send'])
->setConstructorArgs(['lol'])
->getMock();
$socket
->method('send')
->with("HEADER: The quick brown fox jumps over the lazy dog");
$socket->write("The quick brown fox jumps over the lazy dog", "HEADER: ");
}
public function testLongMessagesAreTruncated()
{
$socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
->onlyMethods(['send'])
->setConstructorArgs(['lol'])
->getMock();
$truncatedString = str_repeat("derp", 16254).'d';
$socket->expects($this->exactly(1))
->method('send')
->with("HEADER" . $truncatedString);
$longString = str_repeat("derp", 20000);
$socket->write($longString, "HEADER");
}
public function testDoubleCloseDoesNotError()
{
$socket = new UdpSocket('127.0.0.1', 514);
$socket->close();
$socket->close();
}
public function testWriteAfterCloseReopened()
{
$socket = new UdpSocket('127.0.0.1', 514);
$socket->close();
$socket->write('foo', "HEADER");
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/NewRelicHandlerTest.php | tests/Monolog/Handler/NewRelicHandlerTest.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\Formatter\LineFormatter;
use Monolog\Level;
class NewRelicHandlerTest extends \Monolog\Test\MonologTestCase
{
public static $appname;
public static $customParameters;
public static $transactionName;
public function setUp(): void
{
self::$appname = null;
self::$customParameters = [];
self::$transactionName = null;
}
public function testThehandlerThrowsAnExceptionIfTheNRExtensionIsNotLoaded()
{
$handler = new StubNewRelicHandlerWithoutExtension();
$this->expectException(MissingExtensionException::class);
$handler->handle($this->getRecord(Level::Error));
}
public function testThehandlerCanHandleTheRecord()
{
$handler = new StubNewRelicHandler();
$handler->handle($this->getRecord(Level::Error));
}
public function testThehandlerCanAddContextParamsToTheNewRelicTrace()
{
$handler = new StubNewRelicHandler();
$handler->handle($this->getRecord(Level::Error, 'log message', ['a' => 'b']));
$this->assertEquals(['context_a' => 'b'], self::$customParameters);
}
public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace()
{
$handler = new StubNewRelicHandler(Level::Error, true, self::$appname, true);
$handler->handle($this->getRecord(
Level::Error,
'log message',
['a' => ['key1' => 'value1', 'key2' => 'value2']]
));
$this->assertEquals(
['context_a_key1' => 'value1', 'context_a_key2' => 'value2'],
self::$customParameters
);
}
public function testThehandlerCanAddExtraParamsToTheNewRelicTrace()
{
$record = $this->getRecord(Level::Error, 'log message');
$record->extra = ['c' => 'd'];
$handler = new StubNewRelicHandler();
$handler->handle($record);
$this->assertEquals(['extra_c' => 'd'], self::$customParameters);
}
public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace()
{
$record = $this->getRecord(Level::Error, 'log message');
$record->extra = ['c' => ['key1' => 'value1', 'key2' => 'value2']];
$handler = new StubNewRelicHandler(Level::Error, true, self::$appname, true);
$handler->handle($record);
$this->assertEquals(
['extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'],
self::$customParameters
);
}
public function testThehandlerCanAddExtraContextAndParamsToTheNewRelicTrace()
{
$record = $this->getRecord(Level::Error, 'log message', ['a' => 'b']);
$record->extra = ['c' => 'd'];
$handler = new StubNewRelicHandler();
$handler->handle($record);
$expected = [
'context_a' => 'b',
'extra_c' => 'd',
];
$this->assertEquals($expected, self::$customParameters);
}
public function testThehandlerCanHandleTheRecordsFormattedUsingTheLineFormatter()
{
$handler = new StubNewRelicHandler();
$handler->setFormatter(new LineFormatter());
$handler->handle($this->getRecord(Level::Error));
}
public function testTheAppNameIsNullByDefault()
{
$handler = new StubNewRelicHandler();
$handler->handle($this->getRecord(Level::Error, 'log message'));
$this->assertEquals(null, self::$appname);
}
public function testTheAppNameCanBeInjectedFromtheConstructor()
{
$handler = new StubNewRelicHandler(Level::Debug, false, 'myAppName');
$handler->handle($this->getRecord(Level::Error, 'log message'));
$this->assertEquals('myAppName', self::$appname);
}
public function testTheAppNameCanBeOverriddenFromEachLog()
{
$handler = new StubNewRelicHandler(Level::Debug, false, 'myAppName');
$handler->handle($this->getRecord(Level::Error, 'log message', ['appname' => 'logAppName']));
$this->assertEquals('logAppName', self::$appname);
}
public function testTheTransactionNameIsNullByDefault()
{
$handler = new StubNewRelicHandler();
$handler->handle($this->getRecord(Level::Error, 'log message'));
$this->assertEquals(null, self::$transactionName);
}
public function testTheTransactionNameCanBeInjectedFromTheConstructor()
{
$handler = new StubNewRelicHandler(Level::Debug, false, null, false, 'myTransaction');
$handler->handle($this->getRecord(Level::Error, 'log message'));
$this->assertEquals('myTransaction', self::$transactionName);
}
public function testTheTransactionNameCanBeOverriddenFromEachLog()
{
$handler = new StubNewRelicHandler(Level::Debug, false, null, false, 'myTransaction');
$handler->handle($this->getRecord(Level::Error, 'log message', ['transaction_name' => 'logTransactName']));
$this->assertEquals('logTransactName', self::$transactionName);
}
}
class StubNewRelicHandlerWithoutExtension extends NewRelicHandler
{
protected function isNewRelicEnabled(): bool
{
return false;
}
}
class StubNewRelicHandler extends NewRelicHandler
{
protected function isNewRelicEnabled(): bool
{
return true;
}
}
function newrelic_notice_error()
{
return true;
}
function newrelic_set_appname($appname)
{
return NewRelicHandlerTest::$appname = $appname;
}
function newrelic_name_transaction($transactionName)
{
return NewRelicHandlerTest::$transactionName = $transactionName;
}
function newrelic_add_custom_parameter($key, $value)
{
NewRelicHandlerTest::$customParameters[$key] = $value;
return true;
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/SyslogHandlerTest.php | tests/Monolog/Handler/SyslogHandlerTest.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;
class SyslogHandlerTest extends \PHPUnit\Framework\TestCase
{
/**
* @covers Monolog\Handler\SyslogHandler::__construct
*/
public function testConstruct()
{
$handler = new SyslogHandler('test');
$this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler);
$handler = new SyslogHandler('test', LOG_USER);
$this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler);
$handler = new SyslogHandler('test', 'user');
$this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler);
$handler = new SyslogHandler('test', LOG_USER, Level::Debug, true, LOG_PERROR);
$this->assertInstanceOf('Monolog\Handler\SyslogHandler', $handler);
}
/**
* @covers Monolog\Handler\SyslogHandler::__construct
*/
public function testConstructInvalidFacility()
{
$this->expectException(\UnexpectedValueException::class);
$handler = new SyslogHandler('test', 'unknown');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/FallbackGroupHandlerTest.php | tests/Monolog/Handler/FallbackGroupHandlerTest.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;
class FallbackGroupHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\FallbackGroupHandler::__construct
* @covers Monolog\Handler\FallbackGroupHandler::handle
*/
public function testHandle()
{
$testHandlerOne = new TestHandler();
$testHandlerTwo = new TestHandler();
$testHandlers = [$testHandlerOne, $testHandlerTwo];
$handler = new FallbackGroupHandler($testHandlers);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$this->assertCount(2, $testHandlerOne->getRecords());
$this->assertCount(0, $testHandlerTwo->getRecords());
}
/**
* @covers Monolog\Handler\FallbackGroupHandler::__construct
* @covers Monolog\Handler\FallbackGroupHandler::handle
*/
public function testHandleExceptionThrown()
{
$testHandlerOne = new ExceptionTestHandler();
$testHandlerTwo = new TestHandler();
$testHandlers = [$testHandlerOne, $testHandlerTwo];
$handler = new FallbackGroupHandler($testHandlers);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$this->assertCount(0, $testHandlerOne->getRecords());
$this->assertCount(2, $testHandlerTwo->getRecords());
}
/**
* @covers Monolog\Handler\FallbackGroupHandler::handleBatch
*/
public function testHandleBatch()
{
$testHandlerOne = new TestHandler();
$testHandlerTwo = new TestHandler();
$testHandlers = [$testHandlerOne, $testHandlerTwo];
$handler = new FallbackGroupHandler($testHandlers);
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
$this->assertCount(2, $testHandlerOne->getRecords());
$this->assertCount(0, $testHandlerTwo->getRecords());
}
/**
* @covers Monolog\Handler\FallbackGroupHandler::handleBatch
*/
public function testHandleBatchExceptionThrown()
{
$testHandlerOne = new ExceptionTestHandler();
$testHandlerTwo = new TestHandler();
$testHandlers = [$testHandlerOne, $testHandlerTwo];
$handler = new FallbackGroupHandler($testHandlers);
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
$this->assertCount(0, $testHandlerOne->getRecords());
$this->assertCount(2, $testHandlerTwo->getRecords());
}
/**
* @covers Monolog\Handler\FallbackGroupHandler::isHandling
*/
public function testIsHandling()
{
$testHandlers = [new TestHandler(Level::Error), new TestHandler(Level::Warning)];
$handler = new FallbackGroupHandler($testHandlers);
$this->assertTrue($handler->isHandling($this->getRecord(Level::Error)));
$this->assertTrue($handler->isHandling($this->getRecord(Level::Warning)));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Debug)));
}
/**
* @covers Monolog\Handler\FallbackGroupHandler::handle
*/
public function testHandleUsesProcessors()
{
$test = new TestHandler();
$handler = new FallbackGroupHandler([$test]);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasWarningRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
}
/**
* @covers Monolog\Handler\FallbackGroupHandler::handleBatch
*/
public function testHandleBatchUsesProcessors()
{
$testHandlerOne = new ExceptionTestHandler();
$testHandlerTwo = new TestHandler();
$testHandlers = [$testHandlerOne, $testHandlerTwo];
$handler = new FallbackGroupHandler($testHandlers);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->pushProcessor(function ($record) {
$record->extra['foo2'] = true;
return $record;
});
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
$this->assertEmpty($testHandlerOne->getRecords());
$this->assertTrue($testHandlerTwo->hasDebugRecords());
$this->assertTrue($testHandlerTwo->hasInfoRecords());
$this->assertCount(2, $testHandlerTwo->getRecords());
$records = $testHandlerTwo->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
$this->assertTrue($records[1]['extra']['foo']);
$this->assertTrue($records[0]['extra']['foo2']);
$this->assertTrue($records[1]['extra']['foo2']);
}
public function testProcessorsDoNotInterfereBetweenHandlers()
{
$t1 = new ExceptionTestHandler();
$t2 = new TestHandler();
$handler = new FallbackGroupHandler([$t1, $t2]);
$t1->pushProcessor(function (LogRecord $record) {
$record->extra['foo'] = 'bar';
return $record;
});
$handler->handle($this->getRecord());
self::assertSame([], $t2->getRecords()[0]->extra);
}
public function testProcessorsDoNotInterfereBetweenHandlersWithBatch()
{
$t1 = new ExceptionTestHandler();
$t2 = new TestHandler();
$handler = new FallbackGroupHandler([$t1, $t2]);
$t1->pushProcessor(function (LogRecord $record) {
$record->extra['foo'] = 'bar';
return $record;
});
$handler->handleBatch([$this->getRecord()]);
self::assertSame([], $t2->getRecords()[0]->extra);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/PsrHandlerTest.php | tests/Monolog/Handler/PsrHandlerTest.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\Formatter\LineFormatter;
use PHPUnit\Framework\Attributes\DataProvider;
/**
* @covers Monolog\Handler\PsrHandler::handle
*/
class PsrHandlerTest extends \Monolog\Test\MonologTestCase
{
public static function logLevelProvider()
{
return array_map(
fn (Level $level) => [$level->toPsrLogLevel(), $level],
Level::cases()
);
}
#[DataProvider('logLevelProvider')]
public function testHandlesAllLevels(string $levelName, Level $level)
{
$message = 'Hello, world! ' . $level->value;
$context = ['foo' => 'bar', 'level' => $level->value];
$psrLogger = $this->createMock('Psr\Log\NullLogger');
$psrLogger->expects($this->once())
->method('log')
->with($levelName, $message, $context);
$handler = new PsrHandler($psrLogger);
$handler->handle($this->getRecord($level, $message, context: $context));
}
public function testFormatter()
{
$message = 'Hello, world!';
$context = ['foo' => 'bar'];
$level = Level::Error;
$psrLogger = $this->createMock('Psr\Log\NullLogger');
$psrLogger->expects($this->once())
->method('log')
->with($level->toPsrLogLevel(), 'dummy', $context);
$handler = new PsrHandler($psrLogger);
$handler->setFormatter(new LineFormatter('dummy'));
$handler->handle($this->getRecord($level, $message, context: $context, datetime: new \DateTimeImmutable()));
}
public function testIncludeExtra()
{
$message = 'Hello, world!';
$context = ['foo' => 'bar'];
$extra = ['baz' => 'boo'];
$level = Level::Error;
$psrLogger = $this->createMock('Psr\Log\NullLogger');
$psrLogger->expects($this->once())
->method('log')
->with($level->toPsrLogLevel(), $message, ['baz' => 'boo', 'foo' => 'bar']);
$handler = new PsrHandler($psrLogger, includeExtra: true);
$handler->handle($this->getRecord($level, $message, context: $context, datetime: new \DateTimeImmutable(), extra: $extra));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/ZendMonitorHandlerTest.php | tests/Monolog/Handler/ZendMonitorHandlerTest.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;
class ZendMonitorHandlerTest extends \Monolog\Test\MonologTestCase
{
public function setUp(): void
{
if (!\function_exists('zend_monitor_custom_event')) {
$this->markTestSkipped('ZendServer is not installed');
}
}
public function tearDown(): void
{
parent::tearDown();
unset($this->zendMonitorHandler);
}
/**
* @covers Monolog\Handler\ZendMonitorHandler::write
*/
public function testWrite()
{
$record = $this->getRecord();
$formatterResult = [
'message' => $record->message,
];
$zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler')
->onlyMethods(['writeZendMonitorCustomEvent', 'getDefaultFormatter'])
->getMock();
$formatterMock = $this->getMockBuilder('Monolog\Formatter\NormalizerFormatter')
->disableOriginalConstructor()
->getMock();
$formatterMock->expects($this->once())
->method('format')
->willReturn($formatterResult);
$zendMonitor->expects($this->once())
->method('getDefaultFormatter')
->willReturn($formatterMock);
$zendMonitor->expects($this->once())
->method('writeZendMonitorCustomEvent')
->with(
$record->level->getName(),
$record->message,
$formatterResult,
\ZEND_MONITOR_EVENT_SEVERITY_WARNING
);
$zendMonitor->handle($record);
}
/**
* @covers Monolog\Handler\ZendMonitorHandler::getDefaultFormatter
*/
public function testGetDefaultFormatterReturnsNormalizerFormatter()
{
$zendMonitor = new ZendMonitorHandler();
$this->assertInstanceOf('Monolog\Formatter\NormalizerFormatter', $zendMonitor->getDefaultFormatter());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/NativeMailerHandlerTest.php | tests/Monolog/Handler/NativeMailerHandlerTest.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;
function mail($to, $subject, $message, $additional_headers = null, $additional_parameters = null)
{
$GLOBALS['mail'][] = \func_get_args();
}
class NativeMailerHandlerTest extends \Monolog\Test\MonologTestCase
{
protected function setUp(): void
{
$GLOBALS['mail'] = [];
}
protected function newNativeMailerHandler(... $args) : NativeMailerHandler
{
return new class(... $args) extends NativeMailerHandler {
public $mail = [];
protected function mail(
string $to,
string $subject,
string $content,
string $headers,
string $parameters
) : void {
$this->mail[] = \func_get_args();
}
};
}
public function testConstructorHeaderInjection()
{
$this->expectException(\InvalidArgumentException::class);
$mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', "receiver@example.org\r\nFrom: faked@attacker.org");
}
public function testSetterHeaderInjection()
{
$this->expectException(\InvalidArgumentException::class);
$mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
$mailer->addHeader("Content-Type: text/html\r\nFrom: faked@attacker.org");
}
public function testSetterArrayHeaderInjection()
{
$this->expectException(\InvalidArgumentException::class);
$mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
$mailer->addHeader(["Content-Type: text/html\r\nFrom: faked@attacker.org"]);
}
public function testSetterContentTypeInjection()
{
$this->expectException(\InvalidArgumentException::class);
$mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
$mailer->setContentType("text/html\r\nFrom: faked@attacker.org");
}
public function testSetterEncodingInjection()
{
$this->expectException(\InvalidArgumentException::class);
$mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
$mailer->setEncoding("utf-8\r\nFrom: faked@attacker.org");
}
public function testSend()
{
$to = 'spammer@example.org';
$subject = 'dear victim';
$from = 'receiver@example.org';
$mailer = $this->newNativeMailerHandler($to, $subject, $from);
$mailer->setFormatter(new \Monolog\Formatter\LineFormatter);
$mailer->handleBatch([]);
// batch is empty, nothing sent
$this->assertEmpty($mailer->mail);
// non-empty batch
$mailer->handle($this->getRecord(Level::Error, "Foo\nBar\r\n\r\nBaz"));
$this->assertNotEmpty($mailer->mail);
$this->assertIsArray($mailer->mail);
$this->assertArrayHasKey('0', $mailer->mail);
$params = $mailer->mail[0];
$this->assertCount(5, $params);
$this->assertSame($to, $params[0]);
$this->assertSame($subject, $params[1]);
$this->assertStringEndsWith(" test.ERROR: Foo Bar Baz [] []\n", $params[2]);
$this->assertSame("From: $from\r\nContent-type: text/plain; charset=utf-8\r\n", $params[3]);
$this->assertSame('', $params[4]);
}
public function testMessageSubjectFormatting()
{
$mailer = $this->newNativeMailerHandler('to@example.org', 'Alert: %level_name% %message%', 'from@example.org');
$mailer->handle($this->getRecord(Level::Error, "Foo\nBar\r\n\r\nBaz"));
$this->assertNotEmpty($mailer->mail);
$this->assertIsArray($mailer->mail);
$this->assertArrayHasKey('0', $mailer->mail);
$params = $mailer->mail[0];
$this->assertCount(5, $params);
$this->assertSame('Alert: ERROR Foo Bar Baz', $params[1]);
}
public function testMail()
{
$mailer = new NativeMailerHandler('to@example.org', 'subject', 'from@example.org');
$mailer->addParameter('foo');
$mailer->handle($this->getRecord(Level::Error, "FooBarBaz"));
$this->assertNotEmpty($GLOBALS['mail']);
$this->assertIsArray($GLOBALS['mail']);
$this->assertArrayHasKey('0', $GLOBALS['mail']);
$params = $GLOBALS['mail'][0];
$this->assertCount(5, $params);
$this->assertSame('to@example.org', $params[0]);
$this->assertSame('subject', $params[1]);
$this->assertStringContainsString("FooBarBaz", $params[2]);
$this->assertStringContainsString('From: from@example.org', $params[3]);
$this->assertSame('foo', $params[4]);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/NoopHandlerTest.php | tests/Monolog/Handler/NoopHandlerTest.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 PHPUnit\Framework\Attributes\DataProvider;
/**
* @covers Monolog\Handler\NoopHandler::handle
*/
class NoopHandlerTest extends \Monolog\Test\MonologTestCase
{
#[DataProvider('logLevelsProvider')]
public function testIsHandling(Level $level)
{
$handler = new NoopHandler();
$this->assertTrue($handler->isHandling($this->getRecord($level)));
}
#[DataProvider('logLevelsProvider')]
public function testHandle(Level $level)
{
$handler = new NoopHandler();
$this->assertFalse($handler->handle($this->getRecord($level)));
}
public static function logLevelsProvider()
{
return array_map(
fn ($level) => [$level],
Level::cases()
);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/GroupHandlerTest.php | tests/Monolog/Handler/GroupHandlerTest.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\LogRecord;
use Monolog\Level;
class GroupHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\GroupHandler::__construct
*/
public function testConstructorOnlyTakesHandler()
{
$this->expectException(\InvalidArgumentException::class);
new GroupHandler([new TestHandler(), "foo"]);
}
/**
* @covers Monolog\Handler\GroupHandler::__construct
* @covers Monolog\Handler\GroupHandler::handle
*/
public function testHandle()
{
$testHandlers = [new TestHandler(), new TestHandler()];
$handler = new GroupHandler($testHandlers);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(2, $test->getRecords());
}
}
/**
* @covers Monolog\Handler\GroupHandler::handleBatch
*/
public function testHandleBatch()
{
$testHandlers = [new TestHandler(), new TestHandler()];
$handler = new GroupHandler($testHandlers);
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(2, $test->getRecords());
}
}
/**
* @covers Monolog\Handler\GroupHandler::isHandling
*/
public function testIsHandling()
{
$testHandlers = [new TestHandler(Level::Error), new TestHandler(Level::Warning)];
$handler = new GroupHandler($testHandlers);
$this->assertTrue($handler->isHandling($this->getRecord(Level::Error)));
$this->assertTrue($handler->isHandling($this->getRecord(Level::Warning)));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Debug)));
}
/**
* @covers Monolog\Handler\GroupHandler::handle
*/
public function testHandleUsesProcessors()
{
$test = new TestHandler();
$handler = new GroupHandler([$test]);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasWarningRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
}
/**
* @covers Monolog\Handler\GroupHandler::handle
*/
public function testHandleBatchUsesProcessors()
{
$testHandlers = [new TestHandler(), new TestHandler()];
$handler = new GroupHandler($testHandlers);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->pushProcessor(function ($record) {
$record->extra['foo2'] = true;
return $record;
});
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(2, $test->getRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
$this->assertTrue($records[1]['extra']['foo']);
$this->assertTrue($records[0]['extra']['foo2']);
$this->assertTrue($records[1]['extra']['foo2']);
}
}
public function testProcessorsDoNotInterfereBetweenHandlers()
{
$t1 = new TestHandler();
$t2 = new TestHandler();
$handler = new GroupHandler([$t1, $t2]);
$t1->pushProcessor(function (LogRecord $record) {
$record->extra['foo'] = 'bar';
return $record;
});
$handler->handle($this->getRecord());
self::assertSame([], $t2->getRecords()[0]->extra);
}
public function testProcessorsDoNotInterfereBetweenHandlersWithBatch()
{
$t1 = new TestHandler();
$t2 = new TestHandler();
$handler = new GroupHandler([$t1, $t2]);
$t1->pushProcessor(function (LogRecord $record) {
$record->extra['foo'] = 'bar';
return $record;
});
$handler->handleBatch([$this->getRecord()]);
self::assertSame([], $t2->getRecords()[0]->extra);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/FirePHPHandlerTest.php | tests/Monolog/Handler/FirePHPHandlerTest.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;
/**
* @covers Monolog\Handler\FirePHPHandler
*/
class FirePHPHandlerTest extends \Monolog\Test\MonologTestCase
{
public function setUp(): void
{
TestFirePHPHandler::resetStatic();
$_SERVER['HTTP_USER_AGENT'] = 'Monolog Test; FirePHP/1.0';
}
public function testHeaders()
{
$handler = new TestFirePHPHandler;
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Warning));
$expected = [
'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2',
'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1',
'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3',
'X-Wf-1-1-1-1' => 'test',
'X-Wf-1-1-1-2' => 'test',
];
$this->assertEquals($expected, $handler->getHeaders());
}
public function testConcurrentHandlers()
{
$handler = new TestFirePHPHandler;
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Warning));
$handler2 = new TestFirePHPHandler;
$handler2->setFormatter($this->getIdentityFormatter());
$handler2->handle($this->getRecord(Level::Debug));
$handler2->handle($this->getRecord(Level::Warning));
$expected = [
'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2',
'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1',
'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3',
'X-Wf-1-1-1-1' => 'test',
'X-Wf-1-1-1-2' => 'test',
];
$expected2 = [
'X-Wf-1-1-1-3' => 'test',
'X-Wf-1-1-1-4' => 'test',
];
$this->assertEquals($expected, $handler->getHeaders());
$this->assertEquals($expected2, $handler2->getHeaders());
}
}
class TestFirePHPHandler extends FirePHPHandler
{
protected array $headers = [];
public static function resetStatic(): void
{
self::$initialized = false;
self::$sendHeaders = true;
self::$messageIndex = 1;
}
protected function sendHeader(string $header, string $content): void
{
$this->headers[$header] = $content;
}
public function getHeaders(): array
{
return $this->headers;
}
protected function isWebRequest(): bool
{
return true;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/StreamHandlerTest.php | tests/Monolog/Handler/StreamHandlerTest.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 PHPUnit\Framework\Attributes\DataProvider;
class StreamHandlerTest extends \Monolog\Test\MonologTestCase
{
public function tearDown(): void
{
parent::tearDown();
@unlink(__DIR__.'/test.log');
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWrite()
{
$handle = fopen('php://memory', 'a+');
$handler = new StreamHandler($handle);
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Warning, 'test'));
$handler->handle($this->getRecord(Level::Warning, 'test2'));
$handler->handle($this->getRecord(Level::Warning, 'test3'));
fseek($handle, 0);
$this->assertEquals('testtest2test3', fread($handle, 100));
}
/**
* @covers Monolog\Handler\StreamHandler::close
*/
public function testCloseKeepsExternalHandlersOpen()
{
$handle = fopen('php://memory', 'a+');
$handler = new StreamHandler($handle);
$this->assertTrue(\is_resource($handle));
$handler->close();
$this->assertTrue(\is_resource($handle));
}
/**
* @covers Monolog\Handler\StreamHandler::close
*/
public function testClose()
{
$handler = new StreamHandler('php://memory');
$handler->handle($this->getRecord(Level::Warning, 'test'));
$stream = $handler->getStream();
$this->assertTrue(\is_resource($stream));
$handler->close();
$this->assertFalse(\is_resource($stream));
}
/**
* @covers Monolog\Handler\StreamHandler::close
* @covers Monolog\Handler\Handler::__serialize
*/
public function testSerialization()
{
$handler = new StreamHandler('php://memory');
$handler->handle($this->getRecord(Level::Warning, 'testfoo'));
$stream = $handler->getStream();
$this->assertTrue(\is_resource($stream));
fseek($stream, 0);
$this->assertStringContainsString('testfoo', stream_get_contents($stream));
$serialized = serialize($handler);
$this->assertFalse(\is_resource($stream));
$handler = unserialize($serialized);
$handler->handle($this->getRecord(Level::Warning, 'testbar'));
$stream = $handler->getStream();
$this->assertTrue(\is_resource($stream));
fseek($stream, 0);
$contents = stream_get_contents($stream);
$this->assertStringNotContainsString('testfoo', $contents);
$this->assertStringContainsString('testbar', $contents);
}
/**
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteCreatesTheStreamResource()
{
$handler = new StreamHandler('php://memory');
$handler->handle($this->getRecord());
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteLocking()
{
$temp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'monolog_locked_log';
$handler = new StreamHandler($temp, Level::Debug, true, null, true);
$handler->handle($this->getRecord());
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteMissingResource()
{
$this->expectException(\LogicException::class);
$handler = new StreamHandler(null);
$handler->handle($this->getRecord());
}
public static function invalidArgumentProvider()
{
return [
[1],
[[]],
[['bogus://url']],
];
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
*/
#[DataProvider('invalidArgumentProvider')]
public function testWriteInvalidArgument($invalidArgument)
{
$this->expectException(\InvalidArgumentException::class);
$handler = new StreamHandler($invalidArgument);
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteInvalidResource()
{
$this->expectException(\UnexpectedValueException::class);
$php7xMessage = <<<STRING
The stream or file "bogus://url" could not be opened in append mode: failed to open stream: No such file or directory
The exception occurred while attempting to log: test
Context: {"foo":"bar"}
Extra: [1,2,3]
STRING;
$php8xMessage = <<<STRING
The stream or file "bogus://url" could not be opened in append mode: Failed to open stream: No such file or directory
The exception occurred while attempting to log: test
Context: {"foo":"bar"}
Extra: [1,2,3]
STRING;
$phpVersionString = phpversion();
$phpVersionComponents = explode('.', $phpVersionString);
$majorVersion = (int) $phpVersionComponents[0];
$this->expectExceptionMessage(($majorVersion >= 8) ? $php8xMessage : $php7xMessage);
$handler = new StreamHandler('bogus://url');
$record = $this->getRecord(
context: ['foo' => 'bar'],
extra: [1, 2, 3],
);
$handler->handle($record);
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteNonExistingResource()
{
$this->expectException(\UnexpectedValueException::class);
$handler = new StreamHandler('ftp://foo/bar/baz/'.rand(0, 10000));
$handler->handle($this->getRecord());
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteNonExistingPath()
{
$handler = new StreamHandler(sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000));
$handler->handle($this->getRecord());
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteNonExistingFileResource()
{
$handler = new StreamHandler('file://'.sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000));
$handler->handle($this->getRecord());
}
/**
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteErrorDuringWriteRetriesWithClose()
{
$handler = $this->getMockBuilder(StreamHandler::class)
->onlyMethods(['streamWrite'])
->setConstructorArgs(['file://'.sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000)])
->getMock();
$refs = [];
$handler->expects($this->exactly(2))
->method('streamWrite')
->willReturnCallback(function ($stream) use (&$refs) {
$refs[] = $stream;
if (\count($refs) === 2) {
self::assertNotSame($stream, $refs[0]);
}
if (\count($refs) === 1) {
trigger_error('fwrite(): Write of 378 bytes failed with errno=32 Broken pipe', E_USER_ERROR);
}
});
$handler->handle($this->getRecord());
if (method_exists($this, 'assertIsClosedResource')) {
self::assertIsClosedResource($refs[0]);
self::assertIsResource($refs[1]);
}
}
/**
* @covers Monolog\Handler\StreamHandler::write
*/
public function testWriteErrorDuringWriteRetriesButThrowsIfStillFails()
{
$handler = $this->getMockBuilder(StreamHandler::class)
->onlyMethods(['streamWrite'])
->setConstructorArgs(['file://'.sys_get_temp_dir().'/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000)])
->getMock();
$refs = [];
$handler->expects($this->exactly(2))
->method('streamWrite')
->willReturnCallback(function ($stream) use (&$refs) {
$refs[] = $stream;
if (\count($refs) === 2) {
self::assertNotSame($stream, $refs[0]);
}
trigger_error('fwrite(): Write of 378 bytes failed with errno=32 Broken pipe', E_USER_ERROR);
});
self::expectException(\UnexpectedValueException::class);
self::expectExceptionMessage('Writing to the log file failed: Write of 378 bytes failed with errno=32 Broken pipe
The exception occurred while attempting to log: test');
$handler->handle($this->getRecord());
}
/**
* @covers Monolog\Handler\StreamHandler::__construct
* @covers Monolog\Handler\StreamHandler::write
*/
#[DataProvider('provideNonExistingAndNotCreatablePath')]
public function testWriteNonExistingAndNotCreatablePath($nonExistingAndNotCreatablePath)
{
if (\defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->markTestSkipped('Permissions checks can not run on windows');
}
$handler = null;
try {
$handler = new StreamHandler($nonExistingAndNotCreatablePath);
} catch (\Exception $fail) {
$this->fail(
'A non-existing and not creatable path should throw an Exception earliest on first write.
Not during instantiation.'
);
}
$this->expectException(\UnexpectedValueException::class);
$this->expectExceptionMessage('There is no existing directory at');
$handler->handle($this->getRecord());
}
public static function provideNonExistingAndNotCreatablePath()
{
return [
'/foo/bar/…' => [
'/foo/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000),
],
'file:///foo/bar/…' => [
'file:///foo/bar/'.rand(0, 10000).DIRECTORY_SEPARATOR.rand(0, 10000),
],
];
}
public static function provideMemoryValues()
{
return [
['1M', (int) (1024*1024/10)],
['10M', (int) (1024*1024)],
['1024M', (int) (1024*1024*1024/10)],
['1G', (int) (1024*1024*1024/10)],
['2000M', (int) (2000*1024*1024/10)],
['2050M', (int) (2050*1024*1024/10)],
['2048M', (int) (2048*1024*1024/10)],
['3G', (int) (3*1024*1024*1024/10)],
['2560M', (int) (2560*1024*1024/10)],
];
}
#[DataProvider('provideMemoryValues')]
public function testPreventOOMError($phpMemory, $expectedChunkSize): void
{
$previousValue = @ini_set('memory_limit', $phpMemory);
if ($previousValue === false) {
$this->markTestSkipped('We could not set a memory limit that would trigger the error.');
}
try {
$stream = tmpfile();
if ($stream === false) {
$this->markTestSkipped('We could not create a temp file to be use as a stream.');
}
$handler = new StreamHandler($stream);
stream_get_contents($stream, 1024);
$this->assertEquals($expectedChunkSize, $handler->getStreamChunkSize());
} finally {
ini_set('memory_limit', $previousValue);
}
}
public function testSimpleOOMPrevention(): void
{
$previousValue = ini_set('memory_limit', '2048M');
if ($previousValue === false) {
$this->markTestSkipped('We could not set a memory limit that would trigger the error.');
}
try {
$stream = tmpfile();
new StreamHandler($stream);
stream_get_contents($stream);
$this->assertTrue(true);
} finally {
ini_set('memory_limit', $previousValue);
}
}
public function testReopensFileIfInodeChanges()
{
$filename = __DIR__ . '/test.log';
$handler = new StreamHandler($filename);
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Warning, 'test1'));
@unlink($filename);
$handler->handle($this->getRecord(Level::Warning, 'test2'));
$data = @file_get_contents($filename);
$this->assertEquals('test2', $data);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/ChromePHPHandlerTest.php | tests/Monolog/Handler/ChromePHPHandlerTest.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 PHPUnit\Framework\Attributes\DataProvider;
/**
* @covers Monolog\Handler\ChromePHPHandler
*/
class ChromePHPHandlerTest extends \Monolog\Test\MonologTestCase
{
protected function setUp(): void
{
TestChromePHPHandler::resetStatic();
$_SERVER['HTTP_USER_AGENT'] = 'Monolog Test; Chrome/1.0';
}
#[DataProvider('agentsProvider')]
public function testHeaders($agent)
{
$_SERVER['HTTP_USER_AGENT'] = $agent;
$handler = new TestChromePHPHandler();
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Warning));
$expected = [
'X-ChromeLogger-Data' => base64_encode(json_encode([
'version' => '4.0',
'columns' => ['label', 'log', 'backtrace', 'type'],
'rows' => [
'test',
'test',
],
'request_uri' => '',
])),
];
$this->assertEquals($expected, $handler->getHeaders());
}
public static function agentsProvider()
{
return [
['Monolog Test; Chrome/1.0'],
['Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'],
['Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/56.0.2924.76 Chrome/56.0.2924.76 Safari/537.36'],
['Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome Safari/537.36'],
];
}
public function testHeadersOverflow()
{
$handler = new TestChromePHPHandler();
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Warning, str_repeat('a', 2 * 1024)));
// overflow chrome headers limit
$handler->handle($this->getRecord(Level::Warning, str_repeat('b', 2 * 1024)));
$expected = [
'X-ChromeLogger-Data' => base64_encode(json_encode([
'version' => '4.0',
'columns' => ['label', 'log', 'backtrace', 'type'],
'rows' => [
[
'test',
'test',
'unknown',
'log',
],
[
'test',
str_repeat('a', 2 * 1024),
'unknown',
'warn',
],
[
'monolog',
'Incomplete logs, chrome header size limit reached',
'unknown',
'warn',
],
],
'request_uri' => '',
])),
];
$this->assertEquals($expected, $handler->getHeaders());
}
public function testConcurrentHandlers()
{
$handler = new TestChromePHPHandler();
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Warning));
$handler2 = new TestChromePHPHandler();
$handler2->setFormatter($this->getIdentityFormatter());
$handler2->handle($this->getRecord(Level::Debug));
$handler2->handle($this->getRecord(Level::Warning));
$expected = [
'X-ChromeLogger-Data' => base64_encode(json_encode([
'version' => '4.0',
'columns' => ['label', 'log', 'backtrace', 'type'],
'rows' => [
'test',
'test',
'test',
'test',
],
'request_uri' => '',
])),
];
$this->assertEquals($expected, $handler2->getHeaders());
}
}
class TestChromePHPHandler extends ChromePHPHandler
{
protected array $headers = [];
public static function resetStatic(): void
{
self::$initialized = false;
self::$overflowed = false;
self::$sendHeaders = true;
self::$json['rows'] = [];
}
protected function sendHeader(string $header, string $content): void
{
$this->headers[$header] = $content;
}
public function getHeaders(): array
{
return $this->headers;
}
protected function isWebRequest(): bool
{
return true;
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.