1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-05 04:37:38 +02:00

Merge branch 'master' into master

This commit is contained in:
Jordi Boggiano
2018-11-03 18:06:42 +01:00
committed by GitHub
81 changed files with 259 additions and 342 deletions

View File

@@ -6,6 +6,7 @@ dist: trusty
php:
- 7.1
- 7.2
- 7.3
- nightly
cache:

View File

@@ -2,7 +2,7 @@
* Added ability to customize error handling at the Logger level using Logger::setExceptionHandler
* Added InsightOpsHandler to migrate users of the LogEntriesHandler
* Added protection to NormalizerHandler against circular and very deep structures, it now stops normalizing at a depth of 9
* Added protection to NormalizerFormatter against circular and very deep structures, it now stops normalizing at a depth of 9
* Added capture of stack traces to ErrorHandler when logging PHP errors
* Added forwarding of context info to FluentdFormatter
* Added SocketHandler::setChunkSize to override the default chunk size in case you must send large log lines to rsyslog for example

View File

@@ -30,13 +30,13 @@ class PDOHandler extends AbstractProcessingHandler
private $pdo;
private $statement;
public function __construct(PDO $pdo, $level = Logger::DEBUG, $bubble = true)
public function __construct(PDO $pdo, $level = Logger::DEBUG, bool $bubble = true)
{
$this->pdo = $pdo;
parent::__construct($level, $bubble);
}
protected function write(array $record)
protected function write(array $record): void
{
if (!$this->initialized) {
$this->initialize();

View File

@@ -11,6 +11,8 @@
namespace Monolog;
use DateTimeZone;
/**
* Overrides default json encoding of date time objects
*
@@ -19,9 +21,12 @@ namespace Monolog;
*/
class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable
{
/**
* @var bool
*/
private $useMicroseconds;
public function __construct($useMicroseconds, \DateTimeZone $timezone = null)
public function __construct(bool $useMicroseconds, ?DateTimeZone $timezone = null)
{
$this->useMicroseconds = $useMicroseconds;

View File

@@ -58,13 +58,13 @@ class GelfMessageFormatter extends NormalizerFormatter
Logger::EMERGENCY => 0,
];
public function __construct(string $systemName = null, string $extraPrefix = null, string $contextPrefix = 'ctxt_', int $maxLength = null)
public function __construct(?string $systemName = null, ?string $extraPrefix = null, string $contextPrefix = 'ctxt_', ?int $maxLength = null)
{
parent::__construct('U.u');
$this->systemName = $systemName ?: gethostname();
$this->systemName = (is_null($systemName) || $systemName === '') ? gethostname() : $systemName;
$this->extraPrefix = $extraPrefix;
$this->extraPrefix = is_null($extraPrefix) ? '' : $extraPrefix;
$this->contextPrefix = $contextPrefix;
$this->maxLength = is_null($maxLength) ? self::DEFAULT_MAX_LENGTH : $maxLength;
}

View File

@@ -37,9 +37,9 @@ class HtmlFormatter extends NormalizerFormatter
];
/**
* @param string $dateFormat The format of the timestamp: one supported by DateTime::format
* @param ?string $dateFormat The format of the timestamp: one supported by DateTime::format
*/
public function __construct(string $dateFormat = null)
public function __construct(?string $dateFormat = null)
{
parent::__construct($dateFormat);
}
@@ -47,10 +47,9 @@ class HtmlFormatter extends NormalizerFormatter
/**
* Creates an HTML table row
*
* @param string $th Row header content
* @param string $td Row standard cell content
* @param bool $escapeTd false if td content must not be html escaped
* @return string
* @param string $th Row header content
* @param string $td Row standard cell content
* @param bool $escapeTd false if td content must not be html escaped
*/
protected function addRow(string $th, string $td = ' ', bool $escapeTd = true): string
{
@@ -79,8 +78,8 @@ class HtmlFormatter extends NormalizerFormatter
/**
* Formats a log record.
*
* @param array $record A record to format
* @return mixed The formatted record
* @param array $record A record to format
* @return string The formatted record
*/
public function format(array $record): string
{
@@ -113,8 +112,8 @@ class HtmlFormatter extends NormalizerFormatter
/**
* Formats a set of log records.
*
* @param array $records A set of records to format
* @return mixed The formatted set of records
* @param array $records A set of records to format
* @return string The formatted set of records
*/
public function formatBatch(array $records): string
{

View File

@@ -61,6 +61,8 @@ class JsonFormatter extends NormalizerFormatter
/**
* {@inheritdoc}
*
* @suppress PhanTypeComparisonToArray
*/
public function format(array $record): string
{

View File

@@ -29,14 +29,14 @@ class LineFormatter extends NormalizerFormatter
protected $includeStacktraces;
/**
* @param string $format The format of the message
* @param string $dateFormat The format of the timestamp: one supported by DateTime::format
* @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries
* @param bool $ignoreEmptyContextAndExtra
* @param ?string $format The format of the message
* @param ?string $dateFormat The format of the timestamp: one supported by DateTime::format
* @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries
* @param bool $ignoreEmptyContextAndExtra
*/
public function __construct(string $format = null, string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false)
public function __construct(?string $format = null, ?string $dateFormat = null, bool $allowInlineLineBreaks = false, bool $ignoreEmptyContextAndExtra = false)
{
$this->format = $format ?: static::SIMPLE_FORMAT;
$this->format = $format === null ? static::SIMPLE_FORMAT : $format;
$this->allowInlineLineBreaks = $allowInlineLineBreaks;
$this->ignoreEmptyContextAndExtra = $ignoreEmptyContextAndExtra;
parent::__construct($dateFormat);
@@ -124,6 +124,9 @@ class LineFormatter extends NormalizerFormatter
return $this->replaceNewlines($this->convertToString($value));
}
/**
* @suppress PhanParamSignatureMismatch
*/
protected function normalizeException(\Throwable $e, int $depth = 0): string
{
$str = $this->formatException($e);

View File

@@ -21,30 +21,20 @@ class LogmaticFormatter extends JsonFormatter
const MARKERS = ["sourcecode", "php"];
/**
* @param string
* @var string
*/
protected $hostname = '';
/**
* @param string
* @var string
*/
protected $appname = '';
/**
* Set hostname
*
* @param string $hostname
*/
public function setHostname(string $hostname)
{
$this->hostname = $hostname;
}
/**
* Set appname
*
* @param string $appname
*/
public function setAppname(string $appname)
{
$this->appname = $appname;

View File

@@ -42,17 +42,17 @@ class LogstashFormatter extends NormalizerFormatter
protected $contextKey;
/**
* @param string $applicationName the application that sends the data, used as the "type" field of logstash
* @param string $systemName the system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine
* @param string $extraKey the key for extra keys inside logstash "fields", defaults to extra
* @param string $contextKey the key for context keys inside logstash "fields", defaults to context
* @param string $applicationName the application that sends the data, used as the "type" field of logstash
* @param ?string $systemName the system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine
* @param string $extraKey the key for extra keys inside logstash "fields", defaults to extra
* @param string $contextKey the key for context keys inside logstash "fields", defaults to context
*/
public function __construct(string $applicationName, string $systemName = null, string $extraKey = 'extra', string $contextKey = 'context')
public function __construct(string $applicationName, ?string $systemName = null, string $extraKey = 'extra', string $contextKey = 'context')
{
// logstash requires a ISO 8601 format date with optional millisecond precision.
parent::__construct('Y-m-d\TH:i:s.uP');
$this->systemName = $systemName ?: gethostname();
$this->systemName = $systemName === null ? gethostname() : $systemName;
$this->applicationName = $applicationName;
$this->extraKey = $extraKey;
$this->contextKey = $contextKey;

View File

@@ -28,9 +28,9 @@ class NormalizerFormatter implements FormatterInterface
protected $maxNormalizeItemCount = 1000;
/**
* @param string $dateFormat The format of the timestamp: one supported by DateTime::format
* @param ?string $dateFormat The format of the timestamp: one supported by DateTime::format
*/
public function __construct(string $dateFormat = null)
public function __construct(?string $dateFormat = null)
{
$this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat;
if (!function_exists('json_encode')) {

View File

@@ -91,7 +91,7 @@ class WildfireFormatter extends NormalizerFormatter
// The message itself is a serialization of the above JSON object + it's length
return sprintf(
'%s|%s|',
'%d|%s|',
strlen($json),
$json
);
@@ -107,6 +107,7 @@ class WildfireFormatter extends NormalizerFormatter
/**
* {@inheritdoc}
* @suppress PhanTypeMismatchReturn
*/
protected function normalize($data, int $depth = 0)
{

View File

@@ -27,7 +27,7 @@ abstract class AbstractHandler extends Handler
* @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
*/
public function __construct($level = Logger::DEBUG, $bubble = true)
public function __construct($level = Logger::DEBUG, bool $bubble = true)
{
$this->setLevel($level);
$this->bubble = $bubble;

View File

@@ -46,9 +46,6 @@ abstract class AbstractProcessingHandler extends AbstractHandler implements Proc
/**
* Writes the record down to the log of the implementing handler
*
* @param array $record
* @return void
*/
abstract protected function write(array $record);
abstract protected function write(array $record): void;
}

View File

@@ -54,11 +54,11 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
];
/**
* @param mixed $facility
* @param 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 mixed $facility
* @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
*/
public function __construct($facility = LOG_USER, $level = Logger::DEBUG, $bubble = true)
public function __construct($facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);

View File

@@ -33,10 +33,10 @@ class AmqpHandler extends AbstractProcessingHandler
/**
* @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use
* @param string $exchangeName Optional exchange name, for AMQPChannel (PhpAmqpLib) only
* @param int $level
* @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
*/
public function __construct($exchange, $exchangeName = null, $level = Logger::DEBUG, $bubble = true)
public function __construct($exchange, ?string $exchangeName = null, $level = Logger::DEBUG, bool $bubble = true)
{
if ($exchange instanceof AMQPChannel) {
$this->exchangeName = $exchangeName;
@@ -53,7 +53,7 @@ class AmqpHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$data = $record["formatted"];
$routingKey = $this->getRoutingKey($record);
@@ -80,7 +80,7 @@ class AmqpHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
if ($this->exchange instanceof AMQPExchange) {
parent::handleBatch($records);
@@ -108,25 +108,18 @@ class AmqpHandler extends AbstractProcessingHandler
/**
* Gets the routing key for the AMQP exchange
*
* @param array $record
* @return string
*/
protected function getRoutingKey(array $record)
protected function getRoutingKey(array $record): string
{
$routingKey = sprintf('%s.%s', $record['level_name'], $record['channel']);
return strtolower($routingKey);
}
/**
* @param string $data
* @return AMQPMessage
*/
private function createAmqpMessage($data)
private function createAmqpMessage(string $data): AMQPMessage
{
return new AMQPMessage(
(string) $data,
$data,
[
'delivery_mode' => 2,
'content_type' => 'application/json',

View File

@@ -41,7 +41,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
// Accumulate records
static::$records[] = $record;

View File

@@ -39,7 +39,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
* @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
*/
public function __construct(HandlerInterface $handler, $bufferLimit = 0, $level = Logger::DEBUG, $bubble = true, $flushOnOverflow = false)
public function __construct(HandlerInterface $handler, $bufferLimit = 0, $level = Logger::DEBUG, bool $bubble = true, $flushOnOverflow = false)
{
parent::__construct($level, $bubble);
$this->handler = $handler;
@@ -101,7 +101,7 @@ class BufferHandler extends AbstractHandler implements ProcessableHandlerInterfa
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
$this->flush();
}

View File

@@ -64,7 +64,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct($level = Logger::DEBUG, $bubble = true)
public function __construct($level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);
if (!function_exists('json_encode')) {
@@ -75,7 +75,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
if (!$this->isWebRequest()) {
return;
@@ -112,7 +112,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
* @see send()
* @param array $record
*/
protected function write(array $record)
protected function write(array $record): void
{
if (!$this->isWebRequest()) {
return;

View File

@@ -24,7 +24,7 @@ class CouchDBHandler extends AbstractProcessingHandler
{
private $options;
public function __construct(array $options = [], $level = Logger::DEBUG, $bubble = true)
public function __construct(array $options = [], $level = Logger::DEBUG, bool $bubble = true)
{
$this->options = array_merge([
'host' => 'localhost',
@@ -40,7 +40,7 @@ class CouchDBHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$basicAuth = null;
if ($this->options['username']) {

View File

@@ -35,7 +35,7 @@ class CubeHandler extends AbstractProcessingHandler
* A valid url must consist of three parts : protocol://host:port
* Only valid protocols used by Cube are http and udp
*/
public function __construct($url, $level = Logger::DEBUG, $bubble = true)
public function __construct($url, $level = Logger::DEBUG, bool $bubble = true)
{
$urlInfo = parse_url($url);
@@ -102,7 +102,7 @@ class CubeHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$date = $record['datetime'];

View File

@@ -29,7 +29,7 @@ class Util
* @param resource $ch curl handler
* @throws \RuntimeException
*/
public static function execute($ch, $retries = 5, $closeAfterDone = true)
public static function execute($ch, int $retries = 5, bool $closeAfterDone = true): void
{
while ($retries--) {
if (curl_exec($ch) === false) {
@@ -42,7 +42,7 @@ class Util
curl_close($ch);
}
throw new \RuntimeException(sprintf('Curl error (code %s): %s', $curlErrno, $curlError));
throw new \RuntimeException(sprintf('Curl error (code %d): %s', $curlErrno, $curlError));
}
continue;

View File

@@ -62,7 +62,7 @@ class DeduplicationHandler extends BufferHandler
* @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
*/
public function __construct(HandlerInterface $handler, $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, $time = 60, $bubble = true)
public function __construct(HandlerInterface $handler, $deduplicationStore = null, $deduplicationLevel = Logger::ERROR, $time = 60, bool $bubble = true)
{
parent::__construct($handler, 0, Logger::DEBUG, $bubble, false);

View File

@@ -25,7 +25,7 @@ class DoctrineCouchDBHandler extends AbstractProcessingHandler
{
private $client;
public function __construct(CouchDBClient $client, $level = Logger::DEBUG, $bubble = true)
public function __construct(CouchDBClient $client, $level = Logger::DEBUG, bool $bubble = true)
{
$this->client = $client;
parent::__construct($level, $bubble);
@@ -34,7 +34,7 @@ class DoctrineCouchDBHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$this->client->postDocument($record['formatted']);
}

View File

@@ -54,7 +54,7 @@ class DynamoDbHandler extends AbstractProcessingHandler
* @param int $level
* @param bool $bubble
*/
public function __construct(DynamoDbClient $client, $table, $level = Logger::DEBUG, $bubble = true)
public function __construct(DynamoDbClient $client, $table, $level = Logger::DEBUG, bool $bubble = true)
{
if (defined('Aws\Sdk::VERSION') && version_compare(Sdk::VERSION, '3.0', '>=')) {
$this->version = 3;
@@ -72,7 +72,7 @@ class DynamoDbHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$filtered = $this->filterEmptyFields($record['formatted']);
if ($this->version === 3) {

View File

@@ -51,7 +51,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, $bubble = true)
public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);
$this->client = $client;
@@ -68,7 +68,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$this->bulkSend([$record['formatted']]);
}
@@ -105,7 +105,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
$documents = $this->getFormatter()->formatBatch($records);
$this->bulkSend($documents);

View File

@@ -34,7 +34,7 @@ class ErrorLogHandler extends AbstractProcessingHandler
* @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
*/
public function __construct($messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, $bubble = true, $expandNewlines = false)
public function __construct($messageType = self::OPERATING_SYSTEM, $level = Logger::DEBUG, bool $bubble = true, $expandNewlines = false)
{
parent::__construct($level, $bubble);
@@ -70,7 +70,7 @@ class ErrorLogHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
if (!$this->expandNewlines) {
error_log((string) $record['formatted'], $this->messageType);

View File

@@ -52,7 +52,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface
* @param int $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
*/
public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, $bubble = true)
public function __construct($handler, $minLevelOrList = Logger::DEBUG, $maxLevel = Logger::EMERGENCY, bool $bubble = true)
{
$this->handler = $handler;
$this->bubble = $bubble;
@@ -126,7 +126,7 @@ class FilterHandler extends Handler implements ProcessableHandlerInterface
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
$filtered = [];
foreach ($records as $record) {

View File

@@ -20,9 +20,6 @@ interface ActivationStrategyInterface
{
/**
* Returns whether the given record activates the handler.
*
* @param array $record
* @return bool
*/
public function isHandlerActivated(array $record): bool;
}

View File

@@ -46,7 +46,7 @@ class ChannelLevelActivationStrategy implements ActivationStrategyInterface
private $channelToActionLevel;
/**
* @param string|int $defaultActionLevel The default action level to be used if the record's category doesn't match any
* @param int|string $defaultActionLevel The default action level to be used if the record's category doesn't match any
* @param array $channelToActionLevel An array that maps channel names to action levels.
*/
public function __construct($defaultActionLevel, array $channelToActionLevel = [])

View File

@@ -26,7 +26,7 @@ class ErrorLevelActivationStrategy implements ActivationStrategyInterface
private $actionLevel;
/**
* @param string|int $actionLevel
* @param int|string $actionLevel Level or name or value
*/
public function __construct($actionLevel)
{

View File

@@ -47,7 +47,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
* @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
*/
public function __construct($handler, $activationStrategy = null, $bufferSize = 0, $bubble = true, $stopBuffering = true, $passthruLevel = null)
public function __construct($handler, $activationStrategy = null, $bufferSize = 0, bool $bubble = true, $stopBuffering = true, $passthruLevel = null)
{
if (null === $activationStrategy) {
$activationStrategy = new ErrorLevelActivationStrategy(Logger::WARNING);
@@ -128,7 +128,7 @@ class FingersCrossedHandler extends Handler implements ProcessableHandlerInterfa
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
if (null !== $this->passthruLevel) {
$level = $this->passthruLevel;

View File

@@ -130,7 +130,7 @@ class FirePHPHandler extends AbstractProcessingHandler
* @see sendInitHeaders()
* @param array $record
*/
protected function write(array $record)
protected function write(array $record): void
{
if (!self::$sendHeaders || !$this->isWebRequest()) {
return;

View File

@@ -45,7 +45,7 @@ class FleepHookHandler extends SocketHandler
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
* @throws MissingExtensionException
*/
public function __construct($token, $level = Logger::DEBUG, $bubble = true)
public function __construct($token, $level = Logger::DEBUG, bool $bubble = true)
{
if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FleepHookHandler');
@@ -74,7 +74,7 @@ class FleepHookHandler extends SocketHandler
*
* @param array $record
*/
public function write(array $record)
public function write(array $record): void
{
parent::write($record);
$this->closeSocket();

View File

@@ -40,7 +40,7 @@ class FlowdockHandler extends SocketHandler
*
* @throws MissingExtensionException if OpenSSL is missing
*/
public function __construct($apiToken, $level = Logger::DEBUG, $bubble = true)
public function __construct($apiToken, $level = Logger::DEBUG, bool $bubble = true)
{
if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the FlowdockHandler');
@@ -64,8 +64,6 @@ class FlowdockHandler extends SocketHandler
/**
* Gets the default formatter.
*
* @suppress PhanTypeMissingReturn
*/
protected function getDefaultFormatter(): FormatterInterface
{
@@ -77,7 +75,7 @@ class FlowdockHandler extends SocketHandler
*
* @param array $record
*/
protected function write(array $record)
protected function write(array $record): void
{
parent::write($record);

View File

@@ -28,6 +28,7 @@ trait FormattableHandlerTrait
/**
* {@inheritdoc}
* @suppress PhanTypeMismatchReturn
*/
public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
@@ -51,6 +52,8 @@ trait FormattableHandlerTrait
/**
* Gets the default formatter.
*
* Overwrite this if the LineFormatter is not a good default for your handler.
*
* @return FormatterInterface
*/
protected function getDefaultFormatter(): FormatterInterface

View File

@@ -34,7 +34,7 @@ class GelfHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, $bubble = true)
public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);
@@ -44,7 +44,7 @@ class GelfHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$this->publisher->publish($record['formatted']);
}

View File

@@ -28,7 +28,7 @@ class GroupHandler extends Handler implements ProcessableHandlerInterface
* @param array $handlers Array of Handlers.
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct(array $handlers, $bubble = true)
public function __construct(array $handlers, bool $bubble = true)
{
foreach ($handlers as $handler) {
if (!$handler instanceof HandlerInterface) {
@@ -73,7 +73,7 @@ class GroupHandler extends Handler implements ProcessableHandlerInterface
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
if ($this->processors) {
$processed = [];

View File

@@ -21,7 +21,7 @@ abstract class Handler implements HandlerInterface
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
foreach ($records as $record) {
$this->handle($record);
@@ -31,7 +31,7 @@ abstract class Handler implements HandlerInterface
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
}

View File

@@ -54,7 +54,7 @@ interface HandlerInterface
*
* @param array $records The records to handle (an array of record arrays)
*/
public function handleBatch(array $records);
public function handleBatch(array $records): void;
/**
* Closes the handler.
@@ -64,5 +64,5 @@ interface HandlerInterface
* Implementations have to be idempotent (i.e. it should be possible to call close several times without breakage)
* and ideally handlers should be able to reopen themselves on handle() after they have been closed.
*/
public function close();
public function close(): void;
}

View File

@@ -65,17 +65,17 @@ class HandlerWrapper implements HandlerInterface, ProcessableHandlerInterface, F
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
return $this->handler->handleBatch($records);
$this->handler->handleBatch($records);
}
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
return $this->handler->close();
$this->handler->close();
}
/**

View File

@@ -80,7 +80,7 @@ class HipChatHandler extends SocketHandler
* @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.
*/
public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com')
public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, bool $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com')
{
$connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80';
parent::__construct($connectionString, $level, $bubble);
@@ -140,11 +140,8 @@ class HipChatHandler extends SocketHandler
/**
* Builds the header of the API Call
*
* @param string $content
* @return string
*/
private function buildHeader($content)
private function buildHeader(string $content): string
{
// needed for rooms with special (spaces, etc) characters in the name
$room = rawurlencode($this->room);
@@ -160,11 +157,8 @@ class HipChatHandler extends SocketHandler
/**
* Assigns a color to each level of log records.
*
* @param int $level
* @return string
*/
protected function getAlertColor($level)
protected function getAlertColor(int $level): string
{
switch (true) {
case $level >= Logger::ERROR:
@@ -182,10 +176,8 @@ class HipChatHandler extends SocketHandler
/**
* {@inheritdoc}
*
* @param array $record
*/
protected function write(array $record)
protected function write(array $record): void
{
parent::write($record);
$this->finalizeWrite();
@@ -197,7 +189,7 @@ class HipChatHandler extends SocketHandler
* If we do not read some but close the socket too early, hipchat sometimes
* drops the request entirely.
*/
protected function finalizeWrite()
protected function finalizeWrite(): void
{
$res = $this->getResource();
if (is_resource($res)) {
@@ -209,38 +201,25 @@ class HipChatHandler extends SocketHandler
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
if (count($records) == 0) {
return true;
return;
}
$batchRecords = $this->combineRecords($records);
$handled = false;
foreach ($batchRecords as $batchRecord) {
if ($this->isHandling($batchRecord)) {
$this->write($batchRecord);
$handled = true;
}
$this->handle($batchRecord);
}
if (!$handled) {
return false;
}
return false === $this->bubble;
}
/**
* Combines multiple records into one. Error level of the combined record
* will be the highest level from the given records. Datetime will be taken
* from the first record.
*
* @param $records
* @return array
*/
private function combineRecords($records)
private function combineRecords(array $records): array
{
$batchRecord = null;
$batchRecords = [];

View File

@@ -35,7 +35,7 @@ class IFTTTHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct($eventName, $secretKey, $level = Logger::ERROR, $bubble = true)
public function __construct($eventName, $secretKey, $level = Logger::ERROR, bool $bubble = true)
{
$this->eventName = $eventName;
$this->secretKey = $secretKey;
@@ -46,7 +46,7 @@ class IFTTTHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
public function write(array $record)
public function write(array $record): void
{
$postData = [
"value1" => $record["channel"],

View File

@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Logger;
/**
/**
* Inspired on LogEntriesHandler.
*
* @author Robert Kaufmann III <rok3@rok3.me>
@@ -35,7 +35,7 @@ class InsightOpsHandler extends SocketHandler
*
* @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
*/
public function __construct($token, $region = 'us', $useSSL = true, $level = Logger::DEBUG, $bubble = true)
public function __construct($token, $region = 'us', $useSSL = true, $level = Logger::DEBUG, bool $bubble = true)
{
if ($useSSL && !extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler');

View File

@@ -31,7 +31,7 @@ class LogEntriesHandler extends SocketHandler
*
* @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
*/
public function __construct($token, $useSSL = true, $level = Logger::DEBUG, $bubble = true)
public function __construct($token, $useSSL = true, $level = Logger::DEBUG, bool $bubble = true)
{
if ($useSSL && !extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP plugin is required to use SSL encrypted connection for LogEntriesHandler');

View File

@@ -32,7 +32,7 @@ class LogglyHandler extends AbstractProcessingHandler
protected $tag = [];
public function __construct($token, $level = Logger::DEBUG, $bubble = true)
public function __construct($token, $level = Logger::DEBUG, bool $bubble = true)
{
if (!extension_loaded('curl')) {
throw new \LogicException('The curl extension is needed to use the LogglyHandler');
@@ -57,12 +57,12 @@ class LogglyHandler extends AbstractProcessingHandler
}
}
protected function write(array $record)
protected function write(array $record): void
{
$this->send($record["formatted"], self::ENDPOINT_SINGLE);
}
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
$level = $this->level;

View File

@@ -24,7 +24,7 @@ abstract class MailHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
$messages = [];
@@ -46,17 +46,17 @@ abstract class MailHandler extends AbstractProcessingHandler
* @param string $content formatted email body to be sent
* @param array $records the array of log records that formed this content
*/
abstract protected function send(string $content, array $records);
abstract protected function send(string $content, array $records): void;
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$this->send((string) $record['formatted'], [$record]);
}
protected function getHighestRecord(array $records)
protected function getHighestRecord(array $records): array
{
$highestRecord = null;
foreach ($records as $record) {
@@ -68,7 +68,7 @@ abstract class MailHandler extends AbstractProcessingHandler
return $highestRecord;
}
protected function isHtmlBody($body)
protected function isHtmlBody(string $body): bool
{
return substr($body, 0, 1) === '<';
}

View File

@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Logger;
use Swift;
/**
* MandrillHandler uses cURL to send the emails to the Mandrill API
@@ -29,7 +30,7 @@ class MandrillHandler extends MailHandler
* @param 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
*/
public function __construct($apiKey, $message, $level = Logger::ERROR, $bubble = true)
public function __construct($apiKey, $message, $level = Logger::ERROR, bool $bubble = true)
{
parent::__construct($level, $bubble);
@@ -46,16 +47,20 @@ class MandrillHandler extends MailHandler
/**
* {@inheritdoc}
*/
protected function send(string $content, array $records)
protected function send(string $content, array $records): void
{
$mime = null;
$mime = 'text/plain';
if ($this->isHtmlBody($content)) {
$mime = 'text/html';
}
$message = clone $this->message;
$message->setBody($content, $mime);
$message->setDate(time());
if (version_compare(Swift::VERSION, '6.0.0', '>=')) {
$message->setDate(new \DateTimeImmutable());
} else {
$message->setDate(time());
}
$ch = curl_init();

View File

@@ -46,7 +46,7 @@ class MongoDBHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct($mongodb, $database, $collection, $level = Logger::DEBUG, $bubble = true)
public function __construct($mongodb, $database, $collection, $level = Logger::DEBUG, bool $bubble = true)
{
if (!($mongodb instanceof Client || $mongodb instanceof Manager)) {
throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required');
@@ -62,7 +62,7 @@ class MongoDBHandler extends AbstractProcessingHandler
parent::__construct($level, $bubble);
}
protected function write(array $record)
protected function write(array $record): void
{
if (isset($this->collection)) {
$this->collection->insertOne($record['formatted']);

View File

@@ -72,7 +72,7 @@ class NativeMailerHandler extends MailHandler
* @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
*/
public function __construct($to, $subject, $from, $level = Logger::ERROR, $bubble = true, $maxColumnWidth = 70)
public function __construct($to, $subject, $from, $level = Logger::ERROR, bool $bubble = true, $maxColumnWidth = 70)
{
parent::__construct($level, $bubble);
$this->to = (array) $to;
@@ -115,7 +115,7 @@ class NativeMailerHandler extends MailHandler
/**
* {@inheritdoc}
*/
protected function send(string $content, array $records)
protected function send(string $content, array $records): void
{
$contentType = $this->getContentType() ?: ($this->isHtmlBody($content) ? 'text/html' : 'text/plain');

View File

@@ -72,7 +72,7 @@ class NewRelicHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
if (!$this->isNewRelicEnabled()) {
throw new MissingExtensionException('The newrelic PHP extension is required to use the NewRelicHandler');

View File

@@ -59,7 +59,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
'dumperItemSizeLimit' => 5000, // int Maximum length of any string or dumped array item
'dumperDumpSizeLimit' => 500000, // int Maximum approximate size of dumped vars result formatted in JSON
'detectDumpTraceAndSource' => false, // bool Autodetect and append trace data to debug
'dataStorage' => null, // PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ)
'dataStorage' => null, // \PhpConsole\Storage|null Fixes problem with custom $_SESSION handler(see http://goo.gl/Ne8juJ)
];
/** @var Connector */
@@ -68,11 +68,11 @@ class PHPConsoleHandler extends AbstractProcessingHandler
/**
* @param array $options See \Monolog\Handler\PHPConsoleHandler::$options for more details
* @param Connector|null $connector Instance of \PhpConsole\Connector class (optional)
* @param int $level
* @param int|string $level
* @param bool $bubble
* @throws \RuntimeException
*/
public function __construct(array $options = [], Connector $connector = null, $level = Logger::DEBUG, $bubble = true)
public function __construct(array $options = [], ?Connector $connector = null, $level = Logger::DEBUG, bool $bubble = true)
{
if (!class_exists('PhpConsole\Connector')) {
throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
@@ -92,7 +92,10 @@ class PHPConsoleHandler extends AbstractProcessingHandler
return array_replace($this->options, $options);
}
private function initConnector(Connector $connector = null)
/**
* @suppress PhanTypeMismatchArgument
*/
private function initConnector(Connector $connector = null): Connector
{
if (!$connector) {
if ($this->options['dataStorage']) {
@@ -147,12 +150,12 @@ class PHPConsoleHandler extends AbstractProcessingHandler
return $connector;
}
public function getConnector()
public function getConnector(): Connector
{
return $this->connector;
}
public function getOptions()
public function getOptions(): array
{
return $this->options;
}
@@ -172,7 +175,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
* @param array $record
* @return void
*/
protected function write(array $record)
protected function write(array $record): void
{
if ($record['level'] < Logger::NOTICE) {
$this->handleDebugRecord($record);
@@ -183,7 +186,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
}
}
private function handleDebugRecord(array $record)
private function handleDebugRecord(array $record): void
{
$tags = $this->getRecordTags($record);
$message = $record['message'];
@@ -193,12 +196,12 @@ class PHPConsoleHandler extends AbstractProcessingHandler
$this->connector->getDebugDispatcher()->dispatchDebug($message, $tags, $this->options['classesPartialsTraceIgnore']);
}
private function handleExceptionRecord(array $record)
private function handleExceptionRecord(array $record): void
{
$this->connector->getErrorsDispatcher()->dispatchException($record['context']['exception']);
}
private function handleErrorRecord(array $record)
private function handleErrorRecord(array $record): void
{
$context = $record['context'];

View File

@@ -39,7 +39,7 @@ class ProcessHandler extends AbstractProcessingHandler
private $command;
/**
* @var string
* @var ?string
*/
private $cwd;
@@ -62,10 +62,10 @@ class ProcessHandler extends AbstractProcessingHandler
* especially if you do not use the $cwd parameter.
* @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 $cwd "Current working directory" (CWD) for the process to be executed in.
* @param ?string $cwd "Current working directory" (CWD) for the process to be executed in.
* @throws \InvalidArgumentException
*/
public function __construct(string $command, $level = Logger::DEBUG, bool $bubble = true, string $cwd = null)
public function __construct(string $command, $level = Logger::DEBUG, bool $bubble = true, ?string $cwd = null)
{
if ($command === '') {
throw new \InvalidArgumentException('The command argument must be a non-empty string.');
@@ -83,11 +83,9 @@ class ProcessHandler extends AbstractProcessingHandler
/**
* Writes the record down to the log of the implementing handler
*
* @param array $record
* @throws \UnexpectedValueException
* @return void
*/
protected function write(array $record)
protected function write(array $record): void
{
$this->ensureProcessIsStarted();
@@ -102,10 +100,8 @@ class ProcessHandler extends AbstractProcessingHandler
/**
* Makes sure that the process is actually started, and if not, starts it,
* assigns the stream pipes, and handles startup errors, if any.
*
* @return void
*/
private function ensureProcessIsStarted()
private function ensureProcessIsStarted(): void
{
if (is_resource($this->process) === false) {
$this->startProcess();
@@ -116,10 +112,8 @@ class ProcessHandler extends AbstractProcessingHandler
/**
* Starts the actual process and sets all streams to non-blocking.
*
* @return void
*/
private function startProcess()
private function startProcess(): void
{
$this->process = proc_open($this->command, self::DESCRIPTOR_SPEC, $this->pipes, $this->cwd);
@@ -132,9 +126,8 @@ class ProcessHandler extends AbstractProcessingHandler
* Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any.
*
* @throws \UnexpectedValueException
* @return void
*/
private function handleStartupErrors()
private function handleStartupErrors(): void
{
$selected = $this->selectErrorStream();
if (false === $selected) {
@@ -169,7 +162,7 @@ class ProcessHandler extends AbstractProcessingHandler
* @codeCoverageIgnore
* @return string Empty string if there are no errors.
*/
protected function readProcessErrors()
protected function readProcessErrors(): string
{
return stream_get_contents($this->pipes[2]);
}
@@ -178,18 +171,16 @@ class ProcessHandler extends AbstractProcessingHandler
* Writes to the input stream of the opened process.
*
* @codeCoverageIgnore
* @param $string
* @return void
*/
protected function writeProcessInput($string)
protected function writeProcessInput(string $string): void
{
fwrite($this->pipes[0], (string) $string);
fwrite($this->pipes[0], $string);
}
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
if (is_resource($this->process)) {
foreach ($this->pipes as $pipe) {

View File

@@ -25,6 +25,7 @@ trait ProcessableHandlerTrait
/**
* {@inheritdoc}
* @suppress PhanTypeMismatchReturn
*/
public function pushProcessor(callable $callback): HandlerInterface
{
@@ -47,11 +48,8 @@ trait ProcessableHandlerTrait
/**
* Processes a record.
*
* @param array $record
* @return array
*/
protected function processRecord(array $record)
protected function processRecord(array $record): array
{
foreach ($this->processors as $processor) {
$record = $processor($record);

View File

@@ -33,7 +33,7 @@ class PsrHandler extends AbstractHandler
* @param 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
*/
public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, $bubble = true)
public function __construct(LoggerInterface $logger, $level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);

View File

@@ -79,7 +79,7 @@ class PushoverHandler extends SocketHandler
* @param int $retry The retry parameter specifies how often (in seconds) the Pushover servers will 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, $bubble = true, $useSSL = true, $highPriorityLevel = Logger::CRITICAL, $emergencyLevel = Logger::EMERGENCY, $retry = 30, $expire = 25200)
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)
{
$connectionString = $useSSL ? 'ssl://api.pushover.net:443' : 'api.pushover.net:80';
parent::__construct($connectionString, $level, $bubble);
@@ -152,7 +152,7 @@ class PushoverHandler extends SocketHandler
return $header;
}
protected function write(array $record)
protected function write(array $record): void
{
foreach ($this->users as $user) {
$this->user = $user;

View File

@@ -59,7 +59,7 @@ class RavenHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct(Raven_Client $ravenClient, $level = Logger::DEBUG, $bubble = true)
public function __construct(Raven_Client $ravenClient, $level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);
@@ -69,7 +69,7 @@ class RavenHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
$level = $this->level;
@@ -130,8 +130,9 @@ class RavenHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
* @suppress PhanTypeMismatchArgument
*/
protected function write(array $record)
protected function write(array $record): void
{
/** @var bool|null|array This is false, unless set below to null or an array of data, when we read the current user context */
$previousUserContext = false;

View File

@@ -55,7 +55,7 @@ class RedisHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
if ($this->capSize) {
$this->writeCapped($record);

View File

@@ -63,7 +63,7 @@ class RollbarHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, $bubble = true)
public function __construct(RollbarLogger $rollbarLogger, $level = Logger::ERROR, bool $bubble = true)
{
$this->rollbarLogger = $rollbarLogger;
@@ -73,7 +73,7 @@ class RollbarHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
if (!$this->initialized) {
// __destructor() doesn't get called on Fatal errors
@@ -113,7 +113,7 @@ class RollbarHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
$this->flush();
}

View File

@@ -44,7 +44,7 @@ class RotatingFileHandler extends StreamHandler
* @param int|null $filePermission Optional file permissions (default (0644) are only for owner read/write)
* @param bool $useLocking Try to lock log file before doing any writes
*/
public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, $bubble = true, $filePermission = null, $useLocking = false)
public function __construct($filename, $maxFiles = 0, $level = Logger::DEBUG, bool $bubble = true, $filePermission = null, $useLocking = false)
{
$this->filename = $filename;
$this->maxFiles = (int) $maxFiles;
@@ -58,7 +58,7 @@ class RotatingFileHandler extends StreamHandler
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
parent::close();
@@ -91,7 +91,7 @@ class RotatingFileHandler extends StreamHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
// on the first record written, if the log is new, we should rotate (once per day)
if (null === $this->mustRotate) {
@@ -109,7 +109,7 @@ class RotatingFileHandler extends StreamHandler
/**
* Rotates the files.
*/
protected function rotate()
protected function rotate(): void
{
// update filename
$this->url = $this->getTimedFilename();
@@ -135,7 +135,8 @@ class RotatingFileHandler extends StreamHandler
if (is_writable($file)) {
// suppress errors here as unlink() might fail if two processes
// are cleaning up/rotating at the same time
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): bool {
return false;
});
unlink($file);
restore_error_handler();

View File

@@ -72,7 +72,7 @@ class SendGridHandler extends MailHandler
/**
* {@inheritdoc}
*/
protected function send(string $content, array $records)
protected function send(string $content, array $records): void
{
$message = [];
$message['api_user'] = $this->apiUser;

View File

@@ -35,13 +35,13 @@ class SlackRecord
/**
* Slack channel (encoded ID or name)
* @var string|null
* @var ?string
*/
private $channel;
/**
* Name of a bot
* @var string|null
* @var ?string
*/
private $username;
@@ -177,9 +177,6 @@ class SlackRecord
/**
* Returned a Slack message attachment color associated with
* provided level.
*
* @param int $level
* @return string
*/
public function getAttachmentColor(int $level): string
{
@@ -197,10 +194,6 @@ class SlackRecord
/**
* Stringifies an array of key/value pairs to be used in attachment fields
*
* @param array $fields
*
* @return string
*/
public function stringify(array $fields): string
{
@@ -215,23 +208,17 @@ class SlackRecord
: json_encode($normalized, JSON_UNESCAPED_UNICODE);
}
/**
* Sets the formatter
*
* @param FormatterInterface $formatter
*/
public function setFormatter(FormatterInterface $formatter): void
public function setFormatter(FormatterInterface $formatter): self
{
$this->formatter = $formatter;
return $this;
}
/**
* Generates attachment field
*
* @param string $title
* @param string|array $value
*
* @return array
*/
private function generateAttachmentField(string $title, $value): array
{
@@ -248,10 +235,6 @@ class SlackRecord
/**
* Generates a collection of attachment fields from array
*
* @param array $data
*
* @return array
*/
private function generateAttachmentFields(array $data): array
{
@@ -265,10 +248,6 @@ class SlackRecord
/**
* Get a copy of record with fields excluded according to $this->excludeFields
*
* @param array $record
*
* @return array
*/
private function excludeFields(array $record): array
{

View File

@@ -48,7 +48,7 @@ class SlackHandler extends SocketHandler
* @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
*/
public function __construct($token, $channel, $username = null, $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array())
public function __construct($token, $channel, $username = null, $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, bool $bubble = true, $useShortAttachment = false, $includeContextAndExtra = false, array $excludeFields = array())
{
if (!extension_loaded('openssl')) {
throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
@@ -145,7 +145,7 @@ class SlackHandler extends SocketHandler
*
* @param array $record
*/
protected function write(array $record)
protected function write(array $record): void
{
parent::write($record);
$this->finalizeWrite();

View File

@@ -47,7 +47,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
* @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']
*/
public function __construct($webhookUrl, $channel = null, $username = null, $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeContextAndExtra = false, $level = Logger::CRITICAL, $bubble = true, array $excludeFields = array())
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())
{
parent::__construct($level, $bubble);
@@ -79,7 +79,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
*
* @param array $record
*/
protected function write(array $record)
protected function write(array $record): void
{
$postData = $this->slackRecord->getSlackData($record);
$postString = json_encode($postData);

View File

@@ -46,7 +46,7 @@ class SlackbotHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct($slackTeam, $token, $channel, $level = Logger::CRITICAL, $bubble = true)
public function __construct($slackTeam, $token, $channel, $level = Logger::CRITICAL, bool $bubble = true)
{
parent::__construct($level, $bubble);
@@ -60,7 +60,7 @@ class SlackbotHandler extends AbstractProcessingHandler
*
* @param array $record
*/
protected function write(array $record)
protected function write(array $record): void
{
$slackbotUrl = sprintf(
'https://%s.slack.com/services/hooks/slackbot?token=%s&channel=%s',

View File

@@ -30,6 +30,7 @@ class SocketHandler extends AbstractProcessingHandler
/** @var float */
private $writingTimeout = 10;
private $lastSentBytes = null;
/** @var int */
private $chunkSize = null;
private $persistent = false;
private $errno;
@@ -41,7 +42,7 @@ class SocketHandler extends AbstractProcessingHandler
* @param 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
*/
public function __construct($connectionString, $level = Logger::DEBUG, $bubble = true)
public function __construct($connectionString, $level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);
$this->connectionString = $connectionString;
@@ -56,7 +57,7 @@ class SocketHandler extends AbstractProcessingHandler
* @throws \UnexpectedValueException
* @throws \RuntimeException
*/
protected function write(array $record)
protected function write(array $record): void
{
$this->connectIfNotConnected();
$data = $this->generateDataStream($record);
@@ -66,7 +67,7 @@ class SocketHandler extends AbstractProcessingHandler
/**
* We will not close a PersistentSocket instance so it can be reused in other requests.
*/
public function close()
public function close(): void
{
if (!$this->isPersistent()) {
$this->closeSocket();
@@ -76,7 +77,7 @@ class SocketHandler extends AbstractProcessingHandler
/**
* Close socket, if open
*/
public function closeSocket()
public function closeSocket(): void
{
if (is_resource($this->resource)) {
fclose($this->resource);
@@ -85,23 +86,19 @@ class SocketHandler extends AbstractProcessingHandler
}
/**
* Set socket connection to nbe persistent. It only has effect before the connection is initiated.
*
* @param bool $persistent
* Set socket connection to be persistent. It only has effect before the connection is initiated.
*/
public function setPersistent($persistent)
public function setPersistent(bool $persistent): void
{
$this->persistent = (bool) $persistent;
$this->persistent = $persistent;
}
/**
* Set connection timeout. Only has effect before we connect.
*
* @param float $seconds
*
* @see http://php.net/manual/en/function.fsockopen.php
*/
public function setConnectionTimeout($seconds)
public function setConnectionTimeout(float $seconds): void
{
$this->validateTimeout($seconds);
$this->connectionTimeout = (float) $seconds;
@@ -110,11 +107,9 @@ class SocketHandler extends AbstractProcessingHandler
/**
* Set write timeout. Only has effect before we connect.
*
* @param float $seconds
*
* @see http://php.net/manual/en/function.stream-set-timeout.php
*/
public function setTimeout($seconds)
public function setTimeout(float $seconds): void
{
$this->validateTimeout($seconds);
$this->timeout = (float) $seconds;
@@ -125,7 +120,7 @@ class SocketHandler extends AbstractProcessingHandler
*
* @param float $seconds 0 for no timeout
*/
public function setWritingTimeout($seconds)
public function setWritingTimeout(float $seconds): void
{
$this->validateTimeout($seconds);
$this->writingTimeout = (float) $seconds;
@@ -133,20 +128,16 @@ class SocketHandler extends AbstractProcessingHandler
/**
* Set chunk size. Only has effect during connection in the writing cycle.
*
* @param float $bytes
*/
public function setChunkSize($bytes)
public function setChunkSize(int $bytes): void
{
$this->chunkSize = $bytes;
}
/**
* Get current connection string
*
* @return string
*/
public function getConnectionString()
public function getConnectionString(): string
{
return $this->connectionString;
}
@@ -189,10 +180,8 @@ class SocketHandler extends AbstractProcessingHandler
/**
* Get current chunk size
*
* @return float
*/
public function getChunkSize()
public function getChunkSize(): int
{
return $this->chunkSize;
}
@@ -201,10 +190,8 @@ class SocketHandler extends AbstractProcessingHandler
* Check to see if the socket is currently available.
*
* UDP might appear to be connected but might fail when writing. See http://php.net/fsockopen for details.
*
* @return bool
*/
public function isConnected()
public function isConnected(): bool
{
return is_resource($this->resource)
&& !feof($this->resource); // on TCP - other party can close connection.

View File

@@ -31,7 +31,7 @@ class SqsHandler extends AbstractProcessingHandler
/** @var string */
private $queueUrl;
public function __construct(SqsClient $sqsClient, $queueUrl, $level = Logger::DEBUG, $bubble = true)
public function __construct(SqsClient $sqsClient, $queueUrl, $level = Logger::DEBUG, bool $bubble = true)
{
parent::__construct($level, $bubble);
@@ -44,7 +44,7 @@ class SqsHandler extends AbstractProcessingHandler
*
* @param array $record
*/
protected function write(array $record)
protected function write(array $record): void
{
if (!isset($record['formatted']) || 'string' !== gettype($record['formatted'])) {
throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string');

View File

@@ -41,7 +41,7 @@ class StreamHandler extends AbstractProcessingHandler
* @throws \Exception If a missing directory is not buildable
* @throws \InvalidArgumentException If stream is not a resource or string
*/
public function __construct($stream, $level = Logger::DEBUG, $bubble = true, $filePermission = null, $useLocking = false)
public function __construct($stream, $level = Logger::DEBUG, bool $bubble = true, $filePermission = null, $useLocking = false)
{
parent::__construct($level, $bubble);
if (is_resource($stream)) {
@@ -59,7 +59,7 @@ class StreamHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
if ($this->url && is_resource($this->stream)) {
fclose($this->stream);
@@ -90,7 +90,7 @@ class StreamHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
if (!is_resource($this->stream)) {
if (null === $this->url || '' === $this->url) {
@@ -138,12 +138,7 @@ class StreamHandler extends AbstractProcessingHandler
$this->errorMessage = preg_replace('{^(fopen|mkdir)\(.*?\): }', '', $msg);
}
/**
* @param string $stream
*
* @return null|string
*/
private function getDirFromStream($stream)
private function getDirFromStream(string $stream): ?string
{
$pos = strpos($stream, '://');
if ($pos === false) {
@@ -154,7 +149,7 @@ class StreamHandler extends AbstractProcessingHandler
return dirname(substr($stream, 7));
}
return;
return null;
}
private function createDir()

View File

@@ -44,7 +44,7 @@ class SwiftMailerHandler extends MailHandler
/**
* {@inheritdoc}
*/
protected function send(string $content, array $records)
protected function send(string $content, array $records): void
{
$this->mailer->send($this->buildMessage($content, $records));
}
@@ -85,7 +85,7 @@ class SwiftMailerHandler extends MailHandler
$message->setSubject($subjectFormatter->format($this->getHighestRecord($records)));
}
$mime = null;
$mime = 'text/plain';
if ($this->isHtmlBody($content)) {
$mime = 'text/html';
}

View File

@@ -38,7 +38,7 @@ class SyslogHandler extends AbstractSyslogHandler
* @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
*/
public function __construct($ident, $facility = LOG_USER, $level = Logger::DEBUG, $bubble = true, $logopts = LOG_PID)
public function __construct($ident, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, $logopts = LOG_PID)
{
parent::__construct($facility, $level, $bubble);
@@ -49,7 +49,7 @@ class SyslogHandler extends AbstractSyslogHandler
/**
* {@inheritdoc}
*/
public function close()
public function close(): void
{
closelog();
}
@@ -57,7 +57,7 @@ class SyslogHandler extends AbstractSyslogHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
if (!openlog($this->ident, $this->logopts, $this->facility)) {
throw new \LogicException('Can\'t open syslog for ident "'.$this->ident.'" and facility "'.$this->facility.'"');

View File

@@ -15,13 +15,14 @@ class UdpSocket
{
const DATAGRAM_MAX_LENGTH = 65023;
/** @var string */
protected $ip;
/** @var int */
protected $port;
/** @var resource|null */
protected $socket;
public function __construct($ip, $port = 514)
public function __construct(string $ip, int $port = 514)
{
$this->ip = $ip;
$this->port = $port;
@@ -33,7 +34,7 @@ class UdpSocket
$this->send($this->assembleMessage($line, $header));
}
public function close()
public function close(): void
{
if (is_resource($this->socket)) {
socket_close($this->socket);
@@ -41,7 +42,7 @@ class UdpSocket
}
}
protected function send($chunk)
protected function send(string $chunk): void
{
if (!is_resource($this->socket)) {
throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
@@ -49,7 +50,7 @@ class UdpSocket
socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
}
protected function assembleMessage($line, $header)
protected function assembleMessage(string $line, string $header): string
{
$chunkSize = self::DATAGRAM_MAX_LENGTH - strlen($header);

View File

@@ -32,7 +32,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
* @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.
*/
public function __construct($host, $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, $bubble = true, $ident = 'php')
public function __construct($host, $port = 514, $facility = LOG_USER, $level = Logger::DEBUG, bool $bubble = true, $ident = 'php')
{
parent::__construct($facility, $level, $bubble);
@@ -41,7 +41,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
$this->socket = new UdpSocket($host, $port ?: 514);
}
protected function write(array $record)
protected function write(array $record): void
{
$lines = $this->splitMessageIntoLines($record['formatted']);
@@ -52,7 +52,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
}
}
public function close()
public function close(): void
{
$this->socket->close();
}

View File

@@ -138,7 +138,7 @@ class TestHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$this->recordsByLevel[$record['level']][] = $record;
$this->records[] = $record;

View File

@@ -44,7 +44,7 @@ class WhatFailureGroupHandler extends GroupHandler
/**
* {@inheritdoc}
*/
public function handleBatch(array $records)
public function handleBatch(array $records): void
{
if ($this->processors) {
$processed = array();

View File

@@ -45,7 +45,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
* @param bool $bubble
* @throws MissingExtensionException
*/
public function __construct($level = Logger::DEBUG, $bubble = true)
public function __construct($level = Logger::DEBUG, bool $bubble = true)
{
if (!function_exists('zend_monitor_custom_event')) {
throw new MissingExtensionException('You must have Zend Server installed in order to use this handler');
@@ -56,7 +56,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
protected function write(array $record)
protected function write(array $record): void
{
$this->writeZendMonitorCustomEvent(
$this->levelMap[$record['level']],
@@ -65,14 +65,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
);
}
/**
* Write a record to Zend Monitor
*
* @param int $level
* @param string $message
* @param array $formatted
*/
protected function writeZendMonitorCustomEvent($level, $message, $formatted)
protected function writeZendMonitorCustomEvent(int $level, string $message, array $formatted)
{
zend_monitor_custom_event($level, $message, $formatted);
}
@@ -85,12 +78,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
return new NormalizerFormatter();
}
/**
* Get the level map
*
* @return array
*/
public function getLevelMap()
public function getLevelMap(): array
{
return $this->levelMap;
}

View File

@@ -135,7 +135,7 @@ class Logger implements LoggerInterface
protected $timezone;
/**
* @var callable
* @var ?callable
*/
protected $exceptionHandler;
@@ -143,9 +143,9 @@ class Logger implements LoggerInterface
* @param string $name The logging channel, a simple descriptive name that is attached to all log records
* @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
* @param callable[] $processors Optional array of processors
* @param DateTimeZone $timezone Optional timezone, if not provided date_default_timezone_get() will be used
* @param ?DateTimeZone $timezone Optional timezone, if not provided date_default_timezone_get() will be used
*/
public function __construct(string $name, array $handlers = [], array $processors = [], DateTimeZone $timezone = null)
public function __construct(string $name, array $handlers = [], array $processors = [], ?DateTimeZone $timezone = null)
{
$this->name = $name;
$this->setHandlers($handlers);
@@ -360,7 +360,7 @@ class Logger implements LoggerInterface
/**
* Converts PSR-3 levels to Monolog ones if necessary
*
* @param string|int Level number (monolog) or name (PSR-3)
* @param string|int $level Level number (monolog) or name (PSR-3)
* @throws \Psr\Log\InvalidArgumentException If level is not defined
*/
public static function toMonologLevel($level): int

View File

@@ -22,16 +22,17 @@ class PsrLogMessageProcessor
{
const SIMPLE_DATE = "Y-m-d\TH:i:s.uP";
/** @var ?string */
private $dateFormat;
/** @var bool */
private $removeUsedContextFields;
/**
* @param string $dateFormat The format of the timestamp: one supported by DateTime::format
* @param bool $removeUsedContextFields If set to true the fields interpolated into message gets unset
* @param ?string $dateFormat The format of the timestamp: one supported by DateTime::format
* @param bool $removeUsedContextFields If set to true the fields interpolated into message gets unset
*/
public function __construct(string $dateFormat = null, bool $removeUsedContextFields = false)
public function __construct(?string $dateFormat = null, bool $removeUsedContextFields = false)
{
$this->dateFormat = $dateFormat;
$this->removeUsedContextFields = $removeUsedContextFields;

View File

@@ -25,10 +25,10 @@ class TestCase extends \PHPUnit\Framework\TestCase
/**
* @return array Record
*/
protected function getRecord($level = Logger::WARNING, $message = 'test', $context = [])
protected function getRecord($level = Logger::WARNING, $message = 'test', array $context = []): array
{
return [
'message' => $message,
'message' => (string) $message,
'context' => $context,
'level' => $level,
'level_name' => Logger::getLevelName($level),
@@ -38,10 +38,7 @@ class TestCase extends \PHPUnit\Framework\TestCase
];
}
/**
* @return array
*/
protected function getMultipleRecords()
protected function getMultipleRecords(): array
{
return [
$this->getRecord(Logger::DEBUG, 'debug message 1'),
@@ -52,6 +49,9 @@ class TestCase extends \PHPUnit\Framework\TestCase
];
}
/**
* @suppress PhanTypeMismatchReturn
*/
protected function getIdentityFormatter(): FormatterInterface
{
$formatter = $this->createMock(FormatterInterface::class);

View File

@@ -82,9 +82,8 @@ class HandlerWrapperTest extends TestCase
$records = $this->getMultipleRecords();
$this->handler->expects($this->once())
->method('handleBatch')
->with($records)
->willReturn($result);
->with($records);
$this->assertEquals($result, $this->wrapper->handleBatch($records));
$this->wrapper->handleBatch($records);
}
}

View File

@@ -44,7 +44,7 @@ class SyslogUdpHandlerTest extends TestCase
$socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
->setMethods(['write'])
->setConstructorArgs(['lol', 'lol'])
->setConstructorArgs(['lol'])
->getMock();
$socket->expects($this->at(0))
->method('write')
@@ -65,7 +65,7 @@ class SyslogUdpHandlerTest extends TestCase
$socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
->setMethods(['write'])
->setConstructorArgs(['lol', 'lol'])
->setConstructorArgs(['lol'])
->getMock();
$socket->expects($this->never())
->method('write');

View File

@@ -23,7 +23,7 @@ class UdpSocketTest extends TestCase
{
$socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
->setMethods(['send'])
->setConstructorArgs(['lol', 'lol'])
->setConstructorArgs(['lol'])
->getMock();
$socket->expects($this->at(0))
@@ -37,7 +37,7 @@ class UdpSocketTest extends TestCase
{
$socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
->setMethods(['send'])
->setConstructorArgs(['lol', 'lol'])
->setConstructorArgs(['lol'])
->getMock();
$truncatedString = str_repeat("derp", 16254).'d';