1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-11 07:34:12 +02:00

Merge branch 'master' into update_phpunit_7

This commit is contained in:
George Mponos
2018-11-21 23:24:56 +02:00
63 changed files with 468 additions and 442 deletions

View File

@@ -48,6 +48,10 @@ $log->error('Bar');
- [Extending Monolog](doc/04-extending.md) - [Extending Monolog](doc/04-extending.md)
- [Log Record Structure](doc/message-structure.md) - [Log Record Structure](doc/message-structure.md)
## Support
Get supported Monolog and help fund the project with the [Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-monolog-monolog?utm_source=packagist-monolog-monolog&utm_medium=referral&utm_campaign=readme)
## Third Party Packages ## Third Party Packages
Third party handlers, formatters and processors are Third party handlers, formatters and processors are

View File

@@ -59,7 +59,7 @@
- [_RollbarHandler_](../src/Monolog/Handler/RollbarHandler.php): Logs records to a [Rollbar](https://rollbar.com/) account. - [_RollbarHandler_](../src/Monolog/Handler/RollbarHandler.php): Logs records to a [Rollbar](https://rollbar.com/) account.
- [_SyslogUdpHandler_](../src/Monolog/Handler/SyslogUdpHandler.php): Logs records to a remote [Syslogd](http://www.rsyslog.com/) server. - [_SyslogUdpHandler_](../src/Monolog/Handler/SyslogUdpHandler.php): Logs records to a remote [Syslogd](http://www.rsyslog.com/) server.
- [_LogEntriesHandler_](../src/Monolog/Handler/LogEntriesHandler.php): Logs records to a [LogEntries](http://logentries.com/) account. - [_LogEntriesHandler_](../src/Monolog/Handler/LogEntriesHandler.php): Logs records to a [LogEntries](http://logentries.com/) account.
- [_InsightOpsHandler_](../src/Monolog/Handler/InsightOpsHandler.php): Logs records to a [InsightOps](https://www.rapid7.com/products/insightops/) account. - [_InsightOpsHandler_](../src/Monolog/Handler/InsightOpsHandler.php): Logs records to an [InsightOps](https://www.rapid7.com/products/insightops/) account.
- [_LogmaticHandler_](../src/Monolog/Handler/LogmaticHandler.php): Logs records to a [Logmatic](http://logmatic.io/) account. - [_LogmaticHandler_](../src/Monolog/Handler/LogmaticHandler.php): Logs records to a [Logmatic](http://logmatic.io/) account.
- [_SqsHandler_](../src/Monolog/Handler/SqsHandler.php): Logs records to an [AWS SQS](http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-sqs.html) queue. - [_SqsHandler_](../src/Monolog/Handler/SqsHandler.php): Logs records to an [AWS SQS](http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-sqs.html) queue.

View File

@@ -30,14 +30,18 @@ class LogmaticFormatter extends JsonFormatter
*/ */
protected $appname = ''; protected $appname = '';
public function setHostname(string $hostname) public function setHostname(string $hostname): self
{ {
$this->hostname = $hostname; $this->hostname = $hostname;
return $this;
} }
public function setAppname(string $appname) public function setAppname(string $appname): self
{ {
$this->appname = $appname; $this->appname = $appname;
return $this;
} }
/** /**

View File

@@ -67,9 +67,11 @@ class NormalizerFormatter implements FormatterInterface
return $this->maxNormalizeDepth; return $this->maxNormalizeDepth;
} }
public function setMaxNormalizeDepth(int $maxNormalizeDepth): void public function setMaxNormalizeDepth(int $maxNormalizeDepth): self
{ {
$this->maxNormalizeDepth = $maxNormalizeDepth; $this->maxNormalizeDepth = $maxNormalizeDepth;
return $this;
} }
/** /**
@@ -80,9 +82,11 @@ class NormalizerFormatter implements FormatterInterface
return $this->maxNormalizeItemCount; return $this->maxNormalizeItemCount;
} }
public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): void public function setMaxNormalizeItemCount(int $maxNormalizeItemCount): self
{ {
$this->maxNormalizeItemCount = $maxNormalizeItemCount; $this->maxNormalizeItemCount = $maxNormalizeItemCount;
return $this;
} }
/** /**

View File

@@ -54,7 +54,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
]; ];
/** /**
* @param mixed $facility * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
* @param string|int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */

2
src/Monolog/Handler/BrowserConsoleHandler.php Executable file → Normal file
View File

@@ -97,7 +97,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
/** /**
* Wrapper for register_shutdown_function to allow overriding * Wrapper for register_shutdown_function to allow overriding
*/ */
protected function registerShutdownFunction() protected function registerShutdownFunction(): void
{ {
if (PHP_SAPI !== 'cli') { if (PHP_SAPI !== 'cli') {
register_shutdown_function(['Monolog\Handler\BrowserConsoleHandler', 'send']); register_shutdown_function(['Monolog\Handler\BrowserConsoleHandler', 'send']);

View File

@@ -36,11 +36,11 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
/** /**
* @param HandlerInterface $handler Handler. * @param HandlerInterface $handler Handler.
* @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. * @param int $bufferLimit How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded * @param bool $flushOnOverflow If true, the buffer is flushed when the max size has been reached, by default oldest entries are discarded
*/ */
public function __construct(HandlerInterface $handler, $bufferLimit = 0, $level = Logger::DEBUG, bool $bubble = true, $flushOnOverflow = false) public function __construct(HandlerInterface $handler, int $bufferLimit = 0, $level = Logger::DEBUG, bool $bubble = true, bool $flushOnOverflow = false)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->handler = $handler; $this->handler = $handler;
@@ -82,7 +82,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
return false === $this->bubble; return false === $this->bubble;
} }
public function flush() public function flush(): void
{ {
if ($this->bufferSize === 0) { if ($this->bufferSize === 0) {
return; return;
@@ -112,7 +112,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
/** /**
* Clears the buffer without flushing any messages down to the wrapped handler. * Clears the buffer without flushing any messages down to the wrapped handler.
*/ */
public function clear() public function clear(): void
{ {
$this->bufferSize = 0; $this->bufferSize = 0;
$this->buffer = []; $this->buffer = [];

View File

@@ -61,7 +61,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
protected static $sendHeaders = true; protected static $sendHeaders = true;
/** /**
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($level = Logger::DEBUG, bool $bubble = true) public function __construct($level = Logger::DEBUG, bool $bubble = true)
@@ -110,7 +110,6 @@ class ChromePHPHandler extends AbstractProcessingHandler
* *
* @see sendHeader() * @see sendHeader()
* @see send() * @see send()
* @param array $record
*/ */
protected function write(array $record): void protected function write(array $record): void
{ {
@@ -128,7 +127,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
* *
* @see sendHeader() * @see sendHeader()
*/ */
protected function send() protected function send(): void
{ {
if (self::$overflowed || !self::$sendHeaders) { if (self::$overflowed || !self::$sendHeaders) {
return; return;
@@ -171,11 +170,8 @@ class ChromePHPHandler extends AbstractProcessingHandler
/** /**
* Send header string to the client * Send header string to the client
*
* @param string $header
* @param string $content
*/ */
protected function sendHeader($header, $content) protected function sendHeader(string $header, string $content): void
{ {
if (!headers_sent() && self::$sendHeaders) { if (!headers_sent() && self::$sendHeaders) {
header(sprintf('%s: %s', $header, $content)); header(sprintf('%s: %s', $header, $content));

View File

@@ -35,7 +35,7 @@ class CubeHandler extends AbstractProcessingHandler
* A valid url must consist of three parts : protocol://host:port * A valid url must consist of three parts : protocol://host:port
* Only valid protocols used by Cube are http and udp * Only valid protocols used by Cube are http and udp
*/ */
public function __construct($url, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $url, $level = Logger::DEBUG, bool $bubble = true)
{ {
$urlInfo = parse_url($url); $urlInfo = parse_url($url);
@@ -63,7 +63,7 @@ class CubeHandler extends AbstractProcessingHandler
* @throws \LogicException when unable to connect to the socket * @throws \LogicException when unable to connect to the socket
* @throws MissingExtensionException when there is no socket extension * @throws MissingExtensionException when there is no socket extension
*/ */
protected function connectUdp() protected function connectUdp(): void
{ {
if (!extension_loaded('sockets')) { if (!extension_loaded('sockets')) {
throw new MissingExtensionException('The sockets extension is required to use udp URLs with the CubeHandler'); throw new MissingExtensionException('The sockets extension is required to use udp URLs with the CubeHandler');
@@ -80,13 +80,15 @@ class CubeHandler extends AbstractProcessingHandler
} }
/** /**
* Establish a connection to a http server * Establish a connection to an http server
* @throws \LogicException when no curl extension *
* @throws \LogicException when unable to connect to the socket
* @throws MissingExtensionException when no curl extension
*/ */
protected function connectHttp() protected function connectHttp(): void
{ {
if (!extension_loaded('curl')) { if (!extension_loaded('curl')) {
throw new \LogicException('The curl extension is needed to use http URLs with the CubeHandler'); throw new MissingExtensionException('The curl extension is required to use http URLs with the CubeHandler');
} }
$this->httpConnection = curl_init('http://'.$this->host.':'.$this->port.'/1.0/event/put'); $this->httpConnection = curl_init('http://'.$this->host.':'.$this->port.'/1.0/event/put');
@@ -126,7 +128,7 @@ class CubeHandler extends AbstractProcessingHandler
} }
} }
private function writeUdp($data) private function writeUdp(string $data): void
{ {
if (!$this->udpConnection) { if (!$this->udpConnection) {
$this->connectUdp(); $this->connectUdp();
@@ -135,7 +137,7 @@ class CubeHandler extends AbstractProcessingHandler
socket_send($this->udpConnection, $data, strlen($data), 0); socket_send($this->udpConnection, $data, strlen($data), 0);
} }
private function writeHttp($data) private function writeHttp(string $data): void
{ {
if (!$this->httpConnection) { if (!$this->httpConnection) {
$this->connectHttp(); $this->connectHttp();

View File

@@ -58,11 +58,11 @@ class DeduplicationHandler extends BufferHandler
/** /**
* @param HandlerInterface $handler Handler. * @param HandlerInterface $handler Handler.
* @param string $deduplicationStore The file/path where the deduplication log should be kept * @param string $deduplicationStore The file/path where the deduplication log should be kept
* @param int $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes * @param string|int $deduplicationLevel The minimum logging level for log records to be looked at for deduplication purposes
* @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through * @param int $time The period (in seconds) during which duplicate entries should be suppressed after a given log is sent through
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(HandlerInterface $handler, $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, $time = 60, bool $bubble = true) public function __construct(HandlerInterface $handler, ?string $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, int $time = 60, bool $bubble = true)
{ {
parent::__construct($handler, 0, Logger::DEBUG, $bubble, false); parent::__construct($handler, 0, Logger::DEBUG, $bubble, false);
@@ -71,7 +71,7 @@ class DeduplicationHandler extends BufferHandler
$this->time = $time; $this->time = $time;
} }
public function flush() public function flush(): void
{ {
if ($this->bufferSize === 0) { if ($this->bufferSize === 0) {
return; return;
@@ -100,7 +100,7 @@ class DeduplicationHandler extends BufferHandler
} }
} }
private function isDuplicate(array $record) private function isDuplicate(array $record): bool
{ {
if (!file_exists($this->deduplicationStore)) { if (!file_exists($this->deduplicationStore)) {
return false; return false;
@@ -130,10 +130,10 @@ class DeduplicationHandler extends BufferHandler
return false; return false;
} }
private function collectLogs() private function collectLogs(): void
{ {
if (!file_exists($this->deduplicationStore)) { if (!file_exists($this->deduplicationStore)) {
return false; return;
} }
$handle = fopen($this->deduplicationStore, 'rw+'); $handle = fopen($this->deduplicationStore, 'rw+');
@@ -161,7 +161,7 @@ class DeduplicationHandler extends BufferHandler
$this->gc = false; $this->gc = false;
} }
private function appendRecord(array $record) private function appendRecord(array $record): void
{ {
file_put_contents($this->deduplicationStore, $record['datetime']->getTimestamp() . ':' . $record['level_name'] . ':' . preg_replace('{[\r\n].*}', '', $record['message']) . "\n", FILE_APPEND); file_put_contents($this->deduplicationStore, $record['datetime']->getTimestamp() . ':' . $record['level_name'] . ':' . preg_replace('{[\r\n].*}', '', $record['message']) . "\n", FILE_APPEND);
} }

View File

@@ -49,12 +49,9 @@ class DynamoDbHandler extends AbstractProcessingHandler
protected $marshaler; protected $marshaler;
/** /**
* @param DynamoDbClient $client * @param int|string $level
* @param string $table
* @param int $level
* @param bool $bubble
*/ */
public function __construct(DynamoDbClient $client, $table, $level = Logger::DEBUG, bool $bubble = true) public function __construct(DynamoDbClient $client, string $table, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (defined('Aws\Sdk::VERSION') && version_compare(Sdk::VERSION, '3.0', '>=')) { if (defined('Aws\Sdk::VERSION') && version_compare(Sdk::VERSION, '3.0', '>=')) {
$this->version = 3; $this->version = 3;
@@ -87,11 +84,7 @@ class DynamoDbHandler extends AbstractProcessingHandler
]); ]);
} }
/** protected function filterEmptyFields(array $record): array
* @param array $record
* @return array
*/
protected function filterEmptyFields(array $record)
{ {
return array_filter($record, function ($value) { return array_filter($record, function ($value) {
return !empty($value) || false === $value || 0 === $value; return !empty($value) || false === $value || 0 === $value;

View File

@@ -48,7 +48,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
/** /**
* @param Client $client Elastica Client object * @param Client $client Elastica Client object
* @param array $options Handler configuration * @param array $options Handler configuration
* @param int $level The minimum logging level at which this handler will be triggered * @param int|string $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, bool $bubble = true) public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, bool $bubble = true)
@@ -85,11 +85,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
throw new \InvalidArgumentException('ElasticSearchHandler is only compatible with ElasticaFormatter'); throw new \InvalidArgumentException('ElasticSearchHandler is only compatible with ElasticaFormatter');
} }
/** public function getOptions(): array
* Getter options
* @return array
*/
public function getOptions()
{ {
return $this->options; return $this->options;
} }
@@ -113,10 +109,9 @@ class ElasticSearchHandler extends AbstractProcessingHandler
/** /**
* Use Elasticsearch bulk API to send list of documents * Use Elasticsearch bulk API to send list of documents
* @param array $documents
* @throws \RuntimeException * @throws \RuntimeException
*/ */
protected function bulkSend(array $documents) protected function bulkSend(array $documents): void
{ {
try { try {
$this->client->addDocuments($documents); $this->client->addDocuments($documents);

View File

@@ -30,11 +30,11 @@ class ErrorLogHandler extends AbstractProcessingHandler
/** /**
* @param int $messageType Says where the error should go. * @param int $messageType Says where the error should go.
* @param int $level The minimum logging level at which this handler will be triggered * @param int|string $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries * @param bool $expandNewlines If set to true, newlines in the message will be expanded to be take multiple log entries
*/ */
public function __construct($messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, bool $bubble = true, $expandNewlines = false) public function __construct(int $messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, bool $bubble = true, bool $expandNewlines = false)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
@@ -51,7 +51,7 @@ class ErrorLogHandler extends AbstractProcessingHandler
/** /**
* @return array With all available types * @return array With all available types
*/ */
public static function getAvailableTypes() public static function getAvailableTypes(): array
{ {
return [ return [
self::OPERATING_SYSTEM, self::OPERATING_SYSTEM,

View File

@@ -50,7 +50,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
/** /**
* @param callable|HandlerInterface $handler Handler or factory callable($record, $this). * @param callable|HandlerInterface $handler Handler or factory callable($record, $this).
* @param int|array $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided * @param int|array $minLevelOrList A list of levels to accept or a minimum level if maxLevel is provided
* @param int $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array * @param int|string $maxLevel Maximum level to accept, only used if $minLevelOrList is not an array
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, bool $bubble = true) public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, bool $bubble = true)
@@ -64,9 +64,6 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
} }
} }
/**
* @return array
*/
public function getAcceptedLevels(): array public function getAcceptedLevels(): array
{ {
return array_flip($this->acceptedLevels); return array_flip($this->acceptedLevels);
@@ -76,7 +73,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
* @param int|string|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided * @param int|string|array $minLevelOrList A list of levels to accept or a minimum level or level name if maxLevel is provided
* @param int|string $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array * @param int|string $maxLevel Maximum level or level name to accept, only used if $minLevelOrList is not an array
*/ */
public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY) public function setAcceptedLevels($minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY): self
{ {
if (is_array($minLevelOrList)) { if (is_array($minLevelOrList)) {
$acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList); $acceptedLevels = array_map('Monolog\Logger::toMonologLevel', $minLevelOrList);
@@ -88,6 +85,8 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface, Rese
})); }));
} }
$this->acceptedLevels = array_flip($acceptedLevels); $this->acceptedLevels = array_flip($acceptedLevels);
return $this;
} }
/** /**

View File

@@ -23,6 +23,10 @@ use Monolog\ResettableInterface;
* Only requests which actually trigger an error (or whatever your actionLevel is) will be * Only requests which actually trigger an error (or whatever your actionLevel is) will be
* in the logs, but they will contain all records, not only those above the level threshold. * in the logs, but they will contain all records, not only those above the level threshold.
* *
* You can then have a passthruLevel as well which means that at the end of the request,
* even if it did not get activated, it will still send through log records of e.g. at least a
* warning level.
*
* You can find the various activation strategies in the * You can find the various activation strategies in the
* Monolog\Handler\FingersCrossed\ namespace. * Monolog\Handler\FingersCrossed\ namespace.
* *
@@ -42,13 +46,13 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
/** /**
* @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler). * @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler).
* @param int|ActivationStrategyInterface $activationStrategy Strategy which determines when this handler takes action * @param int|string|ActivationStrategyInterface $activationStrategy Strategy which determines when this handler takes action, or a level name/value at which the handler is activated
* @param int $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer. * @param int $bufferSize How many entries should be buffered at most, beyond that the oldest items are removed from the buffer.
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $stopBuffering Whether the handler should stop buffering after being triggered (default true) * @param bool $stopBuffering Whether the handler should stop buffering after being triggered (default true)
* @param int $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered * @param int|string $passthruLevel Minimum level to always flush to handler on close, even if strategy not triggered
*/ */
public function __construct($handler, $activationStrategy = null, $bufferSize = 0, bool $bubble = true, $stopBuffering = true, $passthruLevel = null) public function __construct($handler, $activationStrategy = null, int $bufferSize = 0, bool $bubble = true, bool $stopBuffering = true, $passthruLevel = null)
{ {
if (null === $activationStrategy) { if (null === $activationStrategy) {
$activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING); $activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING);
@@ -85,7 +89,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
/** /**
* Manually activate this logger regardless of the activation strategy * Manually activate this logger regardless of the activation strategy
*/ */
public function activate() public function activate(): void
{ {
if ($this->stopBuffering) { if ($this->stopBuffering) {
$this->buffering = false; $this->buffering = false;
@@ -152,7 +156,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
* *
* It also resets the handler to its initial buffering state. * It also resets the handler to its initial buffering state.
*/ */
public function clear() public function clear(): void
{ {
$this->buffer = []; $this->buffer = [];
$this->reset(); $this->reset();
@@ -161,7 +165,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
/** /**
* Resets the state of the handler. Stops forwarding records to the wrapped handler. * Resets the state of the handler. Stops forwarding records to the wrapped handler.
*/ */
private function flushBuffer() private function flushBuffer(): void
{ {
if (null !== $this->passthruLevel) { if (null !== $this->passthruLevel) {
$level = $this->passthruLevel; $level = $this->passthruLevel;

View File

@@ -98,9 +98,8 @@ class FirePHPHandler extends AbstractProcessingHandler
* *
* @see createHeader() * @see createHeader()
* @see sendHeader() * @see sendHeader()
* @return array
*/ */
protected function getInitHeaders() protected function getInitHeaders(): array
{ {
// Initial payload consists of required headers for Wildfire // Initial payload consists of required headers for Wildfire
return array_merge( return array_merge(
@@ -112,11 +111,8 @@ class FirePHPHandler extends AbstractProcessingHandler
/** /**
* Send header string to the client * Send header string to the client
*
* @param string $header
* @param string $content
*/ */
protected function sendHeader($header, $content) protected function sendHeader(string $header, string $content): void
{ {
if (!headers_sent() && self::$sendHeaders) { if (!headers_sent() && self::$sendHeaders) {
header(sprintf('%s: %s', $header, $content)); header(sprintf('%s: %s', $header, $content));
@@ -158,10 +154,8 @@ class FirePHPHandler extends AbstractProcessingHandler
/** /**
* Verifies if the headers are accepted by the current user agent * Verifies if the headers are accepted by the current user agent
*
* @return bool
*/ */
protected function headersAccepted() protected function headersAccepted(): bool
{ {
if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) { if (!empty($_SERVER['HTTP_USER_AGENT']) && preg_match('{\bFirePHP/\d+\.\d+\b}', $_SERVER['HTTP_USER_AGENT'])) {
return true; return true;

View File

@@ -41,11 +41,11 @@ class FleepHookHandler extends SocketHandler
* see https://fleep.io/integrations/webhooks/ * see https://fleep.io/integrations/webhooks/
* *
* @param string $token Webhook token * @param string $token Webhook token
* @param bool|int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @throws MissingExtensionException * @throws MissingExtensionException
*/ */
public function __construct($token, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $token, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (!extension_loaded('openssl')) { if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler'); throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler');
@@ -71,8 +71,6 @@ class FleepHookHandler extends SocketHandler
/** /**
* Handles a log record * Handles a log record
*
* @param array $record
*/ */
public function write(array $record): void public function write(array $record): void
{ {
@@ -82,11 +80,8 @@ class FleepHookHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
@@ -95,11 +90,8 @@ class FleepHookHandler extends SocketHandler
/** /**
* Builds the header of the API Call * Builds the header of the API Call
*
* @param string $content
* @return string
*/ */
private function buildHeader($content) private function buildHeader(string $content): string
{ {
$header = "POST " . self::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n"; $header = "POST " . self::FLEEP_HOOK_URI . $this->token . " HTTP/1.1\r\n";
$header .= "Host: " . self::FLEEP_HOST . "\r\n"; $header .= "Host: " . self::FLEEP_HOST . "\r\n";
@@ -112,11 +104,8 @@ class FleepHookHandler extends SocketHandler
/** /**
* Builds the body of API call * Builds the body of API call
*
* @param array $record
* @return string
*/ */
private function buildContent($record) private function buildContent(array $record): string
{ {
$dataArray = [ $dataArray = [
'message' => $record['formatted'], 'message' => $record['formatted'],

View File

@@ -34,13 +34,12 @@ class FlowdockHandler extends SocketHandler
protected $apiToken; protected $apiToken;
/** /**
* @param string $apiToken * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* *
* @throws MissingExtensionException if OpenSSL is missing * @throws MissingExtensionException if OpenSSL is missing
*/ */
public function __construct($apiToken, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $apiToken, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (!extension_loaded('openssl')) { if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler'); throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler');
@@ -84,11 +83,8 @@ class FlowdockHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
@@ -97,22 +93,16 @@ class FlowdockHandler extends SocketHandler
/** /**
* Builds the body of API call * Builds the body of API call
*
* @param array $record
* @return string
*/ */
private function buildContent($record) private function buildContent(array $record): string
{ {
return json_encode($record['formatted']['flowdock']); return json_encode($record['formatted']['flowdock']);
} }
/** /**
* Builds the header of the API Call * Builds the header of the API Call
*
* @param string $content
* @return string
*/ */
private function buildHeader($content) private function buildHeader(string $content): string
{ {
$header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n"; $header = "POST /v1/messages/team_inbox/" . $this->apiToken . " HTTP/1.1\r\n";
$header .= "Host: api.flowdock.com\r\n"; $header .= "Host: api.flowdock.com\r\n";

View File

@@ -53,8 +53,6 @@ trait FormattableHandlerTrait
* Gets the default formatter. * Gets the default formatter.
* *
* Overwrite this if the LineFormatter is not a good default for your handler. * Overwrite this if the LineFormatter is not a good default for your handler.
*
* @return FormatterInterface
*/ */
protected function getDefaultFormatter(): FormatterInterface protected function getDefaultFormatter(): FormatterInterface
{ {

View File

@@ -31,7 +31,7 @@ class GelfHandler extends AbstractProcessingHandler
/** /**
* @param PublisherInterface $publisher a publisher object * @param PublisherInterface $publisher a publisher object
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true) public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true)

View File

@@ -26,7 +26,7 @@ class GroupHandler extends Handler implements ProcessableHandlerInterface, Reset
protected $handlers; protected $handlers;
/** /**
* @param array $handlers Array of Handlers. * @param HandlerInterface[] $handlers Array of Handlers.
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(array $handlers, bool $bubble = true) public function __construct(array $handlers, bool $bubble = true)
@@ -114,7 +114,7 @@ class GroupHandler extends Handler implements ProcessableHandlerInterface, Reset
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function setFormatter(FormatterInterface $formatter) public function setFormatter(FormatterInterface $formatter): HandlerInterface
{ {
foreach ($this->handlers as $handler) { foreach ($this->handlers as $handler) {
$handler->setFormatter($formatter); $handler->setFormatter($formatter);

View File

@@ -38,10 +38,6 @@ class HandlerWrapper implements HandlerInterface, ProcessableHandlerInterface, F
*/ */
protected $handler; protected $handler;
/**
* HandlerWrapper constructor.
* @param HandlerInterface $handler
*/
public function __construct(HandlerInterface $handler) public function __construct(HandlerInterface $handler)
{ {
$this->handler = $handler; $this->handler = $handler;

View File

@@ -72,16 +72,25 @@ class HipChatHandler extends SocketHandler
/** /**
* @param string $token HipChat API Token * @param string $token HipChat API Token
* @param string $room The room that should be alerted of the message (Id or Name) * @param string $room The room that should be alerted of the message (Id or Name)
* @param string $name Name used in the "from" field. * @param string|null $name Name used in the "from" field.
* @param bool $notify Trigger a notification in clients or not * @param bool $notify Trigger a notification in clients or not
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $useSSL Whether to connect via SSL. * @param bool $useSSL Whether to connect via SSL.
* @param string $format The format of the messages (default to text, can be set to html if you have html in the messages) * @param string $format The format of the messages (default to text, can be set to html if you have html in the messages)
* @param string $host The HipChat server hostname. * @param string $host The HipChat server hostname.
*/ */
public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, bool $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com') public function __construct(
{ string $token,
string $room,
?string $name = 'Monolog',
bool $notify = false,
$level = Logger::CRITICAL,
bool $bubble = true,
bool $useSSL = true,
string $format = 'text',
string $host = 'api.hipchat.com'
) {
$connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80'; $connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80';
parent::__construct($connectionString, $level, $bubble); parent::__construct($connectionString, $level, $bubble);
@@ -95,11 +104,8 @@ class HipChatHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
@@ -108,11 +114,8 @@ class HipChatHandler extends SocketHandler
/** /**
* Builds the body of API call * Builds the body of API call
*
* @param array $record
* @return string
*/ */
private function buildContent($record) private function buildContent(array $record): string
{ {
$dataArray = [ $dataArray = [
'notify' => $this->notify ? 'true' : 'false', 'notify' => $this->notify ? 'true' : 'false',
@@ -296,13 +299,8 @@ class HipChatHandler extends SocketHandler
* Note that this might cause false failures in the specific case of using * Note that this might cause false failures in the specific case of using
* a valid name with less than 16 characters, but 16 or more bytes, on a * a valid name with less than 16 characters, but 16 or more bytes, on a
* system where `mb_strlen()` is unavailable. * system where `mb_strlen()` is unavailable.
*
* @param string $str
* @param int $length
*
* @return bool
*/ */
private function validateStringLength($str, $length) private function validateStringLength(string $str, int $length): bool
{ {
if (function_exists('mb_strlen')) { if (function_exists('mb_strlen')) {
return (mb_strlen($str) <= $length); return (mb_strlen($str) <= $length);

View File

@@ -32,10 +32,10 @@ class IFTTTHandler extends AbstractProcessingHandler
/** /**
* @param string $eventName The name of the IFTTT Maker event that should be triggered * @param string $eventName The name of the IFTTT Maker event that should be triggered
* @param string $secretKey A valid IFTTT secret key * @param string $secretKey A valid IFTTT secret key
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($eventName, $secretKey, $level = Logger::ERROR, bool $bubble = true) public function __construct(string $eventName, string $secretKey, $level = Logger::ERROR, bool $bubble = true)
{ {
$this->eventName = $eventName; $this->eventName = $eventName;
$this->secretKey = $secretKey; $this->secretKey = $secretKey;

View File

@@ -30,12 +30,12 @@ class InsightOpsHandler extends SocketHandler
* @param string $token Log token supplied by InsightOps * @param string $token Log token supplied by InsightOps
* @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'. * @param string $region Region where InsightOps account is hosted. Could be 'us' or 'eu'.
* @param bool $useSSL Whether or not SSL encryption should be used * @param bool $useSSL Whether or not SSL encryption should be used
* @param int $level The minimum logging level to trigger this handler * @param string|int $level The minimum logging level to trigger this handler
* @param bool $bubble Whether or not messages that are handled should bubble up the stack. * @param bool $bubble Whether or not messages that are handled should bubble up the stack.
* *
* @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
*/ */
public function __construct($token, $region = 'us', $useSSL = true, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $token, string $region = 'us', bool $useSSL = true, $level = Logger::DEBUG, bool $bubble = true)
{ {
if ($useSSL && !extension_loaded('openssl')) { if ($useSSL && !extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler'); throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler');
@@ -51,11 +51,8 @@ class InsightOpsHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
return $this->logToken . ' ' . $record['formatted']; return $this->logToken . ' ' . $record['formatted'];
} }

View File

@@ -26,12 +26,13 @@ class LogEntriesHandler extends SocketHandler
/** /**
* @param string $token Log token supplied by LogEntries * @param string $token Log token supplied by LogEntries
* @param bool $useSSL Whether or not SSL encryption should be used. * @param bool $useSSL Whether or not SSL encryption should be used.
* @param int $level The minimum logging level to trigger this handler * @param string|int $level The minimum logging level to trigger this handler
* @param bool $bubble Whether or not messages that are handled should bubble up the stack. * @param bool $bubble Whether or not messages that are handled should bubble up the stack.
* @param string $host Custom hostname to send the data to if needed
* *
* @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
*/ */
public function __construct($token, $useSSL = true, $level = Logger::DEBUG, bool $bubble = true, string $host = 'data.logentries.com') public function __construct(string $token, bool $useSSL = true, $level = Logger::DEBUG, bool $bubble = true, string $host = 'data.logentries.com')
{ {
if ($useSSL && !extension_loaded('openssl')) { if ($useSSL && !extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler'); throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler');
@@ -44,11 +45,8 @@ class LogEntriesHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
return $this->logToken . ' ' . $record['formatted']; return $this->logToken . ' ' . $record['formatted'];
} }

View File

@@ -32,10 +32,17 @@ class LogglyHandler extends AbstractProcessingHandler
protected $tag = []; protected $tag = [];
public function __construct($token, $level = Logger::DEBUG, bool $bubble = true) /**
* @param string $token API token supplied by Loggly
* @param string|int $level The minimum logging level to trigger this handler
* @param bool $bubble Whether or not messages that are handled should bubble up the stack.
*
* @throws MissingExtensionException If the curl extension is missing
*/
public function __construct(string $token, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (!extension_loaded('curl')) { if (!extension_loaded('curl')) {
throw new \LogicException('The curl extension is needed to use the LogglyHandler'); throw new MissingExtensionException('The curl extension is needed to use the LogglyHandler');
} }
$this->token = $token; $this->token = $token;
@@ -43,18 +50,28 @@ class LogglyHandler extends AbstractProcessingHandler
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
} }
public function setTag($tag) /**
* @param string[]|string $tag
*/
public function setTag($tag): self
{ {
$tag = !empty($tag) ? $tag : []; $tag = !empty($tag) ? $tag : [];
$this->tag = is_array($tag) ? $tag : [$tag]; $this->tag = is_array($tag) ? $tag : [$tag];
return $this;
} }
public function addTag($tag) /**
* @param string[]|string $tag
*/
public function addTag($tag): self
{ {
if (!empty($tag)) { if (!empty($tag)) {
$tag = is_array($tag) ? $tag : [$tag]; $tag = is_array($tag) ? $tag : [$tag];
$this->tag = array_unique(array_merge($this->tag, $tag)); $this->tag = array_unique(array_merge($this->tag, $tag));
} }
return $this;
} }
protected function write(array $record): void protected function write(array $record): void
@@ -75,7 +92,7 @@ class LogglyHandler extends AbstractProcessingHandler
} }
} }
protected function send($data, $endpoint) protected function send(string $data, string $endpoint): void
{ {
$url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token); $url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token);

View File

@@ -64,7 +64,7 @@ class LogmaticHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
protected function generateDataStream($record): string protected function generateDataStream(array $record): string
{ {
return $this->logToken . ' ' . $record['formatted']; return $this->logToken . ' ' . $record['formatted'];
} }

View File

@@ -27,10 +27,10 @@ class MandrillHandler extends MailHandler
/** /**
* @param string $apiKey A valid Mandrill API key * @param string $apiKey A valid Mandrill API key
* @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($apiKey, $message, $level = Logger::ERROR, bool $bubble = true) public function __construct(string $apiKey, $message, $level = Logger::ERROR, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);

View File

@@ -12,7 +12,7 @@
namespace Monolog\Handler; namespace Monolog\Handler;
/** /**
* Exception can be thrown if an extension for an handler is missing * Exception can be thrown if an extension for a handler is missing
* *
* @author Christian Bergau <cbergau86@gmail.com> * @author Christian Bergau <cbergau86@gmail.com>
*/ */

View File

@@ -43,10 +43,10 @@ class MongoDBHandler extends AbstractProcessingHandler
* @param Client|Manager $mongodb MongoDB library or driver client * @param Client|Manager $mongodb MongoDB library or driver client
* @param string $database Database name * @param string $database Database name
* @param string $collection Collection name * @param string $collection Collection name
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($mongodb, $database, $collection, $level = Logger::DEBUG, bool $bubble = true) public function __construct($mongodb, string $database, string $collection, $level = Logger::DEBUG, bool $bubble = true)
{ {
if (!($mongodb instanceof Client || $mongodb instanceof Manager)) { if (!($mongodb instanceof Client || $mongodb instanceof Manager)) {
throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required'); throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required');

View File

@@ -54,7 +54,7 @@ class NativeMailerHandler extends MailHandler
/** /**
* The Content-type for the message * The Content-type for the message
* @var string * @var string|null
*/ */
protected $contentType; protected $contentType;
@@ -68,11 +68,11 @@ class NativeMailerHandler extends MailHandler
* @param string|array $to The receiver of the mail * @param string|array $to The receiver of the mail
* @param string $subject The subject of the mail * @param string $subject The subject of the mail
* @param string $from The sender of the mail * @param string $from The sender of the mail
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int $maxColumnWidth The maximum column width that the message lines will have * @param int $maxColumnWidth The maximum column width that the message lines will have
*/ */
public function __construct($to, $subject, $from, $level = Logger::ERROR, bool $bubble = true, $maxColumnWidth = 70) public function __construct($to, string $subject, string $from, $level = Logger::ERROR, bool $bubble = true, int $maxColumnWidth = 70)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->to = (array) $to; $this->to = (array) $to;
@@ -85,9 +85,8 @@ class NativeMailerHandler extends MailHandler
* Add headers to the message * Add headers to the message
* *
* @param string|array $headers Custom added headers * @param string|array $headers Custom added headers
* @return self
*/ */
public function addHeader($headers) public function addHeader($headers): self
{ {
foreach ((array) $headers as $header) { foreach ((array) $headers as $header) {
if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) { if (strpos($header, "\n") !== false || strpos($header, "\r") !== false) {
@@ -103,9 +102,8 @@ class NativeMailerHandler extends MailHandler
* Add parameters to the message * Add parameters to the message
* *
* @param string|array $parameters Custom added parameters * @param string|array $parameters Custom added parameters
* @return self
*/ */
public function addParameter($parameters) public function addParameter($parameters): self
{ {
$this->parameters = array_merge($this->parameters, (array) $parameters); $this->parameters = array_merge($this->parameters, (array) $parameters);
@@ -141,28 +139,20 @@ class NativeMailerHandler extends MailHandler
} }
} }
/** public function getContentType(): ?string
* @return string $contentType
*/
public function getContentType()
{ {
return $this->contentType; return $this->contentType;
} }
/** public function getEncoding(): string
* @return string $encoding
*/
public function getEncoding()
{ {
return $this->encoding; return $this->encoding;
} }
/** /**
* @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML * @param string $contentType The content type of the email - Defaults to text/plain. Use text/html for HTML messages.
* messages.
* @return self
*/ */
public function setContentType($contentType) public function setContentType(string $contentType): self
{ {
if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) { if (strpos($contentType, "\n") !== false || strpos($contentType, "\r") !== false) {
throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection'); throw new \InvalidArgumentException('The content type can not contain newline characters to prevent email header injection');
@@ -173,11 +163,7 @@ class NativeMailerHandler extends MailHandler
return $this; return $this;
} }
/** public function setEncoding(string $encoding): self
* @param string $encoding
* @return self
*/
public function setEncoding($encoding)
{ {
if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) { if (strpos($encoding, "\n") !== false || strpos($encoding, "\r") !== false) {
throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection'); throw new \InvalidArgumentException('The encoding can not contain newline characters to prevent email header injection');

View File

@@ -29,14 +29,14 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* Name of the New Relic application that will receive logs from this handler. * Name of the New Relic application that will receive logs from this handler.
* *
* @var string * @var string|null
*/ */
protected $appName; protected $appName;
/** /**
* Name of the current transaction * Name of the current transaction
* *
* @var string * @var string|null
*/ */
protected $transactionName; protected $transactionName;
@@ -51,16 +51,18 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* {@inheritDoc} * {@inheritDoc}
* *
* @param string $appName * @param string|int $level The minimum logging level at which this handler will be triggered.
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not.
* @param string|null $appName
* @param bool $explodeArrays * @param bool $explodeArrays
* @param string $transactionName * @param string|null $transactionName
*/ */
public function __construct( public function __construct(
$level = Logger::ERROR, $level = Logger::ERROR,
$bubble = true, bool $bubble = true,
$appName = null, ?string $appName = null,
$explodeArrays = false, bool $explodeArrays = false,
$transactionName = null ?string $transactionName = null
) { ) {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
@@ -124,7 +126,7 @@ class NewRelicHandler extends AbstractProcessingHandler
* *
* @return bool * @return bool
*/ */
protected function isNewRelicEnabled() protected function isNewRelicEnabled(): bool
{ {
return extension_loaded('newrelic'); return extension_loaded('newrelic');
} }
@@ -132,11 +134,8 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* Returns the appname where this log should be sent. Each log can override the default appname, set in this * 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. * handler's constructor, by providing the appname in it's context.
*
* @param array $context
* @return null|string
*/ */
protected function getAppName(array $context) protected function getAppName(array $context): ?string
{ {
if (isset($context['appname'])) { if (isset($context['appname'])) {
return $context['appname']; return $context['appname'];
@@ -148,12 +147,8 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* Returns the name of the current transaction. Each log can override the default transaction name, set in this * 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 * handler's constructor, by providing the transaction_name in it's context
*
* @param array $context
*
* @return null|string
*/ */
protected function getTransactionName(array $context) protected function getTransactionName(array $context): ?string
{ {
if (isset($context['transaction_name'])) { if (isset($context['transaction_name'])) {
return $context['transaction_name']; return $context['transaction_name'];
@@ -164,20 +159,16 @@ class NewRelicHandler extends AbstractProcessingHandler
/** /**
* Sets the NewRelic application that should receive this log. * Sets the NewRelic application that should receive this log.
*
* @param string $appName
*/ */
protected function setNewRelicAppName($appName) protected function setNewRelicAppName(string $appName): void
{ {
newrelic_set_appname($appName); newrelic_set_appname($appName);
} }
/** /**
* Overwrites the name of the current transaction * Overwrites the name of the current transaction
*
* @param string $transactionName
*/ */
protected function setNewRelicTransactionName($transactionName) protected function setNewRelicTransactionName(string $transactionName): void
{ {
newrelic_name_transaction($transactionName); newrelic_name_transaction($transactionName);
} }
@@ -186,7 +177,7 @@ class NewRelicHandler extends AbstractProcessingHandler
* @param string $key * @param string $key
* @param mixed $value * @param mixed $value
*/ */
protected function setNewRelicParameter($key, $value) protected function setNewRelicParameter(string $key, $value): void
{ {
if (null === $value || is_scalar($value)) { if (null === $value || is_scalar($value)) {
newrelic_add_custom_parameter($key, $value); newrelic_add_custom_parameter($key, $value);

View File

@@ -23,14 +23,17 @@ use Monolog\Logger;
*/ */
class NullHandler extends Handler class NullHandler extends Handler
{ {
/**
* @var int
*/
private $level; private $level;
/** /**
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
*/ */
public function __construct(int $level = Logger::DEBUG) public function __construct($level = Logger::DEBUG)
{ {
$this->level = $level; $this->level = Logger::toMonologLevel($level);
} }
/** /**
@@ -46,10 +49,6 @@ class NullHandler extends Handler
*/ */
public function handle(array $record): bool public function handle(array $record): bool
{ {
if ($record['level'] < $this->level) { return $record['level'] >= $this->level;
return false;
}
return true;
} }
} }

View File

@@ -68,8 +68,8 @@ class PHPConsoleHandler extends AbstractProcessingHandler
/** /**
* @param array $options See \Monolog\Handler\PHPConsoleHandler::$options for more details * @param array $options See \Monolog\Handler\PHPConsoleHandler::$options for more details
* @param Connector|null $connector Instance of \PhpConsole\Connector class (optional) * @param Connector|null $connector Instance of \PhpConsole\Connector class (optional)
* @param int|string $level * @param string|int $level The minimum logging level at which this handler will be triggered.
* @param bool $bubble * @param bool $bubble Whether the messages that are handled can bubble up the stack or not.
* @throws \RuntimeException * @throws \RuntimeException
*/ */
public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true) public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true)
@@ -82,7 +82,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
$this->connector = $this->initConnector($connector); $this->connector = $this->initConnector($connector);
} }
private function initOptions(array $options) private function initOptions(array $options): array
{ {
$wrongOptions = array_diff(array_keys($options), array_keys($this->options)); $wrongOptions = array_diff(array_keys($options), array_keys($this->options));
if ($wrongOptions) { if ($wrongOptions) {
@@ -95,7 +95,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
/** /**
* @suppress PhanTypeMismatchArgument * @suppress PhanTypeMismatchArgument
*/ */
private function initConnector(Connector $connector = null): Connector private function initConnector(?Connector $connector = null): Connector
{ {
if (!$connector) { if (!$connector) {
if ($this->options['dataStorage']) { if ($this->options['dataStorage']) {
@@ -171,9 +171,6 @@ class PHPConsoleHandler extends AbstractProcessingHandler
/** /**
* Writes the record down to the log of the implementing handler * Writes the record down to the log of the implementing handler
*
* @param array $record
* @return void
*/ */
protected function write(array $record): void protected function write(array $record): void
{ {

View File

@@ -21,7 +21,7 @@ interface ProcessableHandlerInterface
/** /**
* Adds a processor in the stack. * Adds a processor in the stack.
* *
* @param callable $callback * @param ProcessorInterface|callable $callback
* @return HandlerInterface self * @return HandlerInterface self
*/ */
public function pushProcessor(callable $callback): HandlerInterface; public function pushProcessor(callable $callback): HandlerInterface;

View File

@@ -60,7 +60,7 @@ trait ProcessableHandlerTrait
return $record; return $record;
} }
protected function resetProcessors() protected function resetProcessors(): void
{ {
foreach ($this->processors as $processor) { foreach ($this->processors as $processor) {
if ($processor instanceof ResettableInterface) { if ($processor instanceof ResettableInterface) {

View File

@@ -13,13 +13,18 @@ namespace Monolog\Handler;
use Monolog\Logger; use Monolog\Logger;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Monolog\Formatter\FormatterInterface;
/** /**
* Proxies log messages to an existing PSR-3 compliant logger. * 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> * @author Michael Moussa <michael.moussa@gmail.com>
*/ */
class PsrHandler extends AbstractHandler class PsrHandler extends AbstractHandler implements FormattableHandlerInterface
{ {
/** /**
* PSR-3 compliant logger * PSR-3 compliant logger
@@ -28,9 +33,14 @@ class PsrHandler extends AbstractHandler
*/ */
protected $logger; protected $logger;
/**
* @var FormatterInterface
*/
protected $formatter;
/** /**
* @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied * @param LoggerInterface $logger The underlying PSR-3 compliant logger to which messages will be proxied
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true) public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true)
@@ -49,8 +59,39 @@ class PsrHandler extends AbstractHandler
return false; return false;
} }
if ($this->formatter) {
$formatted = $this->formatter->format($record);
$this->logger->log(strtolower($record['level_name']), (string) $formatted, $record['context']);
} else {
$this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']); $this->logger->log(strtolower($record['level_name']), $record['message'], $record['context']);
}
return false === $this->bubble; return false === $this->bubble;
} }
/**
* Sets the formatter.
*
* @param FormatterInterface $formatter
*/
public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
$this->formatter = $formatter;
return $this;
}
/**
* Gets the formatter.
*
* @return FormatterInterface
*/
public function getFormatter(): FormatterInterface
{
if (!$this->formatter) {
throw new \LogicException('No formatter has been set and this handler does not have a default formatter');
}
return $this->formatter;
}
} }

View File

@@ -68,19 +68,31 @@ class PushoverHandler extends SocketHandler
* @param string $token Pushover api token * @param string $token Pushover api token
* @param string|array $users Pushover user id or array of ids the message will be sent to * @param string|array $users Pushover user id or array of ids the message will be sent to
* @param string $title Title sent to the Pushover API * @param string $title Title sent to the Pushover API
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not * @param bool $useSSL Whether to connect via SSL. Required when pushing messages to users that are not
* the pushover.net app owner. OpenSSL is required for this option. * the pushover.net app owner. OpenSSL is required for this option.
* @param int $highPriorityLevel The minimum logging level at which this handler will start * @param string|int $highPriorityLevel The minimum logging level at which this handler will start
* sending "high priority" requests to the Pushover API * sending "high priority" requests to the Pushover API
* @param int $emergencyLevel The minimum logging level at which this handler will start * @param string|int $emergencyLevel The minimum logging level at which this handler will start
* sending "emergency" requests to the Pushover API * sending "emergency" requests to the Pushover API
* @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will send the same notification to the user. * @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will
* @param int $expire The expire parameter specifies how many seconds your notification will continue to be retried for (every retry seconds). * send the same notification to the user.
* @param int $expire The expire parameter specifies how many seconds your notification will continue
* to be retried for (every retry seconds).
*/ */
public function __construct($token, $users, $title = null, $level = Logger::CRITICAL, bool $bubble = true, $useSSL = true, $highPriorityLevel = Logger::CRITICAL, $emergencyLevel = Logger::EMERGENCY, $retry = 30, $expire = 25200) public function __construct(
{ string $token,
$users,
?string $title = null,
$level = Logger::CRITICAL,
bool $bubble = true,
bool $useSSL = true,
$highPriorityLevel = Logger::CRITICAL,
$emergencyLevel = Logger::EMERGENCY,
int $retry = 30,
int $expire = 25200
) {
$connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80'; $connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80';
parent::__construct($connectionString, $level, $bubble); parent::__construct($connectionString, $level, $bubble);
@@ -93,14 +105,14 @@ class PushoverHandler extends SocketHandler
$this->expire = $expire; $this->expire = $expire;
} }
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
return $this->buildHeader($content) . $content; return $this->buildHeader($content) . $content;
} }
private function buildContent($record) private function buildContent(array $record): string
{ {
// Pushover has a limit of 512 characters on title and message combined. // Pushover has a limit of 512 characters on title and message combined.
$maxMessageLength = 512 - strlen($this->title); $maxMessageLength = 512 - strlen($this->title);
@@ -141,7 +153,7 @@ class PushoverHandler extends SocketHandler
return http_build_query($dataArray); return http_build_query($dataArray);
} }
private function buildHeader($content) private function buildHeader(string $content): string
{ {
$header = "POST /1/messages.json HTTP/1.1\r\n"; $header = "POST /1/messages.json HTTP/1.1\r\n";
$header .= "Host: api.pushover.net\r\n"; $header .= "Host: api.pushover.net\r\n";
@@ -164,22 +176,27 @@ class PushoverHandler extends SocketHandler
$this->user = null; $this->user = null;
} }
public function setHighPriorityLevel($value) public function setHighPriorityLevel($value): self
{ {
$this->highPriorityLevel = $value; $this->highPriorityLevel = Logger::toMonologLevel($value);
return $this;
} }
public function setEmergencyLevel($value) public function setEmergencyLevel($value): self
{ {
$this->emergencyLevel = $value; $this->emergencyLevel = Logger::toMonologLevel($value);
return $this;
} }
/** /**
* Use the formatted message? * Use the formatted message?
* @param bool $value
*/ */
public function useFormattedMessage($value) public function useFormattedMessage(bool $value): self
{ {
$this->useFormattedMessage = (bool) $value; $this->useFormattedMessage = $value;
return $this;
} }
} }

View File

@@ -114,9 +114,11 @@ class RavenHandler extends AbstractProcessingHandler
* *
* @param FormatterInterface $formatter * @param FormatterInterface $formatter
*/ */
public function setBatchFormatter(FormatterInterface $formatter): void public function setBatchFormatter(FormatterInterface $formatter): self
{ {
$this->batchFormatter = $formatter; $this->batchFormatter = $formatter;
return $this;
} }
/** /**
@@ -250,13 +252,17 @@ class RavenHandler extends AbstractProcessingHandler
/** /**
* @link https://docs.sentry.io/learn/breadcrumbs/ * @link https://docs.sentry.io/learn/breadcrumbs/
*/ */
public function addBreadcrumb(array $crumb): void public function addBreadcrumb(array $crumb): self
{ {
$this->ravenClient->breadcrumbs->record($crumb); $this->ravenClient->breadcrumbs->record($crumb);
return $this;
} }
public function resetBreadcrumbs(): void public function resetBreadcrumbs(): self
{ {
$this->ravenClient->breadcrumbs->reset(); $this->ravenClient->breadcrumbs->reset();
return $this;
} }
} }

View File

@@ -35,7 +35,7 @@ class RedisHandler extends AbstractProcessingHandler
/** /**
* @param \Predis\Client|\Redis $redis The redis instance * @param \Predis\Client|\Redis $redis The redis instance
* @param string $key The key name to push records to * @param string $key The key name to push records to
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int $capSize Number of entries to limit list size to, 0 = unlimited * @param int $capSize Number of entries to limit list size to, 0 = unlimited
*/ */
@@ -67,11 +67,8 @@ class RedisHandler extends AbstractProcessingHandler
/** /**
* Write and cap the collection * Write and cap the collection
* Writes the record to the redis list and caps its * Writes the record to the redis list and caps its
*
* @param array $record associative record array
* @return void
*/ */
protected function writeCapped(array $record) protected function writeCapped(array $record): void
{ {
if ($this->redisClient instanceof \Redis) { if ($this->redisClient instanceof \Redis) {
$this->redisClient->multi() $this->redisClient->multi()

View File

@@ -60,7 +60,7 @@ class RollbarHandler extends AbstractProcessingHandler
/** /**
* @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token * @param RollbarLogger $rollbarLogger RollbarLogger object constructed with valid token
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true) public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true)

View File

@@ -39,12 +39,12 @@ class RotatingFileHandler extends StreamHandler
/** /**
* @param string $filename * @param string $filename
* @param int $maxFiles The maximal amount of files to keep (0 means unlimited) * @param int $maxFiles The maximal amount of files to keep (0 means unlimited)
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) * @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 * @param bool $useLocking Try to lock log file before doing any writes
*/ */
public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, $filePermission = null, $useLocking = false) public function __construct(string $filename, int $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false)
{ {
$this->filename = $filename; $this->filename = $filename;
$this->maxFiles = (int) $maxFiles; $this->maxFiles = (int) $maxFiles;
@@ -79,7 +79,7 @@ class RotatingFileHandler extends StreamHandler
} }
} }
public function setFilenameFormat($filenameFormat, $dateFormat) public function setFilenameFormat(string $filenameFormat, string $dateFormat): self
{ {
if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) { if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) {
throw new InvalidArgumentException( throw new InvalidArgumentException(
@@ -98,6 +98,8 @@ class RotatingFileHandler extends StreamHandler
$this->dateFormat = $dateFormat; $this->dateFormat = $dateFormat;
$this->url = $this->getTimedFilename(); $this->url = $this->getTimedFilename();
$this->close(); $this->close();
return $this;
} }
/** /**
@@ -158,7 +160,7 @@ class RotatingFileHandler extends StreamHandler
$this->mustRotate = false; $this->mustRotate = false;
} }
protected function getTimedFilename() protected function getTimedFilename(): string
{ {
$fileInfo = pathinfo($this->filename); $fileInfo = pathinfo($this->filename);
$timedFilename = str_replace( $timedFilename = str_replace(
@@ -174,7 +176,7 @@ class RotatingFileHandler extends StreamHandler
return $timedFilename; return $timedFilename;
} }
protected function getGlobPattern() protected function getGlobPattern(): string
{ {
$fileInfo = pathinfo($this->filename); $fileInfo = pathinfo($this->filename);
$glob = str_replace( $glob = str_replace(

View File

@@ -41,9 +41,9 @@ class SamplingHandler extends AbstractHandler implements ProcessableHandlerInter
/** /**
* @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler). * @param callable|HandlerInterface $handler Handler or factory callable($record, $fingersCrossedHandler).
* @param int $factor Sample factor * @param int $factor Sample factor (e.g. 10 means every ~10th record is sampled)
*/ */
public function __construct($handler, $factor) public function __construct($handler, int $factor)
{ {
parent::__construct(); parent::__construct();
$this->handler = $handler; $this->handler = $handler;

0
src/Monolog/Handler/Slack/SlackRecord.php Executable file → Normal file
View File

View File

@@ -48,8 +48,18 @@ class SlackHandler extends SocketHandler
* @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] * @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
* @throws MissingExtensionException If no OpenSSL PHP extension configured * @throws MissingExtensionException If no OpenSSL PHP extension configured
*/ */
public function __construct($token, $channel, $username = null, $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, bool $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array()) public function __construct(
{ string $token,
string $channel,
?string $username = null,
bool $useAttachment = true,
?string $iconEmoji = null,
$level = Logger::CRITICAL,
bool $bubble = true,
bool $useShortAttachment = false,
bool $includeContextAndExtra = false,
array $excludeFields = array()
) {
if (!extension_loaded('openssl')) { if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler'); throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
} }
@@ -69,23 +79,20 @@ class SlackHandler extends SocketHandler
$this->token = $token; $this->token = $token;
} }
public function getSlackRecord() public function getSlackRecord(): SlackRecord
{ {
return $this->slackRecord; return $this->slackRecord;
} }
public function getToken() public function getToken(): string
{ {
return $this->token; return $this->token;
} }
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
* @return string
*/ */
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
$content = $this->buildContent($record); $content = $this->buildContent($record);
@@ -94,24 +101,15 @@ class SlackHandler extends SocketHandler
/** /**
* Builds the body of API call * Builds the body of API call
*
* @param array $record
* @return string
*/ */
private function buildContent($record) private function buildContent(array $record): string
{ {
$dataArray = $this->prepareContentData($record); $dataArray = $this->prepareContentData($record);
return http_build_query($dataArray); return http_build_query($dataArray);
} }
/** protected function prepareContentData(array $record): array
* Prepares content data
*
* @param array $record
* @return array
*/
protected function prepareContentData($record)
{ {
$dataArray = $this->slackRecord->getSlackData($record); $dataArray = $this->slackRecord->getSlackData($record);
$dataArray['token'] = $this->token; $dataArray['token'] = $this->token;
@@ -125,11 +123,8 @@ class SlackHandler extends SocketHandler
/** /**
* Builds the header of the API Call * Builds the header of the API Call
*
* @param string $content
* @return string
*/ */
private function buildHeader($content) private function buildHeader(string $content): string
{ {
$header = "POST /api/chat.postMessage HTTP/1.1\r\n"; $header = "POST /api/chat.postMessage HTTP/1.1\r\n";
$header .= "Host: slack.com\r\n"; $header .= "Host: slack.com\r\n";
@@ -142,8 +137,6 @@ class SlackHandler extends SocketHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
*/ */
protected function write(array $record): void protected function write(array $record): void
{ {
@@ -157,7 +150,7 @@ class SlackHandler extends SocketHandler
* If we do not read some but close the socket too early, slack sometimes * If we do not read some but close the socket too early, slack sometimes
* drops the request entirely. * drops the request entirely.
*/ */
protected function finalizeWrite() protected function finalizeWrite(): void
{ {
$res = $this->getResource(); $res = $this->getResource();
if (is_resource($res)) { if (is_resource($res)) {
@@ -166,41 +159,6 @@ class SlackHandler extends SocketHandler
$this->closeSocket(); $this->closeSocket();
} }
/**
* Returned a Slack message attachment color associated with
* provided level.
*
* @param int $level
* @return string
* @deprecated Use underlying SlackRecord instead
*/
protected function getAttachmentColor($level)
{
trigger_error(
'SlackHandler::getAttachmentColor() is deprecated. Use underlying SlackRecord instead.',
E_USER_DEPRECATED
);
return $this->slackRecord->getAttachmentColor($level);
}
/**
* Stringifies an array of key/value pairs to be used in attachment fields
*
* @param array $fields
* @return string
* @deprecated Use underlying SlackRecord instead
*/
protected function stringify($fields)
{
trigger_error(
'SlackHandler::stringify() is deprecated. Use underlying SlackRecord instead.',
E_USER_DEPRECATED
);
return $this->slackRecord->stringify($fields);
}
public function setFormatter(FormatterInterface $formatter): HandlerInterface public function setFormatter(FormatterInterface $formatter): HandlerInterface
{ {
parent::setFormatter($formatter); parent::setFormatter($formatter);

View File

@@ -43,12 +43,22 @@ class SlackWebhookHandler extends AbstractProcessingHandler
* @param string|null $iconEmoji The emoji name to use (or null) * @param string|null $iconEmoji The emoji name to use (or null)
* @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
* @param bool $includeContextAndExtra Whether the attachment should include context and extra data * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2'] * @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
*/ */
public function __construct($webhookUrl, $channel = null, $username = null, $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, $level = Logger::CRITICAL, bool $bubble = true, array $excludeFields = array()) public function __construct(
{ string $webhookUrl,
?string $channel = null,
?string $username = null,
bool $useAttachment = true,
?string $iconEmoji = null,
bool $useShortAttachment = false,
bool $includeContextAndExtra = false,
$level = Logger::CRITICAL,
bool $bubble = true,
array $excludeFields = array()
) {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->webhookUrl = $webhookUrl; $this->webhookUrl = $webhookUrl;
@@ -64,12 +74,12 @@ class SlackWebhookHandler extends AbstractProcessingHandler
); );
} }
public function getSlackRecord() public function getSlackRecord(): SlackRecord
{ {
return $this->slackRecord; return $this->slackRecord;
} }
public function getWebhookUrl() public function getWebhookUrl(): string
{ {
return $this->webhookUrl; return $this->webhookUrl;
} }

View File

@@ -43,10 +43,10 @@ class SlackbotHandler extends AbstractProcessingHandler
* @param string $slackTeam Slack team slug * @param string $slackTeam Slack team slug
* @param string $token Slackbot token * @param string $token Slackbot token
* @param string $channel Slack channel (encoded ID or name) * @param string $channel Slack channel (encoded ID or name)
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($slackTeam, $token, $channel, $level = Logger::CRITICAL, bool $bubble = true) public function __construct(string $slackTeam, string $token, string $channel, $level = Logger::CRITICAL, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
@@ -57,8 +57,6 @@ class SlackbotHandler extends AbstractProcessingHandler
/** /**
* {@inheritdoc} * {@inheritdoc}
*
* @param array $record
*/ */
protected function write(array $record): void protected function write(array $record): void
{ {

View File

@@ -39,10 +39,10 @@ class SocketHandler extends AbstractProcessingHandler
/** /**
* @param string $connectionString Socket connection string * @param string $connectionString Socket connection string
* @param int $level The minimum logging level at which this handler will be triggered * @param int|string $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct($connectionString, $level = Logger::DEBUG, bool $bubble = true) public function __construct(string $connectionString, $level = Logger::DEBUG, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
$this->connectionString = $connectionString; $this->connectionString = $connectionString;
@@ -88,9 +88,11 @@ class SocketHandler extends AbstractProcessingHandler
/** /**
* Set socket connection to be persistent. It only has effect before the connection is initiated. * Set socket connection to be persistent. It only has effect before the connection is initiated.
*/ */
public function setPersistent(bool $persistent): void public function setPersistent(bool $persistent): self
{ {
$this->persistent = $persistent; $this->persistent = $persistent;
return $this;
} }
/** /**
@@ -98,10 +100,12 @@ class SocketHandler extends AbstractProcessingHandler
* *
* @see http://php.net/manual/en/function.fsockopen.php * @see http://php.net/manual/en/function.fsockopen.php
*/ */
public function setConnectionTimeout(float $seconds): void public function setConnectionTimeout(float $seconds): self
{ {
$this->validateTimeout($seconds); $this->validateTimeout($seconds);
$this->connectionTimeout = (float) $seconds; $this->connectionTimeout = $seconds;
return $this;
} }
/** /**
@@ -109,10 +113,12 @@ class SocketHandler extends AbstractProcessingHandler
* *
* @see http://php.net/manual/en/function.stream-set-timeout.php * @see http://php.net/manual/en/function.stream-set-timeout.php
*/ */
public function setTimeout(float $seconds): void public function setTimeout(float $seconds): self
{ {
$this->validateTimeout($seconds); $this->validateTimeout($seconds);
$this->timeout = (float) $seconds; $this->timeout = $seconds;
return $this;
} }
/** /**
@@ -120,18 +126,22 @@ class SocketHandler extends AbstractProcessingHandler
* *
* @param float $seconds 0 for no timeout * @param float $seconds 0 for no timeout
*/ */
public function setWritingTimeout(float $seconds): void public function setWritingTimeout(float $seconds): self
{ {
$this->validateTimeout($seconds); $this->validateTimeout($seconds);
$this->writingTimeout = (float) $seconds; $this->writingTimeout = $seconds;
return $this;
} }
/** /**
* Set chunk size. Only has effect during connection in the writing cycle. * Set chunk size. Only has effect during connection in the writing cycle.
*/ */
public function setChunkSize(int $bytes): void public function setChunkSize(int $bytes): self
{ {
$this->chunkSize = $bytes; $this->chunkSize = $bytes;
return $this;
} }
/** /**
@@ -144,10 +154,8 @@ class SocketHandler extends AbstractProcessingHandler
/** /**
* Get persistent setting * Get persistent setting
*
* @return bool
*/ */
public function isPersistent() public function isPersistent(): bool
{ {
return $this->persistent; return $this->persistent;
} }
@@ -268,7 +276,7 @@ class SocketHandler extends AbstractProcessingHandler
$this->connect(); $this->connect();
} }
protected function generateDataStream($record) protected function generateDataStream(array $record): string
{ {
return (string) $record['formatted']; return (string) $record['formatted'];
} }
@@ -281,14 +289,14 @@ class SocketHandler extends AbstractProcessingHandler
return $this->resource; return $this->resource;
} }
private function connect() private function connect(): void
{ {
$this->createSocketResource(); $this->createSocketResource();
$this->setSocketTimeout(); $this->setSocketTimeout();
$this->setStreamChunkSize(); $this->setStreamChunkSize();
} }
private function createSocketResource() private function createSocketResource(): void
{ {
if ($this->isPersistent()) { if ($this->isPersistent()) {
$resource = $this->pfsockopen(); $resource = $this->pfsockopen();
@@ -301,21 +309,21 @@ class SocketHandler extends AbstractProcessingHandler
$this->resource = $resource; $this->resource = $resource;
} }
private function setSocketTimeout() private function setSocketTimeout(): void
{ {
if (!$this->streamSetTimeout()) { if (!$this->streamSetTimeout()) {
throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()"); throw new \UnexpectedValueException("Failed setting timeout with stream_set_timeout()");
} }
} }
private function setStreamChunkSize() private function setStreamChunkSize(): void
{ {
if ($this->chunkSize && !$this->streamSetChunkSize()) { if ($this->chunkSize && !$this->streamSetChunkSize()) {
throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()"); throw new \UnexpectedValueException("Failed setting chunk size with stream_set_chunk_size()");
} }
} }
private function writeToSocket($data) private function writeToSocket(string $data): void
{ {
$length = strlen($data); $length = strlen($data);
$sent = 0; $sent = 0;
@@ -344,7 +352,7 @@ class SocketHandler extends AbstractProcessingHandler
} }
} }
private function writingIsTimedOut($sent) private function writingIsTimedOut(int $sent): bool
{ {
$writingTimeout = (int) floor($this->writingTimeout); $writingTimeout = (int) floor($this->writingTimeout);
if (0 === $writingTimeout) { if (0 === $writingTimeout) {

View File

@@ -31,7 +31,7 @@ class SqsHandler extends AbstractProcessingHandler
/** @var string */ /** @var string */
private $queueUrl; private $queueUrl;
public function __construct(SqsClient $sqsClient, $queueUrl, $level = Logger::DEBUG, bool $bubble = true) public function __construct(SqsClient $sqsClient, string $queueUrl, $level = Logger::DEBUG, bool $bubble = true)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);

View File

@@ -33,7 +33,7 @@ class StreamHandler extends AbstractProcessingHandler
/** /**
* @param resource|string $stream * @param resource|string $stream
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write) * @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 * @param bool $useLocking Try to lock log file before doing any writes
@@ -41,7 +41,7 @@ class StreamHandler extends AbstractProcessingHandler
* @throws \Exception If a missing directory is not buildable * @throws \Exception If a missing directory is not buildable
* @throws \InvalidArgumentException If stream is not a resource or string * @throws \InvalidArgumentException If stream is not a resource or string
*/ */
public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, $filePermission = null, $useLocking = false) public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, ?int $filePermission = null, bool $useLocking = false)
{ {
parent::__construct($level, $bubble); parent::__construct($level, $bubble);
if (is_resource($stream)) { if (is_resource($stream)) {
@@ -82,7 +82,7 @@ class StreamHandler extends AbstractProcessingHandler
* *
* @return string|null * @return string|null
*/ */
public function getUrl() public function getUrl(): ?string
{ {
return $this->url; return $this->url;
} }
@@ -128,12 +128,12 @@ class StreamHandler extends AbstractProcessingHandler
* @param resource $stream * @param resource $stream
* @param array $record * @param array $record
*/ */
protected function streamWrite($stream, array $record) protected function streamWrite($stream, array $record): void
{ {
fwrite($stream, (string) $record['formatted']); fwrite($stream, (string) $record['formatted']);
} }
private function customErrorHandler($code, $msg) private function customErrorHandler($code, $msg): void
{ {
$this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg); $this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
} }
@@ -152,7 +152,7 @@ class StreamHandler extends AbstractProcessingHandler
return null; return null;
} }
private function createDir() private function createDir(): void
{ {
// Do not try to create dir if it has already been tried. // Do not try to create dir if it has already been tried.
if ($this->dirCreated) { if ($this->dirCreated) {

View File

@@ -30,7 +30,7 @@ class SwiftMailerHandler extends MailHandler
/** /**
* @param \Swift_Mailer $mailer The mailer to use * @param \Swift_Mailer $mailer The mailer to use
* @param callable|Swift_Message $message An example message for real messages, only the body will be replaced * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced
* @param int|string $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/ */
public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, bool $bubble = true) public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, bool $bubble = true)

View File

@@ -33,12 +33,12 @@ class SyslogHandler extends AbstractSyslogHandler
/** /**
* @param string $ident * @param string $ident
* @param mixed $facility * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @param int $logopts Option flags for the openlog() call, defaults to LOG_PID * @param int $logopts Option flags for the openlog() call, defaults to LOG_PID
*/ */
public function __construct($ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, $logopts = LOG_PID) public function __construct(string $ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, int $logopts = LOG_PID)
{ {
parent::__construct($facility, $level, $bubble); parent::__construct($facility, $level, $bubble);

View File

@@ -27,12 +27,12 @@ class SyslogUdpHandler extends AbstractSyslogHandler
/** /**
* @param string $host * @param string $host
* @param int $port * @param int $port
* @param mixed $facility * @param string|int $facility Either one of the names of the keys in $this->facilities, or a LOG_* facility constant
* @param int $level The minimum logging level at which this handler will be triggered * @param string|int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not * @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 string $ident Program name or tag for each log message.
*/ */
public function __construct($host, $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, $ident = 'php') public function __construct(string $host, int $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, string $ident = 'php')
{ {
parent::__construct($facility, $level, $bubble); parent::__construct($facility, $level, $bubble);
@@ -69,7 +69,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
/** /**
* Make common syslog header (see rfc5424) * Make common syslog header (see rfc5424)
*/ */
protected function makeCommonSyslogHeader($severity): string protected function makeCommonSyslogHeader(int $severity): string
{ {
$priority = $severity + $this->facility; $priority = $severity + $this->facility;
@@ -88,7 +88,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
$pid . " - - "; $pid . " - - ";
} }
protected function getDateTime() protected function getDateTime(): string
{ {
return date(\DateTime::RFC3339); return date(\DateTime::RFC3339);
} }
@@ -96,8 +96,10 @@ class SyslogUdpHandler extends AbstractSyslogHandler
/** /**
* Inject your own socket, mainly used for testing * Inject your own socket, mainly used for testing
*/ */
public function setSocket(UdpSocket $socket) public function setSocket(UdpSocket $socket): self
{ {
$this->socket = $socket; $this->socket = $socket;
return $this;
} }
} }

View File

@@ -11,6 +11,8 @@
namespace Monolog\Handler; namespace Monolog\Handler;
use Monolog\Logger;
/** /**
* Used for testing purposes. * Used for testing purposes.
* *
@@ -79,16 +81,19 @@ class TestHandler extends AbstractProcessingHandler
$this->recordsByLevel = []; $this->recordsByLevel = [];
} }
public function hasRecords($level) /**
* @param string|int $level Logging level value or name
*/
public function hasRecords($level): bool
{ {
return isset($this->recordsByLevel[$level]); return isset($this->recordsByLevel[Logger::toMonologLevel($level)]);
} }
/** /**
* @param string|array $record Either a message string or an array containing message and optionally context keys that will be checked against all records * @param string|array $record Either a message string or an array containing message and optionally context keys that will be checked against all records
* @param int $level Logger::LEVEL constant value * @param string|int $level Logging level value or name
*/ */
public function hasRecord($record, $level) public function hasRecord($record, $level): bool
{ {
if (is_string($record)) { if (is_string($record)) {
$record = array('message' => $record); $record = array('message' => $record);
@@ -106,22 +111,33 @@ class TestHandler extends AbstractProcessingHandler
}, $level); }, $level);
} }
public function hasRecordThatContains($message, $level) /**
* @param string|int $level Logging level value or name
*/
public function hasRecordThatContains(string $message, $level): bool
{ {
return $this->hasRecordThatPasses(function ($rec) use ($message) { return $this->hasRecordThatPasses(function ($rec) use ($message) {
return strpos($rec['message'], $message) !== false; return strpos($rec['message'], $message) !== false;
}, $level); }, $level);
} }
public function hasRecordThatMatches($regex, $level) /**
* @param string|int $level Logging level value or name
*/
public function hasRecordThatMatches(string $regex, $level): bool
{ {
return $this->hasRecordThatPasses(function ($rec) use ($regex) { return $this->hasRecordThatPasses(function ($rec) use ($regex) {
return preg_match($regex, $rec['message']) > 0; return preg_match($regex, $rec['message']) > 0;
}, $level); }, $level);
} }
/**
* @param string|int $level Logging level value or name
*/
public function hasRecordThatPasses(callable $predicate, $level) public function hasRecordThatPasses(callable $predicate, $level)
{ {
$level = Logger::toMonologLevel($level);
if (!isset($this->recordsByLevel[$level])) { if (!isset($this->recordsByLevel[$level])) {
return false; return false;
} }

View File

@@ -39,10 +39,8 @@ class ZendMonitorHandler extends AbstractProcessingHandler
]; ];
/** /**
* Construct * @param string|int $level The minimum logging level at which this handler will be triggered.
* * @param bool $bubble Whether the messages that are handled can bubble up the stack or not.
* @param int $level
* @param bool $bubble
* @throws MissingExtensionException * @throws MissingExtensionException
*/ */
public function __construct($level = Logger::DEBUG, bool $bubble = true) public function __construct($level = Logger::DEBUG, bool $bubble = true)
@@ -65,7 +63,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
); );
} }
protected function writeZendMonitorCustomEvent(int $level, string $message, array $formatted) protected function writeZendMonitorCustomEvent(int $level, string $message, array $formatted): void
{ {
zend_monitor_custom_event($level, $message, $formatted); zend_monitor_custom_event($level, $message, $formatted);
} }

View File

@@ -14,7 +14,7 @@ namespace Monolog\Processor;
/** /**
* Injects value of gethostname in all records * Injects value of gethostname in all records
*/ */
class HostnameProcessor class HostnameProcessor implements ProcessorInterface
{ {
private static $host; private static $host;

View File

@@ -25,14 +25,18 @@ class TagProcessor implements ProcessorInterface
$this->setTags($tags); $this->setTags($tags);
} }
public function addTags(array $tags = []) public function addTags(array $tags = []): self
{ {
$this->tags = array_merge($this->tags, $tags); $this->tags = array_merge($this->tags, $tags);
return $this;
} }
public function setTags(array $tags = []) public function setTags(array $tags = []): self
{ {
$this->tags = $tags; $this->tags = $tags;
return $this;
} }
public function __invoke(array $record): array public function __invoke(array $record): array

View File

@@ -136,7 +136,7 @@ class TestChromePHPHandler extends ChromePHPHandler
{ {
protected $headers = []; protected $headers = [];
public static function resetStatic() public static function resetStatic(): void
{ {
self::$initialized = false; self::$initialized = false;
self::$overflowed = false; self::$overflowed = false;
@@ -144,12 +144,12 @@ class TestChromePHPHandler extends ChromePHPHandler
self::$json['rows'] = []; self::$json['rows'] = [];
} }
protected function sendHeader($header, $content) protected function sendHeader(string $header, string $content): void
{ {
$this->headers[$header] = $content; $this->headers[$header] = $content;
} }
public function getHeaders() public function getHeaders(): array
{ {
return $this->headers; return $this->headers;
} }

View File

@@ -77,19 +77,19 @@ class TestFirePHPHandler extends FirePHPHandler
{ {
protected $headers = []; protected $headers = [];
public static function resetStatic() public static function resetStatic(): void
{ {
self::$initialized = false; self::$initialized = false;
self::$sendHeaders = true; self::$sendHeaders = true;
self::$messageIndex = 1; self::$messageIndex = 1;
} }
protected function sendHeader($header, $content) protected function sendHeader(string $header, string $content): void
{ {
$this->headers[$header] = $content; $this->headers[$header] = $content;
} }
public function getHeaders() public function getHeaders(): array
{ {
return $this->headers; return $this->headers;
} }

View File

@@ -163,7 +163,7 @@ class NewRelicHandlerTest extends TestCase
class StubNewRelicHandlerWithoutExtension extends NewRelicHandler class StubNewRelicHandlerWithoutExtension extends NewRelicHandler
{ {
protected function isNewRelicEnabled() protected function isNewRelicEnabled(): bool
{ {
return false; return false;
} }
@@ -171,7 +171,7 @@ class StubNewRelicHandlerWithoutExtension extends NewRelicHandler
class StubNewRelicHandler extends NewRelicHandler class StubNewRelicHandler extends NewRelicHandler
{ {
protected function isNewRelicEnabled() protected function isNewRelicEnabled(): bool
{ {
return true; return true;
} }

View File

@@ -13,6 +13,7 @@ namespace Monolog\Handler;
use Monolog\Test\TestCase; use Monolog\Test\TestCase;
use Monolog\Logger; use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
/** /**
* @covers Monolog\Handler\PsrHandler::handle * @covers Monolog\Handler\PsrHandler::handle
@@ -47,4 +48,21 @@ class PsrHandlerTest extends TestCase
$handler = new PsrHandler($psrLogger); $handler = new PsrHandler($psrLogger);
$handler->handle(['level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context]); $handler->handle(['level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context]);
} }
public function testFormatter()
{
$message = 'Hello, world!';
$context = ['foo' => 'bar'];
$level = Logger::ERROR;
$levelName = 'error';
$psrLogger = $this->createMock('Psr\Log\NullLogger');
$psrLogger->expects($this->once())
->method('log')
->with(strtolower($levelName), 'dummy', $context);
$handler = new PsrHandler($psrLogger);
$handler->setFormatter(new LineFormatter('dummy'));
$handler->handle(['level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context, 'extra' => [], 'date' => new \DateTimeImmutable()]);
}
} }

View File

@@ -23,7 +23,7 @@ class SyslogUdpHandlerTest extends TestCase
*/ */
public function testWeValidateFacilities() public function testWeValidateFacilities()
{ {
$handler = new SyslogUdpHandler("ip", null, "invalidFacility"); $handler = new SyslogUdpHandler("ip", 514, "invalidFacility");
} }
public function testWeSplitIntoLines() public function testWeSplitIntoLines()