1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-10-22 17:16:18 +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

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

View File

@@ -34,7 +34,7 @@ class ElasticaFormatter extends NormalizerFormatter
* @param string $index Elastic Search index name
* @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.
parent::__construct('Y-m-d\TH:i:s.uP');
@@ -53,31 +53,20 @@ class ElasticaFormatter extends NormalizerFormatter
return $this->getDocument($record);
}
/**
* Getter index
* @return string
*/
public function getIndex()
public function getIndex(): string
{
return $this->index;
}
/**
* Getter type
* @return string
*/
public function getType()
public function getType(): string
{
return $this->type;
}
/**
* 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->setData($record);

View File

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

View File

@@ -39,21 +39,21 @@ class FluentdFormatter implements FormatterInterface
*/
protected $levelTag = false;
public function __construct($levelTag = false)
public function __construct(bool $levelTag = false)
{
if (!function_exists('json_encode')) {
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;
}
public function format(array $record)
public function format(array $record): string
{
$tag = $record['channel'];
if ($this->levelTag) {
@@ -73,7 +73,7 @@ class FluentdFormatter implements FormatterInterface
return json_encode([$tag, $record['datetime']->getTimestamp(), $message]);
}
public function formatBatch(array $records)
public function formatBatch(array $records): string
{
$message = '';
foreach ($records as $record) {

View File

@@ -53,7 +53,7 @@ class GelfMessageFormatter extends NormalizerFormatter
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');
@@ -66,7 +66,7 @@ class GelfMessageFormatter extends NormalizerFormatter
/**
* {@inheritdoc}
*/
public function format(array $record)
public function format(array $record): Message
{
if (isset($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
*/
public function __construct($dateFormat = null)
public function __construct(string $dateFormat = null)
{
parent::__construct($dateFormat);
}
@@ -52,7 +52,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param bool $escapeTd false if td content must not be html escaped
* @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');
if ($escapeTd) {
@@ -69,7 +69,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param int $level Error level
* @return string
*/
protected function addTitle($title, $level)
protected function addTitle(string $title, int $level)
{
$title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8');
@@ -82,7 +82,7 @@ class HtmlFormatter extends NormalizerFormatter
* @param array $record A record to format
* @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 .= '<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
* @return mixed The formatted set of records
*/
public function formatBatch(array $records)
public function formatBatch(array $records): string
{
$message = '';
foreach ($records as $record) {
@@ -126,7 +126,7 @@ class HtmlFormatter extends NormalizerFormatter
return $message;
}
protected function convertToString($data)
protected function convertToString($data): string
{
if (null === $data || is_scalar($data)) {
return (string) $data;

View File

@@ -32,10 +32,7 @@ class JsonFormatter extends NormalizerFormatter
*/
protected $includeStacktraces = false;
/**
* @param int $batchMode
*/
public function __construct($batchMode = self::BATCH_MODE_JSON, $appendNewline = true)
public function __construct(int $batchMode = self::BATCH_MODE_JSON, bool $appendNewline = true)
{
$this->batchMode = $batchMode;
$this->appendNewline = $appendNewline;
@@ -47,20 +44,16 @@ class JsonFormatter extends NormalizerFormatter
* formatted as a JSON-encoded array. However, for
* compatibility with some API endpoints, alternative styles
* are available.
*
* @return int
*/
public function getBatchMode()
public function getBatchMode(): int
{
return $this->batchMode;
}
/**
* True if newlines are appended to every formatted record
*
* @return bool
*/
public function isAppendingNewlines()
public function isAppendingNewlines(): bool
{
return $this->appendNewline;
}
@@ -68,7 +61,7 @@ class JsonFormatter extends NormalizerFormatter
/**
* {@inheritdoc}
*/
public function format(array $record)
public function format(array $record): string
{
return $this->toJson($this->normalize($record), true) . ($this->appendNewline ? "\n" : '');
}
@@ -76,7 +69,7 @@ class JsonFormatter extends NormalizerFormatter
/**
* {@inheritdoc}
*/
public function formatBatch(array $records)
public function formatBatch(array $records): string
{
switch ($this->batchMode) {
case static::BATCH_MODE_NEWLINES:
@@ -91,18 +84,15 @@ class JsonFormatter extends NormalizerFormatter
/**
* @param bool $include
*/
public function includeStacktraces($include = true)
public function includeStacktraces(bool $include = true)
{
$this->includeStacktraces = $include;
}
/**
* 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);
}
@@ -110,11 +100,8 @@ class JsonFormatter extends NormalizerFormatter
/**
* Use new lines to separate records instead of a
* JSON-encoded array.
*
* @param array $records
* @return string
*/
protected function formatBatchNewlines(array $records)
protected function formatBatchNewlines(array $records): string
{
$instance = $this;
@@ -135,7 +122,7 @@ class JsonFormatter extends NormalizerFormatter
*
* @return mixed
*/
protected function normalize($data, $depth = 0)
protected function normalize($data, int $depth = 0)
{
if ($depth > 9) {
return 'Over 9 levels deep, aborting normalization';
@@ -157,7 +144,7 @@ class JsonFormatter extends NormalizerFormatter
}
if ($data instanceof Throwable) {
return $this->normalizeException($data);
return $this->normalizeException($data, $depth);
}
return $data;
@@ -166,12 +153,8 @@ class JsonFormatter extends NormalizerFormatter
/**
* Normalizes given exception with or without its own stack trace based on
* `includeStacktraces` property.
*
* @param Throwable $e
*
* @return array
*/
protected function normalizeException(Throwable $e)
protected function normalizeException(Throwable $e, int $depth = 0): array
{
$data = [
'class' => get_class($e),
@@ -196,7 +179,7 @@ class JsonFormatter extends NormalizerFormatter
}
if ($previous = $e->getPrevious()) {
$data['previous'] = $this->normalizeException($previous);
$data['previous'] = $this->normalizeException($previous, $depth + 1);
}
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 $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->allowInlineLineBreaks = $allowInlineLineBreaks;
@@ -42,7 +42,7 @@ class LineFormatter extends NormalizerFormatter
parent::__construct($dateFormat);
}
public function includeStacktraces($include = true)
public function includeStacktraces(bool $include = true)
{
$this->includeStacktraces = $include;
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;
}
public function ignoreEmptyContextAndExtra($ignore = true)
public function ignoreEmptyContextAndExtra(bool $ignore = true)
{
$this->ignoreEmptyContextAndExtra = $ignore;
}
@@ -63,7 +63,7 @@ class LineFormatter extends NormalizerFormatter
/**
* {@inheritdoc}
*/
public function format(array $record)
public function format(array $record): string
{
$vars = parent::format($record);
@@ -104,7 +104,7 @@ class LineFormatter extends NormalizerFormatter
return $output;
}
public function formatBatch(array $records)
public function formatBatch(array $records): string
{
$message = '';
foreach ($records as $record) {
@@ -114,12 +114,12 @@ class LineFormatter extends NormalizerFormatter
return $message;
}
public function stringify($value)
public function stringify($value): string
{
return $this->replaceNewlines($this->convertToString($value));
}
protected function normalizeException(\Throwable $e)
protected function normalizeException(\Throwable $e, int $depth = 0): string
{
$previousText = '';
if ($previous = $e->getPrevious()) {
@@ -136,7 +136,7 @@ class LineFormatter extends NormalizerFormatter
return $str;
}
protected function convertToString($data)
protected function convertToString($data): string
{
if (null === $data || is_bool($data)) {
return var_export($data, true);
@@ -149,7 +149,7 @@ class LineFormatter extends NormalizerFormatter
return $this->toJson($data, true);
}
protected function replaceNewlines($str)
protected function replaceNewlines(string $str): string
{
if ($this->allowInlineLineBreaks) {
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
* 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);
}
@@ -35,7 +33,7 @@ class LogglyFormatter extends JsonFormatter
* @see https://www.loggly.com/docs/automated-parsing/#json
* @see \Monolog\Formatter\JsonFormatter::format()
*/
public function format(array $record)
public function format(array $record): string
{
if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) {
$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 \Monolog\Formatter\JsonFormatter::format()
*/
public function format(array $record)
public function format(array $record): string
{
if (!empty($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 $extraPrefix prefix for extra keys inside logstash "fields"
* @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.
parent::__construct('Y-m-d\TH:i:s.uP');
@@ -62,7 +61,7 @@ class LogstashFormatter extends NormalizerFormatter
/**
* {@inheritdoc}
*/
public function format(array $record)
public function format(array $record): string
{
$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 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->exceptionTraceAsString = (bool) $exceptionTraceAsString;
$this->exceptionTraceAsString = $exceptionTraceAsString;
}
/**
* {@inheritDoc}
*/
public function format(array $record)
public function format(array $record): array
{
return $this->formatArray($record);
}
@@ -44,7 +44,7 @@ class MongoDBFormatter implements FormatterInterface
/**
* {@inheritDoc}
*/
public function formatBatch(array $records)
public function formatBatch(array $records): array
{
foreach ($records as $key => $record) {
$records[$key] = $this->format($record);
@@ -53,7 +53,10 @@ class MongoDBFormatter implements FormatterInterface
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) {
foreach ($record as $name => $value) {
@@ -74,7 +77,7 @@ class MongoDBFormatter implements FormatterInterface
return $record;
}
protected function formatObject($value, $nestingLevel)
protected function formatObject($value, int $nestingLevel)
{
$objectVars = get_object_vars($value);
$objectVars['class'] = get_class($value);
@@ -82,7 +85,7 @@ class MongoDBFormatter implements FormatterInterface
return $this->formatArray($objectVars, $nestingLevel);
}
protected function formatException(\Throwable $exception, $nestingLevel)
protected function formatException(\Throwable $exception, int $nestingLevel)
{
$formattedException = [
'class' => get_class($exception),
@@ -100,7 +103,7 @@ class MongoDBFormatter implements FormatterInterface
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));
}

View File

@@ -39,7 +39,7 @@ class NormalizerFormatter implements FormatterInterface
/**
* {@inheritdoc}
*/
public function format(array $record)
public function format(array $record): array
{
return $this->normalize($record);
}
@@ -47,7 +47,7 @@ class NormalizerFormatter implements FormatterInterface
/**
* {@inheritdoc}
*/
public function formatBatch(array $records)
public function formatBatch(array $records): array
{
foreach ($records as $key => $record) {
$records[$key] = $this->format($record);
@@ -56,7 +56,11 @@ class NormalizerFormatter implements FormatterInterface
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) {
return 'Over 9 levels deep, aborting normalization';
@@ -96,7 +100,7 @@ class NormalizerFormatter implements FormatterInterface
if (is_object($data)) {
if ($data instanceof Throwable) {
return $this->normalizeException($data);
return $this->normalizeException($data, $depth);
}
if ($data instanceof \JsonSerializable) {
@@ -123,7 +127,10 @@ class NormalizerFormatter implements FormatterInterface
return '[unknown('.gettype($data).')]';
}
protected function normalizeException(Throwable $e)
/**
* @return array
*/
protected function normalizeException(Throwable $e, int $depth = 0)
{
$data = [
'class' => get_class($e),
@@ -155,12 +162,12 @@ class NormalizerFormatter implements FormatterInterface
$data['trace'][] = $frame['function'];
} else {
// 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()) {
$data['previous'] = $this->normalizeException($previous);
$data['previous'] = $this->normalizeException($previous, $depth + 1);
}
return $data;
@@ -170,11 +177,10 @@ class NormalizerFormatter implements FormatterInterface
* Return the JSON representation of a value
*
* @param mixed $data
* @param bool $ignoreErrors
* @throws \RuntimeException if encoding fails and errors are not ignored
* @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
if ($ignoreErrors) {

View File

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

View File

@@ -41,7 +41,7 @@ class WildfireFormatter extends NormalizerFormatter
/**
* {@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
$file = $line = '';
@@ -97,12 +97,18 @@ class WildfireFormatter extends NormalizerFormatter
);
}
/**
* {@inheritdoc}
*/
public function formatBatch(array $records)
{
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) {
return $data;