1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-06 13:16:39 +02:00

Add scalar types to processor/formatters and top level classes

This commit is contained in:
Jordi Boggiano
2016-09-25 21:23:35 +02:00
parent 760dc44ebd
commit 6e6586257d
29 changed files with 130 additions and 196 deletions

View File

@@ -55,7 +55,7 @@ class ErrorHandler
* @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling * @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling
* @return ErrorHandler * @return ErrorHandler
*/ */
public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null) public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null): self
{ {
$handler = new static($logger); $handler = new static($logger);
if ($errorLevelMap !== false) { if ($errorLevelMap !== false) {
@@ -71,16 +71,18 @@ class ErrorHandler
return $handler; return $handler;
} }
public function registerExceptionHandler($levelMap = [], $callPrevious = true) public function registerExceptionHandler($levelMap = [], $callPrevious = true): self
{ {
$prev = set_exception_handler([$this, 'handleException']); $prev = set_exception_handler([$this, 'handleException']);
$this->uncaughtExceptionLevelMap = array_replace($this->defaultExceptionLevelMap(), $levelMap); $this->uncaughtExceptionLevelMap = array_replace($this->defaultExceptionLevelMap(), $levelMap);
if ($callPrevious && $prev) { if ($callPrevious && $prev) {
$this->previousExceptionHandler = $prev; $this->previousExceptionHandler = $prev;
} }
return $this;
} }
public function registerErrorHandler(array $levelMap = [], $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true) public function registerErrorHandler(array $levelMap = [], $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true): self
{ {
$prev = set_error_handler([$this, 'handleError'], $errorTypes); $prev = set_error_handler([$this, 'handleError'], $errorTypes);
$this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap); $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
@@ -89,18 +91,22 @@ class ErrorHandler
} }
$this->handleOnlyReportedErrors = $handleOnlyReportedErrors; $this->handleOnlyReportedErrors = $handleOnlyReportedErrors;
return $this;
} }
public function registerFatalHandler($level = null, $reservedMemorySize = 20) public function registerFatalHandler($level = null, $reservedMemorySize = 20): self
{ {
register_shutdown_function([$this, 'handleFatalError']); register_shutdown_function([$this, 'handleFatalError']);
$this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize); $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
$this->fatalLevel = $level; $this->fatalLevel = $level;
$this->hasFatalErrorHandler = true; $this->hasFatalErrorHandler = true;
return $this;
} }
protected function defaultExceptionLevelMap() protected function defaultExceptionLevelMap(): array
{ {
return [ return [
'ParseError' => LogLevel::CRITICAL, 'ParseError' => LogLevel::CRITICAL,
@@ -108,7 +114,7 @@ class ErrorHandler
]; ];
} }
protected function defaultErrorLevelMap() protected function defaultErrorLevelMap(): array
{ {
return [ return [
E_ERROR => LogLevel::CRITICAL, E_ERROR => LogLevel::CRITICAL,
@@ -200,7 +206,7 @@ class ErrorHandler
} }
} }
private static function codeToString($code) private static function codeToString($code): string
{ {
switch ($code) { switch ($code) {
case E_ERROR: case E_ERROR:

View File

@@ -65,6 +65,9 @@ class ChromePHPFormatter implements FormatterInterface
]; ];
} }
/**
* {@inheritdoc}
*/
public function formatBatch(array $records) public function formatBatch(array $records)
{ {
$formatted = []; $formatted = [];

View File

@@ -34,7 +34,7 @@ class ElasticaFormatter extends NormalizerFormatter
* @param string $index Elastic Search index name * @param string $index Elastic Search index name
* @param string $type Elastic Search document type * @param string $type Elastic Search document type
*/ */
public function __construct($index, $type) public function __construct(string $index, string $type)
{ {
// elasticsearch requires a ISO 8601 format date with optional millisecond precision. // elasticsearch requires a ISO 8601 format date with optional millisecond precision.
parent::__construct('Y-m-d\TH:i:s.uP'); parent::__construct('Y-m-d\TH:i:s.uP');
@@ -53,31 +53,20 @@ class ElasticaFormatter extends NormalizerFormatter
return $this->getDocument($record); return $this->getDocument($record);
} }
/** public function getIndex(): string
* Getter index
* @return string
*/
public function getIndex()
{ {
return $this->index; return $this->index;
} }
/** public function getType(): string
* Getter type
* @return string
*/
public function getType()
{ {
return $this->type; return $this->type;
} }
/** /**
* Convert a log message into an Elastica Document * Convert a log message into an Elastica Document
*
* @param array $record Log message
* @return Document
*/ */
protected function getDocument($record) protected function getDocument(array $record): Document
{ {
$document = new Document(); $document = new Document();
$document->setData($record); $document->setData($record);

View File

@@ -28,11 +28,7 @@ class FlowdockFormatter implements FormatterInterface
*/ */
private $sourceEmail; private $sourceEmail;
/** public function __construct(string $source, string $sourceEmail)
* @param string $source
* @param string $sourceEmail
*/
public function __construct($source, $sourceEmail)
{ {
$this->source = $source; $this->source = $source;
$this->sourceEmail = $sourceEmail; $this->sourceEmail = $sourceEmail;
@@ -41,7 +37,7 @@ class FlowdockFormatter implements FormatterInterface
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function format(array $record) public function format(array $record): array
{ {
$tags = [ $tags = [
'#logs', '#logs',
@@ -75,7 +71,7 @@ class FlowdockFormatter implements FormatterInterface
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function formatBatch(array $records) public function formatBatch(array $records): array
{ {
$formatted = []; $formatted = [];
@@ -86,12 +82,7 @@ class FlowdockFormatter implements FormatterInterface
return $formatted; return $formatted;
} }
/** public function getShortMessage(string $message): string
* @param string $message
*
* @return string
*/
public function getShortMessage($message)
{ {
static $hasMbString; static $hasMbString;

View File

@@ -39,21 +39,21 @@ class FluentdFormatter implements FormatterInterface
*/ */
protected $levelTag = false; protected $levelTag = false;
public function __construct($levelTag = false) public function __construct(bool $levelTag = false)
{ {
if (!function_exists('json_encode')) { if (!function_exists('json_encode')) {
throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter'); throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s FluentdUnixFormatter');
} }
$this->levelTag = (bool) $levelTag; $this->levelTag = $levelTag;
} }
public function isUsingLevelsInTag() public function isUsingLevelsInTag(): bool
{ {
return $this->levelTag; return $this->levelTag;
} }
public function format(array $record) public function format(array $record): string
{ {
$tag = $record['channel']; $tag = $record['channel'];
if ($this->levelTag) { if ($this->levelTag) {
@@ -73,7 +73,7 @@ class FluentdFormatter implements FormatterInterface
return json_encode([$tag, $record['datetime']->getTimestamp(), $message]); return json_encode([$tag, $record['datetime']->getTimestamp(), $message]);
} }
public function formatBatch(array $records) public function formatBatch(array $records): string
{ {
$message = ''; $message = '';
foreach ($records as $record) { foreach ($records as $record) {

View File

@@ -53,7 +53,7 @@ class GelfMessageFormatter extends NormalizerFormatter
Logger::EMERGENCY => 0, Logger::EMERGENCY => 0,
]; ];
public function __construct($systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_') public function __construct(string $systemName = null, string $extraPrefix = null, string $contextPrefix = 'ctxt_')
{ {
parent::__construct('U.u'); parent::__construct('U.u');
@@ -66,7 +66,7 @@ class GelfMessageFormatter extends NormalizerFormatter
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function format(array $record) public function format(array $record): Message
{ {
if (isset($record['context'])) { if (isset($record['context'])) {
$record['context'] = parent::format($record['context']); $record['context'] = parent::format($record['context']);

View File

@@ -39,7 +39,7 @@ 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($dateFormat = null) public function __construct(string $dateFormat = null)
{ {
parent::__construct($dateFormat); parent::__construct($dateFormat);
} }
@@ -52,7 +52,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param bool $escapeTd false if td content must not be html escaped * @param bool $escapeTd false if td content must not be html escaped
* @return string * @return string
*/ */
protected function addRow($th, $td = ' ', $escapeTd = true) protected function addRow(string $th, string $td = ' ', bool $escapeTd = true): string
{ {
$th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8'); $th = htmlspecialchars($th, ENT_NOQUOTES, 'UTF-8');
if ($escapeTd) { if ($escapeTd) {
@@ -69,7 +69,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param int $level Error level * @param int $level Error level
* @return string * @return string
*/ */
protected function addTitle($title, $level) protected function addTitle(string $title, int $level)
{ {
$title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8'); $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8');
@@ -82,7 +82,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param array $record A record to format * @param array $record A record to format
* @return mixed The formatted record * @return mixed The formatted record
*/ */
public function format(array $record) public function format(array $record): string
{ {
$output = $this->addTitle($record['level_name'], $record['level']); $output = $this->addTitle($record['level_name'], $record['level']);
$output .= '<table cellspacing="1" width="100%" class="monolog-output">'; $output .= '<table cellspacing="1" width="100%" class="monolog-output">';
@@ -116,7 +116,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param array $records A set of records to format * @param array $records A set of records to format
* @return mixed The formatted set of records * @return mixed The formatted set of records
*/ */
public function formatBatch(array $records) public function formatBatch(array $records): string
{ {
$message = ''; $message = '';
foreach ($records as $record) { foreach ($records as $record) {
@@ -126,7 +126,7 @@ class HtmlFormatter extends NormalizerFormatter
return $message; return $message;
} }
protected function convertToString($data) protected function convertToString($data): string
{ {
if (null === $data || is_scalar($data)) { if (null === $data || is_scalar($data)) {
return (string) $data; return (string) $data;

View File

@@ -32,10 +32,7 @@ class JsonFormatter extends NormalizerFormatter
*/ */
protected $includeStacktraces = false; protected $includeStacktraces = false;
/** public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = true)
* @param int $batchMode
*/
public function __construct($batchMode = self::BATCH_MODE_JSON, $appendNewline = true)
{ {
$this->batchMode = $batchMode; $this->batchMode = $batchMode;
$this->appendNewline = $appendNewline; $this->appendNewline = $appendNewline;
@@ -47,20 +44,16 @@ class JsonFormatter extends NormalizerFormatter
* formatted as a JSON-encoded array. However, for * formatted as a JSON-encoded array. However, for
* compatibility with some API endpoints, alternative styles * compatibility with some API endpoints, alternative styles
* are available. * are available.
*
* @return int
*/ */
public function getBatchMode() public function getBatchMode(): int
{ {
return $this->batchMode; return $this->batchMode;
} }
/** /**
* True if newlines are appended to every formatted record * True if newlines are appended to every formatted record
*
* @return bool
*/ */
public function isAppendingNewlines() public function isAppendingNewlines(): bool
{ {
return $this->appendNewline; return $this->appendNewline;
} }
@@ -68,7 +61,7 @@ class JsonFormatter extends NormalizerFormatter
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function format(array $record) public function format(array $record): string
{ {
return $this->toJson($this->normalize($record), true) . ($this->appendNewline ? "\n" : ''); return $this->toJson($this->normalize($record), true) . ($this->appendNewline ? "\n" : '');
} }
@@ -76,7 +69,7 @@ class JsonFormatter extends NormalizerFormatter
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function formatBatch(array $records) public function formatBatch(array $records): string
{ {
switch ($this->batchMode) { switch ($this->batchMode) {
case static::BATCH_MODE_NEWLINES: case static::BATCH_MODE_NEWLINES:
@@ -91,18 +84,15 @@ class JsonFormatter extends NormalizerFormatter
/** /**
* @param bool $include * @param bool $include
*/ */
public function includeStacktraces($include = true) public function includeStacktraces(bool $include = true)
{ {
$this->includeStacktraces = $include; $this->includeStacktraces = $include;
} }
/** /**
* Return a JSON-encoded array of records. * Return a JSON-encoded array of records.
*
* @param array $records
* @return string
*/ */
protected function formatBatchJson(array $records) protected function formatBatchJson(array $records): string
{ {
return $this->toJson($this->normalize($records), true); return $this->toJson($this->normalize($records), true);
} }
@@ -110,11 +100,8 @@ class JsonFormatter extends NormalizerFormatter
/** /**
* Use new lines to separate records instead of a * Use new lines to separate records instead of a
* JSON-encoded array. * JSON-encoded array.
*
* @param array $records
* @return string
*/ */
protected function formatBatchNewlines(array $records) protected function formatBatchNewlines(array $records): string
{ {
$instance = $this; $instance = $this;
@@ -135,7 +122,7 @@ class JsonFormatter extends NormalizerFormatter
* *
* @return mixed * @return mixed
*/ */
protected function normalize($data, $depth = 0) protected function normalize($data, int $depth = 0)
{ {
if ($depth > 9) { if ($depth > 9) {
return 'Over 9 levels deep, aborting normalization'; return 'Over 9 levels deep, aborting normalization';
@@ -157,7 +144,7 @@ class JsonFormatter extends NormalizerFormatter
} }
if ($data instanceof Throwable) { if ($data instanceof Throwable) {
return $this->normalizeException($data); return $this->normalizeException($data, $depth);
} }
return $data; return $data;
@@ -166,12 +153,8 @@ class JsonFormatter extends NormalizerFormatter
/** /**
* Normalizes given exception with or without its own stack trace based on * Normalizes given exception with or without its own stack trace based on
* `includeStacktraces` property. * `includeStacktraces` property.
*
* @param Throwable $e
*
* @return array
*/ */
protected function normalizeException(Throwable $e) protected function normalizeException(Throwable $e, int $depth = 0): array
{ {
$data = [ $data = [
'class' => get_class($e), 'class' => get_class($e),
@@ -196,7 +179,7 @@ class JsonFormatter extends NormalizerFormatter
} }
if ($previous = $e->getPrevious()) { if ($previous = $e->getPrevious()) {
$data['previous'] = $this->normalizeException($previous); $data['previous'] = $this->normalizeException($previous, $depth + 1);
} }
return $data; return $data;

View File

@@ -34,7 +34,7 @@ class LineFormatter extends NormalizerFormatter
* @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries * @param bool $allowInlineLineBreaks Whether to allow inline line breaks in log entries
* @param bool $ignoreEmptyContextAndExtra * @param bool $ignoreEmptyContextAndExtra
*/ */
public function __construct($format = null, $dateFormat = null, $allowInlineLineBreaks = false, $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 ?: static::SIMPLE_FORMAT;
$this->allowInlineLineBreaks = $allowInlineLineBreaks; $this->allowInlineLineBreaks = $allowInlineLineBreaks;
@@ -42,7 +42,7 @@ class LineFormatter extends NormalizerFormatter
parent::__construct($dateFormat); parent::__construct($dateFormat);
} }
public function includeStacktraces($include = true) public function includeStacktraces(bool $include = true)
{ {
$this->includeStacktraces = $include; $this->includeStacktraces = $include;
if ($this->includeStacktraces) { if ($this->includeStacktraces) {
@@ -50,12 +50,12 @@ class LineFormatter extends NormalizerFormatter
} }
} }
public function allowInlineLineBreaks($allow = true) public function allowInlineLineBreaks(bool $allow = true)
{ {
$this->allowInlineLineBreaks = $allow; $this->allowInlineLineBreaks = $allow;
} }
public function ignoreEmptyContextAndExtra($ignore = true) public function ignoreEmptyContextAndExtra(bool $ignore = true)
{ {
$this->ignoreEmptyContextAndExtra = $ignore; $this->ignoreEmptyContextAndExtra = $ignore;
} }
@@ -63,7 +63,7 @@ class LineFormatter extends NormalizerFormatter
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function format(array $record) public function format(array $record): string
{ {
$vars = parent::format($record); $vars = parent::format($record);
@@ -104,7 +104,7 @@ class LineFormatter extends NormalizerFormatter
return $output; return $output;
} }
public function formatBatch(array $records) public function formatBatch(array $records): string
{ {
$message = ''; $message = '';
foreach ($records as $record) { foreach ($records as $record) {
@@ -114,12 +114,12 @@ class LineFormatter extends NormalizerFormatter
return $message; return $message;
} }
public function stringify($value) public function stringify($value): string
{ {
return $this->replaceNewlines($this->convertToString($value)); return $this->replaceNewlines($this->convertToString($value));
} }
protected function normalizeException(\Throwable $e) protected function normalizeException(\Throwable $e, int $depth = 0): string
{ {
$previousText = ''; $previousText = '';
if ($previous = $e->getPrevious()) { if ($previous = $e->getPrevious()) {
@@ -136,7 +136,7 @@ class LineFormatter extends NormalizerFormatter
return $str; return $str;
} }
protected function convertToString($data) protected function convertToString($data): string
{ {
if (null === $data || is_bool($data)) { if (null === $data || is_bool($data)) {
return var_export($data, true); return var_export($data, true);
@@ -149,7 +149,7 @@ class LineFormatter extends NormalizerFormatter
return $this->toJson($data, true); return $this->toJson($data, true);
} }
protected function replaceNewlines($str) protected function replaceNewlines(string $str): string
{ {
if ($this->allowInlineLineBreaks) { if ($this->allowInlineLineBreaks) {
if (0 === strpos($str, '{')) { if (0 === strpos($str, '{')) {

View File

@@ -21,10 +21,8 @@ class LogglyFormatter extends JsonFormatter
/** /**
* Overrides the default batch mode to new lines for compatibility with the * Overrides the default batch mode to new lines for compatibility with the
* Loggly bulk API. * Loggly bulk API.
*
* @param int $batchMode
*/ */
public function __construct($batchMode = self::BATCH_MODE_NEWLINES, $appendNewline = false) public function __construct(int $batchMode = self::BATCH_MODE_NEWLINES, bool $appendNewline = false)
{ {
parent::__construct($batchMode, $appendNewline); parent::__construct($batchMode, $appendNewline);
} }
@@ -35,7 +33,7 @@ class LogglyFormatter extends JsonFormatter
* @see https://www.loggly.com/docs/automated-parsing/#json * @see https://www.loggly.com/docs/automated-parsing/#json
* @see \Monolog\Formatter\JsonFormatter::format() * @see \Monolog\Formatter\JsonFormatter::format()
*/ */
public function format(array $record) public function format(array $record): string
{ {
if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) { if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) {
$record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO"); $record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO");

View File

@@ -54,7 +54,7 @@ class LogmaticFormatter extends JsonFormatter
* @see http://doc.logmatic.io/docs/basics-to-send-data * @see http://doc.logmatic.io/docs/basics-to-send-data
* @see \Monolog\Formatter\JsonFormatter::format() * @see \Monolog\Formatter\JsonFormatter::format()
*/ */
public function format(array $record) public function format(array $record): string
{ {
if (!empty($this->hostname)) { if (!empty($this->hostname)) {
$record['hostname'] = $this->hostname; $record['hostname'] = $this->hostname;

View File

@@ -46,9 +46,8 @@ class LogstashFormatter extends NormalizerFormatter
* @param string $systemName the system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine * @param string $systemName the system/machine name, used as the "source" field of logstash, defaults to the hostname of the machine
* @param string $extraPrefix prefix for extra keys inside logstash "fields" * @param string $extraPrefix prefix for extra keys inside logstash "fields"
* @param string $contextPrefix prefix for context keys inside logstash "fields", defaults to ctxt_ * @param string $contextPrefix prefix for context keys inside logstash "fields", defaults to ctxt_
* @param int $version the logstash format version to use, defaults to 0
*/ */
public function __construct($applicationName, $systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_') public function __construct(string $applicationName, string $systemName = null, string $extraPrefix = null, string $contextPrefix = 'ctxt_')
{ {
// logstash requires a ISO 8601 format date with optional millisecond precision. // logstash requires a ISO 8601 format date with optional millisecond precision.
parent::__construct('Y-m-d\TH:i:s.uP'); parent::__construct('Y-m-d\TH:i:s.uP');
@@ -62,7 +61,7 @@ class LogstashFormatter extends NormalizerFormatter
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function format(array $record) public function format(array $record): string
{ {
$record = parent::format($record); $record = parent::format($record);

View File

@@ -27,16 +27,16 @@ class MongoDBFormatter implements FormatterInterface
* @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record['context'] is 2 * @param int $maxNestingLevel 0 means infinite nesting, the $record itself is level 1, $record['context'] is 2
* @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings * @param bool $exceptionTraceAsString set to false to log exception traces as a sub documents instead of strings
*/ */
public function __construct($maxNestingLevel = 3, $exceptionTraceAsString = true) public function __construct(int $maxNestingLevel = 3, bool $exceptionTraceAsString = true)
{ {
$this->maxNestingLevel = max($maxNestingLevel, 0); $this->maxNestingLevel = max($maxNestingLevel, 0);
$this->exceptionTraceAsString = (bool) $exceptionTraceAsString; $this->exceptionTraceAsString = $exceptionTraceAsString;
} }
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function format(array $record) public function format(array $record): array
{ {
return $this->formatArray($record); return $this->formatArray($record);
} }
@@ -44,7 +44,7 @@ class MongoDBFormatter implements FormatterInterface
/** /**
* {@inheritDoc} * {@inheritDoc}
*/ */
public function formatBatch(array $records) public function formatBatch(array $records): array
{ {
foreach ($records as $key => $record) { foreach ($records as $key => $record) {
$records[$key] = $this->format($record); $records[$key] = $this->format($record);
@@ -53,7 +53,10 @@ class MongoDBFormatter implements FormatterInterface
return $records; return $records;
} }
protected function formatArray(array $record, $nestingLevel = 0) /**
* @return array|string Array except when max nesting level is reached then a string "[...]"
*/
protected function formatArray(array $record, int $nestingLevel = 0)
{ {
if ($this->maxNestingLevel == 0 || $nestingLevel <= $this->maxNestingLevel) { if ($this->maxNestingLevel == 0 || $nestingLevel <= $this->maxNestingLevel) {
foreach ($record as $name => $value) { foreach ($record as $name => $value) {
@@ -74,7 +77,7 @@ class MongoDBFormatter implements FormatterInterface
return $record; return $record;
} }
protected function formatObject($value, $nestingLevel) protected function formatObject($value, int $nestingLevel)
{ {
$objectVars = get_object_vars($value); $objectVars = get_object_vars($value);
$objectVars['class'] = get_class($value); $objectVars['class'] = get_class($value);
@@ -82,7 +85,7 @@ class MongoDBFormatter implements FormatterInterface
return $this->formatArray($objectVars, $nestingLevel); return $this->formatArray($objectVars, $nestingLevel);
} }
protected function formatException(\Throwable $exception, $nestingLevel) protected function formatException(\Throwable $exception, int $nestingLevel)
{ {
$formattedException = [ $formattedException = [
'class' => get_class($exception), 'class' => get_class($exception),
@@ -100,7 +103,7 @@ class MongoDBFormatter implements FormatterInterface
return $this->formatArray($formattedException, $nestingLevel); return $this->formatArray($formattedException, $nestingLevel);
} }
protected function formatDate(\DateTimeInterface $value, $nestingLevel) protected function formatDate(\DateTimeInterface $value, int $nestingLevel): UTCDateTime
{ {
return new UTCDateTime((string) floor($value->format('U.u') * 1000)); return new UTCDateTime((string) floor($value->format('U.u') * 1000));
} }

View File

@@ -39,7 +39,7 @@ class NormalizerFormatter implements FormatterInterface
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function format(array $record) public function format(array $record): array
{ {
return $this->normalize($record); return $this->normalize($record);
} }
@@ -47,7 +47,7 @@ class NormalizerFormatter implements FormatterInterface
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function formatBatch(array $records) public function formatBatch(array $records): array
{ {
foreach ($records as $key => $record) { foreach ($records as $key => $record) {
$records[$key] = $this->format($record); $records[$key] = $this->format($record);
@@ -56,7 +56,11 @@ class NormalizerFormatter implements FormatterInterface
return $records; return $records;
} }
protected function normalize($data, $depth = 0) /**
* @param mixed $data
* @return int|bool|string|null|array
*/
protected function normalize($data, int $depth = 0)
{ {
if ($depth > 9) { if ($depth > 9) {
return 'Over 9 levels deep, aborting normalization'; return 'Over 9 levels deep, aborting normalization';
@@ -96,7 +100,7 @@ class NormalizerFormatter implements FormatterInterface
if (is_object($data)) { if (is_object($data)) {
if ($data instanceof Throwable) { if ($data instanceof Throwable) {
return $this->normalizeException($data); return $this->normalizeException($data, $depth);
} }
if ($data instanceof \JsonSerializable) { if ($data instanceof \JsonSerializable) {
@@ -123,7 +127,10 @@ class NormalizerFormatter implements FormatterInterface
return '[unknown('.gettype($data).')]'; return '[unknown('.gettype($data).')]';
} }
protected function normalizeException(Throwable $e) /**
* @return array
*/
protected function normalizeException(Throwable $e, int $depth = 0)
{ {
$data = [ $data = [
'class' => get_class($e), 'class' => get_class($e),
@@ -155,12 +162,12 @@ class NormalizerFormatter implements FormatterInterface
$data['trace'][] = $frame['function']; $data['trace'][] = $frame['function'];
} else { } else {
// We should again normalize the frames, because it might contain invalid items // We should again normalize the frames, because it might contain invalid items
$data['trace'][] = $this->toJson($this->normalize($frame), true); $data['trace'][] = $this->toJson($this->normalize($frame, $depth + 1), true);
} }
} }
if ($previous = $e->getPrevious()) { if ($previous = $e->getPrevious()) {
$data['previous'] = $this->normalizeException($previous); $data['previous'] = $this->normalizeException($previous, $depth + 1);
} }
return $data; return $data;
@@ -170,11 +177,10 @@ class NormalizerFormatter implements FormatterInterface
* Return the JSON representation of a value * Return the JSON representation of a value
* *
* @param mixed $data * @param mixed $data
* @param bool $ignoreErrors
* @throws \RuntimeException if encoding fails and errors are not ignored * @throws \RuntimeException if encoding fails and errors are not ignored
* @return string|bool * @return string|bool
*/ */
protected function toJson($data, $ignoreErrors = false) protected function toJson($data, bool $ignoreErrors = false)
{ {
// suppress json_encode errors since it's twitchy with some inputs // suppress json_encode errors since it's twitchy with some inputs
if ($ignoreErrors) { if ($ignoreErrors) {

View File

@@ -22,7 +22,7 @@ class ScalarFormatter extends NormalizerFormatter
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function format(array $record) public function format(array $record): array
{ {
foreach ($record as $key => $value) { foreach ($record as $key => $value) {
$record[$key] = $this->normalizeValue($value); $record[$key] = $this->normalizeValue($value);

View File

@@ -41,7 +41,7 @@ class WildfireFormatter extends NormalizerFormatter
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function format(array $record) public function format(array $record): string
{ {
// Retrieve the line and file if set and remove them from the formatted extra // Retrieve the line and file if set and remove them from the formatted extra
$file = $line = ''; $file = $line = '';
@@ -97,12 +97,18 @@ class WildfireFormatter extends NormalizerFormatter
); );
} }
/**
* {@inheritdoc}
*/
public function formatBatch(array $records) public function formatBatch(array $records)
{ {
throw new \BadMethodCallException('Batch formatting does not make sense for the WildfireFormatter'); throw new \BadMethodCallException('Batch formatting does not make sense for the WildfireFormatter');
} }
protected function normalize($data, $depth = 0) /**
* {@inheritdoc}
*/
protected function normalize($data, int $depth = 0)
{ {
if (is_object($data) && !$data instanceof \DateTimeInterface) { if (is_object($data) && !$data instanceof \DateTimeInterface) {
return $data; return $data;

View File

@@ -136,7 +136,7 @@ class Logger implements LoggerInterface
protected $timezone; protected $timezone;
/** /**
* @param string $name The logging channel * @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 HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
* @param callable[] $processors Optional array of processors * @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
@@ -149,9 +149,6 @@ class Logger implements LoggerInterface
$this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC'); $this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC');
} }
/**
* @return string
*/
public function getName(): string public function getName(): string
{ {
return $this->name; return $this->name;
@@ -159,8 +156,6 @@ class Logger implements LoggerInterface
/** /**
* Return a new cloned instance with the name changed * Return a new cloned instance with the name changed
*
* @return static
*/ */
public function withName(string $name): self public function withName(string $name): self
{ {
@@ -172,9 +167,6 @@ class Logger implements LoggerInterface
/** /**
* Pushes a handler on to the stack. * Pushes a handler on to the stack.
*
* @param HandlerInterface $handler
* @return $this
*/ */
public function pushHandler(HandlerInterface $handler): self public function pushHandler(HandlerInterface $handler): self
{ {
@@ -187,7 +179,6 @@ class Logger implements LoggerInterface
* Pops a handler from the stack * Pops a handler from the stack
* *
* @throws \LogicException If empty handler stack * @throws \LogicException If empty handler stack
* @return HandlerInterface
*/ */
public function popHandler(): HandlerInterface public function popHandler(): HandlerInterface
{ {
@@ -204,7 +195,6 @@ class Logger implements LoggerInterface
* If a map is passed, keys will be ignored. * If a map is passed, keys will be ignored.
* *
* @param HandlerInterface[] $handlers * @param HandlerInterface[] $handlers
* @return $this
*/ */
public function setHandlers(array $handlers): self public function setHandlers(array $handlers): self
{ {
@@ -226,9 +216,6 @@ class Logger implements LoggerInterface
/** /**
* Adds a processor on to the stack. * Adds a processor on to the stack.
*
* @param callable $callback
* @return $this
*/ */
public function pushProcessor(callable $callback): self public function pushProcessor(callable $callback): self
{ {
@@ -532,9 +519,11 @@ class Logger implements LoggerInterface
* *
* @param DateTimeZone $tz Timezone object * @param DateTimeZone $tz Timezone object
*/ */
public function setTimezone(DateTimeZone $tz) public function setTimezone(DateTimeZone $tz): self
{ {
$this->timezone = $tz; $this->timezone = $tz;
return $this;
} }
/** /**

View File

@@ -29,11 +29,7 @@ class GitProcessor
$this->level = Logger::toMonologLevel($level); $this->level = Logger::toMonologLevel($level);
} }
/** public function __invoke(array $record): array
* @param array $record
* @return array
*/
public function __invoke(array $record)
{ {
// return if the level is not high enough // return if the level is not high enough
if ($record['level'] < $this->level) { if ($record['level'] < $this->level) {
@@ -45,7 +41,7 @@ class GitProcessor
return $record; return $record;
} }
private static function getGitInfo() private static function getGitInfo(): array
{ {
if (self::$cache) { if (self::$cache) {
return self::$cache; return self::$cache;

View File

@@ -37,18 +37,14 @@ class IntrospectionProcessor
'call_user_func_array', 'call_user_func_array',
]; ];
public function __construct($level = Logger::DEBUG, array $skipClassesPartials = [], $skipStackFramesCount = 0) public function __construct($level = Logger::DEBUG, array $skipClassesPartials = [], int $skipStackFramesCount = 0)
{ {
$this->level = Logger::toMonologLevel($level); $this->level = Logger::toMonologLevel($level);
$this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials); $this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials);
$this->skipStackFramesCount = $skipStackFramesCount; $this->skipStackFramesCount = $skipStackFramesCount;
} }
/** public function __invoke(array $record): array
* @param array $record
* @return array
*/
public function __invoke(array $record)
{ {
// return if the level is not high enough // return if the level is not high enough
if ($record['level'] < $this->level) { if ($record['level'] < $this->level) {
@@ -96,7 +92,7 @@ class IntrospectionProcessor
return $record; return $record;
} }
private function isTraceClassOrSkippedFunction(array $trace, $index) private function isTraceClassOrSkippedFunction(array $trace, int $index)
{ {
if (!isset($trace[$index])) { if (!isset($trace[$index])) {
return false; return false;

View File

@@ -19,11 +19,7 @@ namespace Monolog\Processor;
*/ */
class MemoryPeakUsageProcessor extends MemoryProcessor class MemoryPeakUsageProcessor extends MemoryProcessor
{ {
/** public function __invoke(array $record): array
* @param array $record
* @return array
*/
public function __invoke(array $record)
{ {
$bytes = memory_get_peak_usage($this->realUsage); $bytes = memory_get_peak_usage($this->realUsage);
$formatted = $this->formatBytes($bytes); $formatted = $this->formatBytes($bytes);

View File

@@ -32,22 +32,20 @@ abstract class MemoryProcessor
* @param bool $realUsage Set this to true to get the real size of memory allocated from system. * @param bool $realUsage Set this to true to get the real size of memory allocated from system.
* @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size) * @param bool $useFormatting If true, then format memory size to human readable string (MB, KB, B depending on size)
*/ */
public function __construct($realUsage = true, $useFormatting = true) public function __construct(bool $realUsage = true, bool $useFormatting = true)
{ {
$this->realUsage = (boolean) $realUsage; $this->realUsage = $realUsage;
$this->useFormatting = (boolean) $useFormatting; $this->useFormatting = $useFormatting;
} }
/** /**
* Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is * Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is
* *
* @param int $bytes * @param int $bytes
* @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as is * @return string|int Formatted string if $this->useFormatting is true, otherwise return $bytes as int
*/ */
protected function formatBytes($bytes) protected function formatBytes(int $bytes)
{ {
$bytes = (int) $bytes;
if (!$this->useFormatting) { if (!$this->useFormatting) {
return $bytes; return $bytes;
} }

View File

@@ -19,11 +19,7 @@ namespace Monolog\Processor;
*/ */
class MemoryUsageProcessor extends MemoryProcessor class MemoryUsageProcessor extends MemoryProcessor
{ {
/** public function __invoke(array $record): array
* @param array $record
* @return array
*/
public function __invoke(array $record)
{ {
$bytes = memory_get_usage($this->realUsage); $bytes = memory_get_usage($this->realUsage);
$formatted = $this->formatBytes($bytes); $formatted = $this->formatBytes($bytes);

View File

@@ -28,11 +28,7 @@ class MercurialProcessor
$this->level = Logger::toMonologLevel($level); $this->level = Logger::toMonologLevel($level);
} }
/** public function __invoke(array $record): arra
* @param array $record
* @return array
*/
public function __invoke(array $record)
{ {
// return if the level is not high enough // return if the level is not high enough
if ($record['level'] < $this->level) { if ($record['level'] < $this->level) {
@@ -44,7 +40,7 @@ class MercurialProcessor
return $record; return $record;
} }
private static function getMercurialInfo() private static function getMercurialInfo(): array
{ {
if (self::$cache) { if (self::$cache) {
return self::$cache; return self::$cache;

View File

@@ -18,11 +18,7 @@ namespace Monolog\Processor;
*/ */
class ProcessIdProcessor class ProcessIdProcessor
{ {
/** public function __invoke(array $record): array
* @param array $record
* @return array
*/
public function __invoke(array $record)
{ {
$record['extra']['process_id'] = getmypid(); $record['extra']['process_id'] = getmypid();

View File

@@ -24,7 +24,7 @@ class PsrLogMessageProcessor
* @param array $record * @param array $record
* @return array * @return array
*/ */
public function __invoke(array $record) public function __invoke(array $record): array
{ {
if (false === strpos($record['message'], '{')) { if (false === strpos($record['message'], '{')) {
return $record; return $record;

View File

@@ -35,7 +35,7 @@ class TagProcessor
$this->tags = $tags; $this->tags = $tags;
} }
public function __invoke(array $record) public function __invoke(array $record): array
{ {
$record['extra']['tags'] = $this->tags; $record['extra']['tags'] = $this->tags;

View File

@@ -20,7 +20,7 @@ class UidProcessor
{ {
private $uid; private $uid;
public function __construct($length = 7) public function __construct(int $length = 7)
{ {
if (!is_int($length) || $length > 32 || $length < 1) { if (!is_int($length) || $length > 32 || $length < 1) {
throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32'); throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
@@ -29,7 +29,7 @@ class UidProcessor
$this->uid = substr(hash('md5', uniqid('', true)), 0, $length); $this->uid = substr(hash('md5', uniqid('', true)), 0, $length);
} }
public function __invoke(array $record) public function __invoke(array $record): array
{ {
$record['extra']['uid'] = $this->uid; $record['extra']['uid'] = $this->uid;
@@ -39,7 +39,7 @@ class UidProcessor
/** /**
* @return string * @return string
*/ */
public function getUid() public function getUid(): string
{ {
return $this->uid; return $this->uid;
} }

View File

@@ -65,11 +65,7 @@ class WebProcessor
} }
} }
/** public function __invoke(array $record): array
* @param array $record
* @return array
*/
public function __invoke(array $record)
{ {
// skip processing if for some reason request data // skip processing if for some reason request data
// is not present (CLI or wonky SAPIs) // is not present (CLI or wonky SAPIs)
@@ -82,23 +78,14 @@ class WebProcessor
return $record; return $record;
} }
/** public function addExtraField(string $extraName, string $serverName): self
* @param string $extraName
* @param string $serverName
* @return $this
*/
public function addExtraField($extraName, $serverName)
{ {
$this->extraFields[$extraName] = $serverName; $this->extraFields[$extraName] = $serverName;
return $this; return $this;
} }
/** private function appendExtraFields(array $extra): array
* @param array $extra
* @return array
*/
private function appendExtraFields(array $extra)
{ {
foreach ($this->extraFields as $extraName => $serverName) { foreach ($this->extraFields as $extraName => $serverName) {
$extra[$extraName] = isset($this->serverData[$serverName]) ? $this->serverData[$serverName] : null; $extra[$extraName] = isset($this->serverData[$serverName]) ? $this->serverData[$serverName] : null;

View File

@@ -74,9 +74,9 @@ class Registry
$index = array_search($logger, self::$loggers, true); $index = array_search($logger, self::$loggers, true);
return false !== $index; return false !== $index;
} else {
return isset(self::$loggers[$logger]);
} }
return isset(self::$loggers[$logger]);
} }
/** /**