summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitattributes7
-rw-r--r--.php_cs27
-rw-r--r--.travis.yml27
-rw-r--r--CHANGELOG.md6
-rw-r--r--LICENSE2
-rw-r--r--README.md13
-rw-r--r--UPGRADE.md17
-rw-r--r--composer.json18
-rw-r--r--doc/01-usage.md8
-rw-r--r--doc/02-handlers-formatters-processors.md146
-rw-r--r--doc/04-extending.md9
-rw-r--r--doc/message-structure.md18
-rw-r--r--doc/sockets.md2
-rw-r--r--phpunit.xml.dist2
-rw-r--r--src/Monolog/DateTimeImmutable.php64
-rw-r--r--src/Monolog/ErrorHandler.php86
-rw-r--r--src/Monolog/Formatter/ChromePHPFormatter.php17
-rw-r--r--src/Monolog/Formatter/ElasticaFormatter.php21
-rw-r--r--src/Monolog/Formatter/FlowdockFormatter.php29
-rw-r--r--src/Monolog/Formatter/FluentdFormatter.php18
-rw-r--r--src/Monolog/Formatter/FormatterInterface.php2
-rw-r--r--src/Monolog/Formatter/GelfMessageFormatter.php19
-rw-r--r--src/Monolog/Formatter/HtmlFormatter.php26
-rw-r--r--src/Monolog/Formatter/JsonFormatter.php67
-rw-r--r--src/Monolog/Formatter/LineFormatter.php36
-rw-r--r--src/Monolog/Formatter/LogglyFormatter.php12
-rw-r--r--src/Monolog/Formatter/LogmaticFormatter.php72
-rw-r--r--src/Monolog/Formatter/LogstashFormatter.php89
-rw-r--r--src/Monolog/Formatter/MongoDBFormatter.php63
-rw-r--r--src/Monolog/Formatter/NormalizerFormatter.php112
-rw-r--r--src/Monolog/Formatter/ScalarFormatter.php4
-rw-r--r--src/Monolog/Formatter/WildfireFormatter.php30
-rw-r--r--src/Monolog/Handler/AbstractHandler.php111
-rw-r--r--src/Monolog/Handler/AbstractProcessingHandler.php30
-rw-r--r--src/Monolog/Handler/AbstractSyslogHandler.php15
-rw-r--r--src/Monolog/Handler/AmqpHandler.php32
-rw-r--r--src/Monolog/Handler/BrowserConsoleHandler.php25
-rw-r--r--src/Monolog/Handler/BufferHandler.php18
-rw-r--r--src/Monolog/Handler/ChromePHPHandler.php59
-rw-r--r--src/Monolog/Handler/CouchDBHandler.php21
-rw-r--r--src/Monolog/Handler/CubeHandler.php10
-rw-r--r--src/Monolog/Handler/Curl/Util.php6
-rw-r--r--src/Monolog/Handler/DeduplicationHandler.php7
-rw-r--r--src/Monolog/Handler/DoctrineCouchDBHandler.php5
-rw-r--r--src/Monolog/Handler/DynamoDbHandler.php9
-rw-r--r--src/Monolog/Handler/ElasticSearchHandler.php16
-rw-r--r--src/Monolog/Handler/ErrorLogHandler.php22
-rw-r--r--src/Monolog/Handler/FilterHandler.php18
-rw-r--r--src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php2
-rw-r--r--src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php4
-rw-r--r--src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php2
-rw-r--r--src/Monolog/Handler/FingersCrossedHandler.php22
-rw-r--r--src/Monolog/Handler/FirePHPHandler.php45
-rw-r--r--src/Monolog/Handler/FleepHookHandler.php9
-rw-r--r--src/Monolog/Handler/FlowdockHandler.php8
-rw-r--r--src/Monolog/Handler/FormattableHandlerInterface.php37
-rw-r--r--src/Monolog/Handler/FormattableHandlerTrait.php60
-rw-r--r--src/Monolog/Handler/GelfHandler.php22
-rw-r--r--src/Monolog/Handler/GroupHandler.php16
-rw-r--r--src/Monolog/Handler/Handler.php53
-rw-r--r--src/Monolog/Handler/HandlerInterface.php38
-rw-r--r--src/Monolog/Handler/HandlerWrapper.php50
-rw-r--r--src/Monolog/Handler/HipChatHandler.php93
-rw-r--r--src/Monolog/Handler/IFTTTHandler.php10
-rw-r--r--src/Monolog/Handler/LogEntriesHandler.php2
-rw-r--r--src/Monolog/Handler/LogglyHandler.php15
-rw-r--r--src/Monolog/Handler/LogmaticHandler.php88
-rw-r--r--src/Monolog/Handler/MailHandler.php26
-rw-r--r--src/Monolog/Handler/MandrillHandler.php15
-rw-r--r--src/Monolog/Handler/MissingExtensionException.php2
-rw-r--r--src/Monolog/Handler/MongoDBHandler.php60
-rw-r--r--src/Monolog/Handler/NativeMailerHandler.php23
-rw-r--r--src/Monolog/Handler/NewRelicHandler.php5
-rw-r--r--src/Monolog/Handler/NoopHandler.php40
-rw-r--r--src/Monolog/Handler/NullHandler.php20
-rw-r--r--src/Monolog/Handler/PHPConsoleHandler.php50
-rw-r--r--src/Monolog/Handler/ProcessHandler.php202
-rw-r--r--src/Monolog/Handler/ProcessableHandlerInterface.php36
-rw-r--r--src/Monolog/Handler/ProcessableHandlerTrait.php62
-rw-r--r--src/Monolog/Handler/PsrHandler.php4
-rw-r--r--src/Monolog/Handler/PushoverHandler.php14
-rw-r--r--src/Monolog/Handler/RavenHandler.php28
-rw-r--r--src/Monolog/Handler/RedisHandler.php9
-rw-r--r--src/Monolog/Handler/RollbarHandler.php16
-rw-r--r--src/Monolog/Handler/RotatingFileHandler.php28
-rw-r--r--src/Monolog/Handler/SamplingHandler.php14
-rw-r--r--src/Monolog/Handler/SendGridHandler.php100
-rw-r--r--src/Monolog/Handler/Slack/SlackRecord.php11
-rw-r--r--src/Monolog/Handler/SlackHandler.php6
-rw-r--r--src/Monolog/Handler/SlackWebhookHandler.php26
-rw-r--r--src/Monolog/Handler/SlackbotHandler.php12
-rw-r--r--src/Monolog/Handler/SocketHandler.php17
-rw-r--r--src/Monolog/Handler/SqsHandler.php53
-rw-r--r--src/Monolog/Handler/StreamHandler.php10
-rw-r--r--src/Monolog/Handler/SwiftMailerHandler.php48
-rw-r--r--src/Monolog/Handler/SyslogHandler.php2
-rw-r--r--src/Monolog/Handler/SyslogUdp/UdpSocket.php6
-rw-r--r--src/Monolog/Handler/SyslogUdpHandler.php10
-rw-r--r--src/Monolog/Handler/TestHandler.php18
-rw-r--r--src/Monolog/Handler/WhatFailureGroupHandler.php8
-rw-r--r--src/Monolog/Handler/ZendMonitorHandler.php10
-rw-r--r--src/Monolog/Logger.php392
-rw-r--r--src/Monolog/Processor/GitProcessor.php16
-rw-r--r--src/Monolog/Processor/IntrospectionProcessor.php22
-rw-r--r--src/Monolog/Processor/MemoryPeakUsageProcessor.php8
-rw-r--r--src/Monolog/Processor/MemoryProcessor.php14
-rw-r--r--src/Monolog/Processor/MemoryUsageProcessor.php8
-rw-r--r--src/Monolog/Processor/MercurialProcessor.php19
-rw-r--r--src/Monolog/Processor/ProcessIdProcessor.php8
-rw-r--r--src/Monolog/Processor/PsrLogMessageProcessor.php20
-rw-r--r--src/Monolog/Processor/TagProcessor.php10
-rw-r--r--src/Monolog/Processor/UidProcessor.php10
-rw-r--r--src/Monolog/Processor/WebProcessor.php27
-rw-r--r--src/Monolog/Registry.php19
-rw-r--r--src/Monolog/Test/TestCase.php (renamed from tests/Monolog/TestCase.php)40
-rw-r--r--tests/Monolog/ErrorHandlerTest.php106
-rw-r--r--tests/Monolog/Formatter/ChromePHPFormatterTest.php98
-rw-r--r--tests/Monolog/Formatter/ElasticaFormatterTest.php20
-rw-r--r--tests/Monolog/Formatter/FlowdockFormatterTest.php14
-rw-r--r--tests/Monolog/Formatter/FluentdFormatterTest.php8
-rw-r--r--tests/Monolog/Formatter/GelfMessageFormatterTest.php78
-rw-r--r--tests/Monolog/Formatter/JsonFormatterTest.php36
-rw-r--r--tests/Monolog/Formatter/LineFormatterTest.php158
-rw-r--r--tests/Monolog/Formatter/LogglyFormatterTest.php7
-rw-r--r--tests/Monolog/Formatter/LogmaticFormatterTest.php36
-rw-r--r--tests/Monolog/Formatter/LogstashFormatterTest.php270
-rw-r--r--tests/Monolog/Formatter/MongoDBFormatterTest.php156
-rw-r--r--tests/Monolog/Formatter/NormalizerFormatterTest.php221
-rw-r--r--tests/Monolog/Formatter/ScalarFormatterTest.php68
-rw-r--r--tests/Monolog/Formatter/WildfireFormatterTest.php70
-rw-r--r--tests/Monolog/Handler/AbstractHandlerTest.php58
-rw-r--r--tests/Monolog/Handler/AbstractProcessingHandlerTest.php68
-rw-r--r--tests/Monolog/Handler/AmqpHandlerTest.php79
-rw-r--r--tests/Monolog/Handler/BrowserConsoleHandlerTest.php6
-rw-r--r--tests/Monolog/Handler/BufferHandlerTest.php6
-rw-r--r--tests/Monolog/Handler/ChromePHPHandlerTest.php62
-rw-r--r--tests/Monolog/Handler/CouchDBHandlerTest.php6
-rw-r--r--tests/Monolog/Handler/DeduplicationHandlerTest.php14
-rw-r--r--tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php18
-rw-r--r--tests/Monolog/Handler/DynamoDbHandlerTest.php17
-rw-r--r--tests/Monolog/Handler/ElasticSearchHandlerTest.php61
-rw-r--r--tests/Monolog/Handler/ErrorLogHandlerTest.php6
-rw-r--r--tests/Monolog/Handler/FilterHandlerTest.php12
-rw-r--r--tests/Monolog/Handler/FingersCrossedHandlerTest.php16
-rw-r--r--tests/Monolog/Handler/FirePHPHandlerTest.php18
-rw-r--r--tests/Monolog/Handler/FleepHookHandlerTest.php14
-rw-r--r--tests/Monolog/Handler/FlowdockHandlerTest.php17
-rw-r--r--tests/Monolog/Handler/GelfHandlerLegacyTest.php95
-rw-r--r--tests/Monolog/Handler/GelfHandlerTest.php9
-rw-r--r--tests/Monolog/Handler/GelfMockMessagePublisher.php25
-rw-r--r--tests/Monolog/Handler/GroupHandlerTest.php20
-rw-r--r--tests/Monolog/Handler/HandlerWrapperTest.php54
-rw-r--r--tests/Monolog/Handler/HipChatHandlerTest.php139
-rw-r--r--tests/Monolog/Handler/LogEntriesHandlerTest.php25
-rw-r--r--tests/Monolog/Handler/LogmaticHandlerTest.php83
-rw-r--r--tests/Monolog/Handler/MailHandlerTest.php17
-rw-r--r--tests/Monolog/Handler/MockRavenClient-gte-0-16-0.php27
-rw-r--r--tests/Monolog/Handler/MockRavenClient.php2
-rw-r--r--tests/Monolog/Handler/MongoDBHandlerTest.php67
-rw-r--r--tests/Monolog/Handler/NativeMailerHandlerTest.php11
-rw-r--r--tests/Monolog/Handler/NewRelicHandlerTest.php34
-rw-r--r--tests/Monolog/Handler/NoopHandlerTest.php49
-rw-r--r--tests/Monolog/Handler/NullHandlerTest.php4
-rw-r--r--tests/Monolog/Handler/PHPConsoleHandlerTest.php96
-rw-r--r--tests/Monolog/Handler/ProcessHandlerTest.php195
-rw-r--r--tests/Monolog/Handler/PsrHandlerTest.php14
-rw-r--r--tests/Monolog/Handler/PushoverHandlerTest.php19
-rw-r--r--tests/Monolog/Handler/RavenHandlerTest.php52
-rw-r--r--tests/Monolog/Handler/RedisHandlerTest.php40
-rw-r--r--tests/Monolog/Handler/RollbarHandlerTest.php22
-rw-r--r--tests/Monolog/Handler/RotatingFileHandlerTest.php110
-rw-r--r--tests/Monolog/Handler/SamplingHandlerTest.php4
-rw-r--r--tests/Monolog/Handler/Slack/SlackRecordTest.php40
-rw-r--r--tests/Monolog/Handler/SlackHandlerTest.php19
-rw-r--r--tests/Monolog/Handler/SlackWebhookHandlerTest.php4
-rw-r--r--tests/Monolog/Handler/SlackbotHandlerTest.php4
-rw-r--r--tests/Monolog/Handler/SocketHandlerTest.php49
-rw-r--r--tests/Monolog/Handler/StreamHandlerTest.php49
-rw-r--r--tests/Monolog/Handler/SwiftMailerHandlerTest.php23
-rw-r--r--tests/Monolog/Handler/SyslogHandlerTest.php6
-rw-r--r--tests/Monolog/Handler/SyslogUdpHandlerTest.php16
-rw-r--r--tests/Monolog/Handler/TestHandlerTest.php26
-rw-r--r--tests/Monolog/Handler/UdpSocketTest.php16
-rw-r--r--tests/Monolog/Handler/WhatFailureGroupHandlerTest.php20
-rw-r--r--tests/Monolog/Handler/ZendMonitorHandlerTest.php11
-rw-r--r--tests/Monolog/LoggerTest.php213
-rw-r--r--tests/Monolog/Processor/GitProcessorTest.php4
-rw-r--r--tests/Monolog/Processor/IntrospectionProcessorTest.php30
-rw-r--r--tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php4
-rw-r--r--tests/Monolog/Processor/MemoryUsageProcessorTest.php4
-rw-r--r--tests/Monolog/Processor/MercurialProcessorTest.php7
-rw-r--r--tests/Monolog/Processor/ProcessIdProcessorTest.php4
-rw-r--r--tests/Monolog/Processor/PsrLogMessageProcessorTest.php47
-rw-r--r--tests/Monolog/Processor/TagProcessorTest.php16
-rw-r--r--tests/Monolog/Processor/UidProcessorTest.php4
-rw-r--r--tests/Monolog/Processor/WebProcessorTest.php36
-rw-r--r--tests/Monolog/PsrLogCompatTest.php2
-rw-r--r--tests/Monolog/RegistryTest.php50
-rw-r--r--tests/bootstrap.php14
199 files changed, 4140 insertions, 3268 deletions
diff --git a/.gitattributes b/.gitattributes
index 4afe792..ed6e29a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,3 +1,4 @@
-.gitattributes export-ignore
-.gitignore export-ignore
-.travis.yml export-ignore
+/doc export-ignore
+/tests export-ignore
+/.* export-ignore
+/phpunit.xml.dist export-ignore
diff --git a/.php_cs b/.php_cs
index 366ccd0..34eb329 100644
--- a/.php_cs
+++ b/.php_cs
@@ -9,7 +9,7 @@ For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;
-$finder = Symfony\CS\Finder::create()
+$finder = PhpCsFixer\Finder::create()
->files()
->name('*.php')
->exclude('Fixtures')
@@ -17,43 +17,46 @@ $finder = Symfony\CS\Finder::create()
->in(__DIR__.'/tests')
;
-return Symfony\CS\Config::create()
+return PhpCsFixer\Config::create()
->setUsingCache(true)
- //->setUsingLinter(false)
->setRiskyAllowed(true)
->setRules(array(
'@PSR2' => true,
- 'binary_operator_spaces' => true,
+ // some rules disabled as long as 1.x branch is maintained
+ 'binary_operator_spaces' => array(
+ 'align_double_arrow' => null,
+ 'align_equals' => null,
+ ),
'blank_line_before_return' => true,
+ 'cast_spaces' => true,
'header_comment' => array('header' => $header),
'include' => true,
- 'long_array_syntax' => true,
'method_separation' => true,
'no_blank_lines_after_class_opening' => true,
'no_blank_lines_after_phpdoc' => true,
- 'no_blank_lines_between_uses' => true,
- 'no_duplicate_semicolons' => true,
+ 'no_empty_statement' => true,
'no_extra_consecutive_blank_lines' => true,
'no_leading_import_slash' => true,
'no_leading_namespace_whitespace' => true,
'no_trailing_comma_in_singleline_array' => true,
'no_unused_imports' => true,
+ 'no_whitespace_in_blank_line' => true,
'object_operator_without_whitespace' => true,
'phpdoc_align' => true,
'phpdoc_indent' => true,
'phpdoc_no_access' => true,
'phpdoc_no_package' => true,
'phpdoc_order' => true,
- 'phpdoc_scalar' => true,
+ //'phpdoc_scalar' => true,
'phpdoc_trim' => true,
- 'phpdoc_type_to_var' => true,
+ //'phpdoc_types' => true,
'psr0' => true,
+ //'array_syntax' => array('syntax' => 'short'),
+ 'declare_strict_types' => true,
'single_blank_line_before_namespace' => true,
- 'spaces_cast' => true,
'standardize_not_equals' => true,
'ternary_operator_spaces' => true,
'trailing_comma_in_multiline_array' => true,
- 'whitespacy_lines' => true,
))
- ->finder($finder)
+ ->setFinder($finder)
;
diff --git a/.travis.yml b/.travis.yml
index b821b45..6f62136 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,26 +4,25 @@ sudo: false
dist: trusty
php:
- - 5.4
- - 5.5
- - 5.6
- 7.0
- 7.1
- - hhvm
- nightly
+cache:
+ directories:
+ - $HOME/.composer/cache
+
matrix:
- include:
- - dist: precise
- php: 5.3
- - dist: precise
- php: 5.3
- env: deps=low
- fast_finish: true
+ include:
+ - php: 7.0
+ env: deps=low
+ fast_finish: true
before_script:
- - if [[ $TRAVIS_PHP_VERSION = 5.* ]]; then echo "extension = mongo.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini; fi
- - if [ "$deps" == "low" ]; then composer update --prefer-source --prefer-lowest --prefer-stable; fi
- - if [ "$deps" != "low" ]; then composer install --prefer-source; fi
+ - echo "extension = redis.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
+ - echo "extension = mongodb.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
+ - echo "extension = amqp.so" >> ~/.phpenv/versions/$(phpenv version-name)/etc/php.ini
+ - if [ "$deps" == "low" ]; then composer update --prefer-dist --prefer-lowest --prefer-stable; fi
+ - if [ "$deps" != "low" ]; then composer install --prefer-dist; fi
script: composer test
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cd1142d..b1cd458 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,7 +17,7 @@
* Added SlackbotHandler and SlackWebhookHandler to set up Slack integration more easily
* Added MercurialProcessor to add mercurial revision and branch names to log records
* Added support for AWS SDK v3 in DynamoDbHandler
- * Fixed fatal errors occuring when normalizing generators that have been fully consumed
+ * Fixed fatal errors occurring when normalizing generators that have been fully consumed
* Fixed RollbarHandler to include a level (rollbar level), monolog_level (original name), channel and datetime (unix)
* Fixed RollbarHandler not flushing records automatically, calling close() explicitly is not necessary anymore
* Fixed SyslogUdpHandler to avoid sending empty frames
@@ -27,7 +27,7 @@
* Break: Reverted the addition of $context when the ErrorHandler handles regular php errors from 1.20.0 as it was causing issues
* Added support for more formats in RotatingFileHandler::setFilenameFormat as long as they have Y, m and d in order
- * Added ability to format the main line of text the SlackHandler sends by explictly setting a formatter on the handler
+ * Added ability to format the main line of text the SlackHandler sends by explicitly setting a formatter on the handler
* Added information about SoapFault instances in NormalizerFormatter
* Added $handleOnlyReportedErrors option on ErrorHandler::registerErrorHandler (default true) to allow logging of all errors no matter the error_reporting level
@@ -149,7 +149,7 @@
* Added $useShortAttachment to SlackHandler to minify attachment size and $includeExtra to append extra data
* Added $host to HipChatHandler for users of private instances
* Added $transactionName to NewRelicHandler and support for a transaction_name context value
- * Fixed MandrillHandler to avoid outputing API call responses
+ * Fixed MandrillHandler to avoid outputting API call responses
* Fixed some non-standard behaviors in SyslogUdpHandler
### 1.11.0 (2014-09-30)
diff --git a/LICENSE b/LICENSE
index 1647321..b97667f 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2011-2016 Jordi Boggiano
+Copyright (c) 2011-2017 Jordi Boggiano
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
diff --git a/README.md b/README.md
index 7d8ade5..ea18c30 100644
--- a/README.md
+++ b/README.md
@@ -37,16 +37,17 @@ $log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));
// add records to the log
-$log->addWarning('Foo');
-$log->addError('Bar');
+$log->warning('Foo');
+$log->error('Bar');
```
## Documentation
- [Usage Instructions](doc/01-usage.md)
- [Handlers, Formatters and Processors](doc/02-handlers-formatters-processors.md)
-- [Utility classes](doc/03-utilities.md)
+- [Utility Classes](doc/03-utilities.md)
- [Extending Monolog](doc/04-extending.md)
+- [Log Record Structure](doc/message-structure.md)
## Third Party Packages
@@ -58,7 +59,7 @@ can also add your own there if you publish one.
### Requirements
-- Monolog works with PHP 5.3 or above, and is also tested to work with HHVM.
+- Monolog works with PHP 7.0 or above, use Monolog `^1.0` for PHP 5.3+ support.
### Submitting bugs and feature requests
@@ -79,6 +80,10 @@ Bugs and feature request are tracked on [GitHub](https://github.com/Seldaek/mono
- [Aura.Web_Project](https://github.com/auraphp/Aura.Web_Project) comes out of the box with Monolog.
- [Nette Framework](http://nette.org/en/) can be used with Monolog via [Kdyby/Monolog](https://github.com/Kdyby/Monolog) extension.
- [Proton Micro Framework](https://github.com/alexbilbie/Proton) comes out of the box with Monolog.
+- [FuelPHP](http://fuelphp.com/) comes out of the box with Monolog.
+- [Equip Framework](https://github.com/equip/framework) comes out of the box with Monolog.
+- [Yii 2](http://www.yiiframework.com/) is usable with Monolog via the [yii2-monolog](https://github.com/merorafael/yii2-monolog) plugin.
+- [Hawkbit Micro Framework](https://github.com/HawkBitPhp/hawkbit) comes out of the box with Monolog.
### Author
diff --git a/UPGRADE.md b/UPGRADE.md
new file mode 100644
index 0000000..81b6e90
--- /dev/null
+++ b/UPGRADE.md
@@ -0,0 +1,17 @@
+### 2.0.0
+
+- The timezone is now set per Logger instance and not statically, either
+ via ->setTimezone or passed in the constructor. Calls to Logger::setTimezone
+ should be converted.
+
+- Removed non-PSR-3 methods to add records, all the `add*` (e.g. `addWarning`)
+ methods as well as `emerg`, `crit`, `err` and `warn`.
+
+- `HandlerInterface` has been split off and two new interfaces now exist for
+ more granular controls: `ProcessableHandlerInterface` and
+ `FormattableHandlerInterface`. Handlers not extending `AbstractHandler`
+ should make sure to implement the relevant interfaces.
+
+- `HandlerInterface` now requires the `close` method to be implemented. This
+ only impacts you if you implement the interface yourself, but you can extend
+ the new `Monolog\Handler\Handler` base class.
diff --git a/composer.json b/composer.json
index 3b0c880..bc87c44 100644
--- a/composer.json
+++ b/composer.json
@@ -13,12 +13,12 @@
}
],
"require": {
- "php": ">=5.3.0",
- "psr/log": "~1.0"
+ "php": "^7.0",
+ "psr/log": "^1.0.1"
},
"require-dev": {
- "phpunit/phpunit": "~4.5",
- "graylog2/gelf-php": "~1.0",
+ "phpunit/phpunit": "^5.7",
+ "graylog2/gelf-php": "^1.4.2",
"sentry/sentry": "^0.13",
"ruflin/elastica": ">=0.90 <3.0",
"doctrine/couchdb": "~1.0@dev",
@@ -26,10 +26,10 @@
"php-amqplib/php-amqplib": "~2.4",
"swiftmailer/swiftmailer": "^5.3|^6.0",
"php-console/php-console": "^3.1.3",
- "phpunit/phpunit-mock-objects": "2.3.0",
- "jakub-onderka/php-parallel-lint": "0.9"
+ "jakub-onderka/php-parallel-lint": "^0.9",
+ "predis/predis": "^1.1",
+ "phpspec/prophecy": "^1.6.1"
},
- "_": "phpunit/phpunit-mock-objects required in 2.3.0 due to https://github.com/sebastianbergmann/phpunit-mock-objects/issues/223 - needs hhvm 3.8+ on travis",
"suggest": {
"graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server",
"sentry/sentry": "Allow sending log messages to a Sentry server",
@@ -37,8 +37,8 @@
"ruflin/elastica": "Allow sending log messages to an Elastic Search server",
"php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib",
"ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)",
- "ext-mongo": "Allow sending log messages to a MongoDB server",
- "mongodb/mongodb": "Allow sending log messages to a MongoDB server via PHP Driver",
+ "ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)",
+ "mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)",
"aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB",
"rollbar/rollbar": "Allow sending log messages to Rollbar",
"php-console/php-console": "Allow sending log messages to Google Chrome"
diff --git a/doc/01-usage.md b/doc/01-usage.md
index 8e2551f..ec9bbbb 100644
--- a/doc/01-usage.md
+++ b/doc/01-usage.md
@@ -24,7 +24,7 @@ to load Monolog classes.
## Core Concepts
Every `Logger` instance has a channel (name) and a stack of handlers. Whenever
-you add a record to the logger, it traverses the handler stack. Each handler
+you add a [record](message-structure.md) to the logger, it traverses the handler stack. Each handler
decides whether it fully handled the record, and if so, the propagation of the
record ends there.
@@ -97,7 +97,7 @@ $logger->pushHandler(new StreamHandler(__DIR__.'/my_app.log', Logger::DEBUG));
$logger->pushHandler(new FirePHPHandler());
// You can now use your logger
-$logger->addInfo('My logger is now ready');
+$logger->info('My logger is now ready');
```
Let's explain it. The first step is to create the logger instance which will
@@ -118,7 +118,7 @@ you want to override other configured loggers.
## Adding extra data in the records
-Monolog provides two different ways to add extra informations along the simple
+Monolog provides two different ways to add extra information along the simple
textual message.
### Using the logging context
@@ -129,7 +129,7 @@ record:
```php
<?php
-$logger->addInfo('Adding a new user', array('username' => 'Seldaek'));
+$logger->info('Adding a new user', array('username' => 'Seldaek'));
```
Simple handlers (like the StreamHandler for instance) will simply format
diff --git a/doc/02-handlers-formatters-processors.md b/doc/02-handlers-formatters-processors.md
index bea968a..9987908 100644
--- a/doc/02-handlers-formatters-processors.md
+++ b/doc/02-handlers-formatters-processors.md
@@ -15,71 +15,75 @@
### Log to files and syslog
-- _StreamHandler_: Logs records into any PHP stream, use this for log files.
-- _RotatingFileHandler_: Logs records to a file and creates one logfile per day.
+- [_StreamHandler_](../src/Monolog/Handler/StreamHandler.php): Logs records into any PHP stream, use this for log files.
+- [_RotatingFileHandler_](../src/Monolog/Handler/RotatingFileHandler.php): Logs records to a file and creates one logfile per day.
It will also delete files older than `$maxFiles`. You should use
[logrotate](http://linuxcommand.org/man_pages/logrotate8.html) for high profile
setups though, this is just meant as a quick and dirty solution.
-- _SyslogHandler_: Logs records to the syslog.
-- _ErrorLogHandler_: Logs records to PHP's
+- [_SyslogHandler_](../src/Monolog/Handler/SyslogHandler.php): Logs records to the syslog.
+- [_ErrorLogHandler_](../src/Monolog/Handler/ErrorLogHandler.php): Logs records to PHP's
[`error_log()`](http://docs.php.net/manual/en/function.error-log.php) function.
+- [_ProcessHandler_](../src/Monolog/Handler/ProcessHandler.php): Logs records to the [STDIN](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_.28stdin.29) of any process, specified by a command.
### Send alerts and emails
-- _NativeMailerHandler_: Sends emails using PHP's
+- [_NativeMailerHandler_](../src/Monolog/Handler/NativeMailerHandler.php): Sends emails using PHP's
[`mail()`](http://php.net/manual/en/function.mail.php) function.
-- _SwiftMailerHandler_: Sends emails using a [`Swift_Mailer`](http://swiftmailer.org/) instance.
-- _PushoverHandler_: Sends mobile notifications via the [Pushover](https://www.pushover.net/) API.
-- _HipChatHandler_: Logs records to a [HipChat](http://hipchat.com) chat room using its API.
-- _FlowdockHandler_: Logs records to a [Flowdock](https://www.flowdock.com/) account.
-- _SlackHandler_: Logs records to a [Slack](https://www.slack.com/) account using the Slack API.
-- _SlackbotHandler_: Logs records to a [Slack](https://www.slack.com/) account using the Slackbot incoming hook.
-- _SlackWebhookHandler_: Logs records to a [Slack](https://www.slack.com/) account using Slack Webhooks.
-- _MandrillHandler_: Sends emails via the Mandrill API using a [`Swift_Message`](http://swiftmailer.org/) instance.
-- _FleepHookHandler_: Logs records to a [Fleep](https://fleep.io/) conversation using Webhooks.
-- _IFTTTHandler_: Notifies an [IFTTT](https://ifttt.com/maker) trigger with the log channel, level name and message.
+- [_SwiftMailerHandler_](../src/Monolog/Handler/SwiftMailerHandler.php): Sends emails using a [`Swift_Mailer`](http://swiftmailer.org/) instance.
+- [_PushoverHandler_](../src/Monolog/Handler/PushoverHandler.php): Sends mobile notifications via the [Pushover](https://www.pushover.net/) API.
+- [_HipChatHandler_](../src/Monolog/Handler/HipChatHandler.php): Logs records to a [HipChat](http://hipchat.com) chat room using its API.
+- [_FlowdockHandler_](../src/Monolog/Handler/FlowdockHandler.php): Logs records to a [Flowdock](https://www.flowdock.com/) account.
+- [_SlackbotHandler_](../src/Monolog/Handler/SlackbotHandler.php): Logs records to a [Slack](https://www.slack.com/) account using the Slackbot incoming hook.
+- [_SlackWebhookHandler_](../src/Monolog/Handler/SlackWebhookHandler.php): Logs records to a [Slack](https://www.slack.com/) account using Slack Webhooks.
+- [_SlackHandler_](../src/Monolog/Handler/SlackHandler.php): Logs records to a [Slack](https://www.slack.com/) account using the Slack API (complex setup).
+- [_SendGridHandler_](../src/Monolog/Handler/SendGridHandler.php): Sends emails via the SendGrid API.
+- [_MandrillHandler_](../src/Monolog/Handler/MandrillHandler.php): Sends emails via the Mandrill API using a [`Swift_Message`](http://swiftmailer.org/) instance.
+- [_FleepHookHandler_](../src/Monolog/Handler/FleepHookHandler.php): Logs records to a [Fleep](https://fleep.io/) conversation using Webhooks.
+- [_IFTTTHandler_](../src/Monolog/Handler/IFTTTHandler.php): Notifies an [IFTTT](https://ifttt.com/maker) trigger with the log channel, level name and message.
### Log specific servers and networked logging
-- _SocketHandler_: Logs records to [sockets](http://php.net/fsockopen), use this
+- [_SocketHandler_](../src/Monolog/Handler/SocketHandler.php): Logs records to [sockets](http://php.net/fsockopen), use this
for UNIX and TCP sockets. See an [example](sockets.md).
-- _AmqpHandler_: Logs records to an [amqp](http://www.amqp.org/) compatible
+- [_AmqpHandler_](../src/Monolog/Handler/AmqpHandler.php): Logs records to an [amqp](http://www.amqp.org/) compatible
server. Requires the [php-amqp](http://pecl.php.net/package/amqp) extension (1.0+).
-- _GelfHandler_: Logs records to a [Graylog2](http://www.graylog2.org) server.
-- _CubeHandler_: Logs records to a [Cube](http://square.github.com/cube/) server.
-- _RavenHandler_: Logs records to a [Sentry](http://getsentry.com/) server using
+- [_GelfHandler_](../src/Monolog/Handler/GelfHandler.php): Logs records to a [Graylog2](http://www.graylog2.org) server.
+- [_CubeHandler_](../src/Monolog/Handler/CubeHandler.php): Logs records to a [Cube](http://square.github.com/cube/) server.
+- [_RavenHandler_](../src/Monolog/Handler/RavenHandler.php): Logs records to a [Sentry](http://getsentry.com/) server using
[raven](https://packagist.org/packages/raven/raven).
-- _ZendMonitorHandler_: Logs records to the Zend Monitor present in Zend Server.
-- _NewRelicHandler_: Logs records to a [NewRelic](http://newrelic.com/) application.
-- _LogglyHandler_: Logs records to a [Loggly](http://www.loggly.com/) account.
-- _RollbarHandler_: Logs records to a [Rollbar](https://rollbar.com/) account.
-- _SyslogUdpHandler_: Logs records to a remote [Syslogd](http://www.rsyslog.com/) server.
-- _LogEntriesHandler_: Logs records to a [LogEntries](http://logentries.com/) account.
+- [_ZendMonitorHandler_](../src/Monolog/Handler/ZendMonitorHandler.php): Logs records to the Zend Monitor present in Zend Server.
+- [_NewRelicHandler_](../src/Monolog/Handler/NewRelicHandler.php): Logs records to a [NewRelic](http://newrelic.com/) application.
+- [_LogglyHandler_](../src/Monolog/Handler/LogglyHandler.php): Logs records to a [Loggly](http://www.loggly.com/) account.
+- [_RollbarHandler_](../src/Monolog/Handler/RollbarHandler.php): Logs records to a [Rollbar](https://rollbar.com/) account.
+- [_SyslogUdpHandler_](../src/Monolog/Handler/SyslogUdpHandler.php): Logs records to a remote [Syslogd](http://www.rsyslog.com/) server.
+- [_LogEntriesHandler_](../src/Monolog/Handler/LogEntriesHandler.php): Logs records to a [LogEntries](http://logentries.com/) account.
+- [_LogmaticHandler_](../src/Monolog/Handler/LogmaticHandler.php): Logs records to a [Logmatic](http://logmatic.io/) account.
+- [_SqsHandler_](../src/Monolog/Handler/SqsHandler.php): Logs records to an [AWS SQS](http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-sqs.html) queue.
### Logging in development
-- _FirePHPHandler_: Handler for [FirePHP](http://www.firephp.org/), providing
+- [_FirePHPHandler_](../src/Monolog/Handler/FirePHPHandler.php): Handler for [FirePHP](http://www.firephp.org/), providing
inline `console` messages within [FireBug](http://getfirebug.com/).
-- _ChromePHPHandler_: Handler for [ChromePHP](http://www.chromephp.com/), providing
+- [_ChromePHPHandler_](../src/Monolog/Handler/ChromePHPHandler.php): Handler for [ChromePHP](http://www.chromephp.com/), providing
inline `console` messages within Chrome.
-- _BrowserConsoleHandler_: Handler to send logs to browser's Javascript `console` with
+- [_BrowserConsoleHandler_](../src/Monolog/Handler/BrowserConsoleHandler.php): Handler to send logs to browser's Javascript `console` with
no browser extension required. Most browsers supporting `console` API are supported.
-- _PHPConsoleHandler_: Handler for [PHP Console](https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef), providing
+- [_PHPConsoleHandler_](../src/Monolog/Handler/PHPConsoleHandler.php): Handler for [PHP Console](https://chrome.google.com/webstore/detail/php-console/nfhmhhlpfleoednkpnnnkolmclajemef), providing
inline `console` and notification popup messages within Chrome.
### Log to databases
-- _RedisHandler_: Logs records to a [redis](http://redis.io) server.
-- _MongoDBHandler_: Handler to write records in MongoDB via a
+- [_RedisHandler_](../src/Monolog/Handler/RedisHandler.php): Logs records to a [redis](http://redis.io) server.
+- [_MongoDBHandler_](../src/Monolog/Handler/MongoDBHandler.php): Handler to write records in MongoDB via a
[Mongo](http://pecl.php.net/package/mongo) extension connection.
-- _CouchDBHandler_: Logs records to a CouchDB server.
-- _DoctrineCouchDBHandler_: Logs records to a CouchDB server via the Doctrine CouchDB ODM.
-- _ElasticSearchHandler_: Logs records to an Elastic Search server.
-- _DynamoDbHandler_: Logs records to a DynamoDB table with the [AWS SDK](https://github.com/aws/aws-sdk-php).
+- [_CouchDBHandler_](../src/Monolog/Handler/CouchDBHandler.php): Logs records to a CouchDB server.
+- [_DoctrineCouchDBHandler_](../src/Monolog/Handler/DoctrineCouchDBHandler.php): Logs records to a CouchDB server via the Doctrine CouchDB ODM.
+- [_ElasticSearchHandler_](../src/Monolog/Handler/ElasticSearchHandler.php): Logs records to an Elastic Search server.
+- [_DynamoDbHandler_](../src/Monolog/Handler/DynamoDbHandler.php): Logs records to a DynamoDB table with the [AWS SDK](https://github.com/aws/aws-sdk-php).
### Wrappers / Special Handlers
-- _FingersCrossedHandler_: A very interesting wrapper. It takes a logger as
+- [_FingersCrossedHandler_](../src/Monolog/Handler/FingersCrossedHandler.php): A very interesting wrapper. It takes a logger as
parameter and will accumulate log records of all levels until a record
exceeds the defined severity level. At which point it delivers all records,
including those of lower severity, to the handler it wraps. This means that
@@ -87,7 +91,7 @@
when it happens you will have the full information, including debug and info
records. This provides you with all the information you need, but only when
you need it.
-- _DeduplicationHandler_: Useful if you are sending notifications or emails
+- [_DeduplicationHandler_](../src/Monolog/Handler/DeduplicationHandler.php): Useful if you are sending notifications or emails
when critical errors occur. It takes a logger as parameter and will
accumulate log records of all levels until the end of the request (or
`flush()` is called). At that point it delivers all records to the handler
@@ -97,56 +101,60 @@
database is unreachable for example all your requests will fail and that
can result in a lot of notifications being sent. Adding this handler reduces
the amount of notifications to a manageable level.
-- _WhatFailureGroupHandler_: This handler extends the _GroupHandler_ ignoring
+- [_WhatFailureGroupHandler_](../src/Monolog/Handler/WhatFailureGroupHandler.php): This handler extends the _GroupHandler_ ignoring
exceptions raised by each child handler. This allows you to ignore issues
where a remote tcp connection may have died but you do not want your entire
application to crash and may wish to continue to log to other handlers.
-- _BufferHandler_: This handler will buffer all the log records it receives
+- [_BufferHandler_](../src/Monolog/Handler/BufferHandler.php): This handler will buffer all the log records it receives
until `close()` is called at which point it will call `handleBatch()` on the
handler it wraps with all the log messages at once. This is very useful to
send an email with all records at once for example instead of having one mail
for every log record.
-- _GroupHandler_: This handler groups other handlers. Every record received is
+- [_GroupHandler_](../src/Monolog/Handler/GroupHandler.php): This handler groups other handlers. Every record received is
sent to all the handlers it is configured with.
-- _FilterHandler_: This handler only lets records of the given levels through
+- [_FilterHandler_](../src/Monolog/Handler/FilterHandler.php): This handler only lets records of the given levels through
to the wrapped handler.
-- _SamplingHandler_: Wraps around another handler and lets you sample records
+- [_SamplingHandler_](../src/Monolog/Handler/SamplingHandler.php): Wraps around another handler and lets you sample records
if you only want to store some of them.
-- _NullHandler_: Any record it can handle will be thrown away. This can be used
+- [_NoopHandler_](../src/Monolog/Handler/NoopHandler.php): This handler handles anything by doing nothing. It does not stop
+ processing the rest of the stack. This can be used for testing, or to disable a handler when overriding a configuration.
+- [_NullHandler_](../src/Monolog/Handler/NullHandler.php): Any record it can handle will be thrown away. This can be used
to put on top of an existing handler stack to disable it temporarily.
-- _PsrHandler_: Can be used to forward log records to an existing PSR-3 logger
-- _TestHandler_: Used for testing, it records everything that is sent to it and
+- [_PsrHandler_](../src/Monolog/Handler/PsrHandler.php): Can be used to forward log records to an existing PSR-3 logger
+- [_TestHandler_](../src/Monolog/Handler/TestHandler.php): Used for testing, it records everything that is sent to it and
has accessors to read out the information.
-- _HandlerWrapper_: A simple handler wrapper you can inherit from to create
+- [_HandlerWrapper_](../src/Monolog/Handler/HandlerWrapper.php): A simple handler wrapper you can inherit from to create
your own wrappers easily.
## Formatters
-- _LineFormatter_: Formats a log record into a one-line string.
-- _HtmlFormatter_: Used to format log records into a human readable html table, mainly suitable for emails.
-- _NormalizerFormatter_: Normalizes objects/resources down to strings so a record can easily be serialized/encoded.
-- _ScalarFormatter_: Used to format log records into an associative array of scalar values.
-- _JsonFormatter_: Encodes a log record into json.
-- _WildfireFormatter_: Used to format log records into the Wildfire/FirePHP protocol, only useful for the FirePHPHandler.
-- _ChromePHPFormatter_: Used to format log records into the ChromePHP format, only useful for the ChromePHPHandler.
-- _GelfMessageFormatter_: Used to format log records into Gelf message instances, only useful for the GelfHandler.
-- _LogstashFormatter_: Used to format log records into [logstash](http://logstash.net/) event json, useful for any handler listed under inputs [here](http://logstash.net/docs/latest).
-- _ElasticaFormatter_: Used to format log records into an Elastica\Document object, only useful for the ElasticSearchHandler.
-- _LogglyFormatter_: Used to format log records into Loggly messages, only useful for the LogglyHandler.
-- _FlowdockFormatter_: Used to format log records into Flowdock messages, only useful for the FlowdockHandler.
-- _MongoDBFormatter_: Converts \DateTime instances to \MongoDate and objects recursively to arrays, only useful with the MongoDBHandler.
+- [_LineFormatter_](../src/Monolog/Formatter/LineFormatter.php): Formats a log record into a one-line string.
+- [_HtmlFormatter_](../src/Monolog/Formatter/HtmlFormatter.php): Used to format log records into a human readable html table, mainly suitable for emails.
+- [_NormalizerFormatter_](../src/Monolog/Formatter/NormalizerFormatter.php): Normalizes objects/resources down to strings so a record can easily be serialized/encoded.
+- [_ScalarFormatter_](../src/Monolog/Formatter/ScalarFormatter.php): Used to format log records into an associative array of scalar values.
+- [_JsonFormatter_](../src/Monolog/Formatter/JsonFormatter.php): Encodes a log record into json.
+- [_WildfireFormatter_](../src/Monolog/Formatter/WildfireFormatter.php): Used to format log records into the Wildfire/FirePHP protocol, only useful for the FirePHPHandler.
+- [_ChromePHPFormatter_](../src/Monolog/Formatter/ChromePHPFormatter.php): Used to format log records into the ChromePHP format, only useful for the ChromePHPHandler.
+- [_GelfMessageFormatter_](../src/Monolog/Formatter/GelfMessageFormatter.php): Used to format log records into Gelf message instances, only useful for the GelfHandler.
+- [_LogstashFormatter_](../src/Monolog/Formatter/LogstashFormatter.php): Used to format log records into [logstash](http://logstash.net/) event json, useful for any handler listed under inputs [here](http://logstash.net/docs/latest).
+- [_ElasticaFormatter_](../src/Monolog/Formatter/ElasticaFormatter.php): Used to format log records into an Elastica\Document object, only useful for the ElasticSearchHandler.
+- [_LogglyFormatter_](../src/Monolog/Formatter/LogglyFormatter.php): Used to format log records into Loggly messages, only useful for the LogglyHandler.
+- [_FlowdockFormatter_](../src/Monolog/Formatter/FlowdockFormatter.php): Used to format log records into Flowdock messages, only useful for the FlowdockHandler.
+- [_MongoDBFormatter_](../src/Monolog/Formatter/MongoDBFormatter.php): Converts \DateTime instances to \MongoDate and objects recursively to arrays, only useful with the MongoDBHandler.
+- [_LogmaticFormatter_](../src/Monolog/Formatter/LogmaticFormatter.php): User to format log records to [Logmatic](http://logmatic.io/) messages, only useful for the LogmaticHandler.
## Processors
-- _PsrLogMessageProcessor_: Processes a log record's message according to PSR-3 rules, replacing `{foo}` with the value from `$context['foo']`.
-- _IntrospectionProcessor_: Adds the line/file/class/method from which the log call originated.
-- _WebProcessor_: Adds the current request URI, request method and client IP to a log record.
-- _MemoryUsageProcessor_: Adds the current memory usage to a log record.
-- _MemoryPeakUsageProcessor_: Adds the peak memory usage to a log record.
-- _ProcessIdProcessor_: Adds the process id to a log record.
-- _UidProcessor_: Adds a unique identifier to a log record.
-- _GitProcessor_: Adds the current git branch and commit to a log record.
-- _TagProcessor_: Adds an array of predefined tags to a log record.
+- [_PsrLogMessageProcessor_](../src/Monolog/Processor/PsrLogMessageProcessor.php): Processes a log record's message according to PSR-3 rules, replacing `{foo}` with the value from `$context['foo']`.
+- [_IntrospectionProcessor_](../src/Monolog/Processor/IntrospectionProcessor.php): Adds the line/file/class/method from which the log call originated.
+- [_WebProcessor_](../src/Monolog/Processor/WebProcessor.php): Adds the current request URI, request method and client IP to a log record.
+- [_MemoryUsageProcessor_](../src/Monolog/Processor/MemoryUsageProcessor.php): Adds the current memory usage to a log record.
+- [_MemoryPeakUsageProcessor_](../src/Monolog/Processor/MemoryPeakUsageProcessor.php): Adds the peak memory usage to a log record.
+- [_ProcessIdProcessor_](../src/Monolog/Processor/ProcessIdProcessor.php): Adds the process id to a log record.
+- [_UidProcessor_](../src/Monolog/Processor/UidProcessor.php): Adds a unique identifier to a log record.
+- [_GitProcessor_](../src/Monolog/Processor/GitProcessor.php): Adds the current git branch and commit to a log record.
+- [_MercurialProcessor_](../src/Monolog/Processor/MercurialProcessor.php): Adds the current hg branch and commit to a log record.
+- [_TagProcessor_](../src/Monolog/Processor/TagProcessor.php): Adds an array of predefined tags to a log record.
## Third Party Packages
diff --git a/doc/04-extending.md b/doc/04-extending.md
index ebd9104..ffb0700 100644
--- a/doc/04-extending.md
+++ b/doc/04-extending.md
@@ -2,6 +2,13 @@
Monolog is fully extensible, allowing you to adapt your logger to your needs.
+## Understanding log records
+
+See [the page about log records](message-structure.md) to learn what makes up
+a log record before going further. This is essential to understand as all
+Handlers/Formatters/Processors need to deal with log records in one way or
+another.
+
## Writing your own handler
Monolog provides many built-in handlers. But if the one you need does not
@@ -66,7 +73,7 @@ You can now use this handler in your logger:
$logger->pushHandler(new PDOHandler(new PDO('sqlite:logs.sqlite')));
// You can now use your logger
-$logger->addInfo('My logger is now ready');
+$logger->info('My logger is now ready');
```
The `Monolog\Handler\AbstractProcessingHandler` class provides most of the
diff --git a/doc/message-structure.md b/doc/message-structure.md
new file mode 100644
index 0000000..093a10c
--- /dev/null
+++ b/doc/message-structure.md
@@ -0,0 +1,18 @@
+# Log message structure
+
+Within monolog log messages are passed around as arrays, for example to processors or handlers.
+The table below describes which keys are always available for every log message.
+
+key | type | description
+-----------|---------------------------|-------------------------------------------------------------------------------
+message | string | The log message. When the `PsrLogMessageProcessor` is used this string may contain placeholders that will be replaced by variables from the context, e.g., "User %username% logged in" with `['username' => 'John']` as context will be written as "User John logged in".
+level | int | Severity of the log message. See log levels described in [01-usage.md](01-usage.md).
+level_name | string | String representation of log level.
+context | array | Arbitrary data passed with the construction of the message. For example the username of the current user or their IP address.
+channel | string | The channel this message was logged to. This is the name that was passed when the logger was created with `new Logger($channel)`.
+datetime | Monolog\DateTimeImmutable | Date and time when the message was logged. Class extends `\DateTimeImmutable`.
+extra | array | A placeholder array where processors can put additional data. Always available, but empty if there are no processors registered.
+
+At first glance `context` and `extra` look very similar, and they are in the sense that they both carry arbitrary data that is related to the log message somehow.
+The main difference is that `context` can be supplied in user land (it is the 3rd parameter to `Logger::addRecord()`) whereas `extra` is internal only and can be filled by processors.
+The reason processors write to `extra` and not to `context` is to prevent overriding any user provided data in `context`.
diff --git a/doc/sockets.md b/doc/sockets.md
index ea9cf0e..c1190c2 100644
--- a/doc/sockets.md
+++ b/doc/sockets.md
@@ -29,7 +29,7 @@ $handler->setPersistent(true);
$logger->pushHandler($handler, Logger::DEBUG);
// You can now use your logger
-$logger->addInfo('My logger is now ready');
+$logger->info('My logger is now ready');
```
diff --git a/phpunit.xml.dist b/phpunit.xml.dist
index 20d82b6..54da281 100644
--- a/phpunit.xml.dist
+++ b/phpunit.xml.dist
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
-<phpunit bootstrap="vendor/autoload.php" colors="true">
+<phpunit bootstrap="tests/bootstrap.php" colors="true">
<testsuites>
<testsuite name="Monolog Test Suite">
<directory>tests/Monolog/</directory>
diff --git a/src/Monolog/DateTimeImmutable.php b/src/Monolog/DateTimeImmutable.php
new file mode 100644
index 0000000..4e9f598
--- /dev/null
+++ b/src/Monolog/DateTimeImmutable.php
@@ -0,0 +1,64 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog;
+
+/**
+ * Overrides default json encoding of date time objects
+ *
+ * @author Menno Holtkamp
+ * @author Jordi Boggiano <j.boggiano@seld.be>
+ */
+class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable
+{
+ private $useMicroseconds;
+
+ public function __construct($useMicroseconds, \DateTimeZone $timezone = null)
+ {
+ static $needsMicrosecondsHack = PHP_VERSION_ID < 70100;
+
+ $this->useMicroseconds = $useMicroseconds;
+ $date = 'now';
+
+ if ($needsMicrosecondsHack && $useMicroseconds) {
+ $timestamp = microtime(true);
+
+ // apply offset of the timezone as microtime() is always UTC
+ if ($timezone && $timezone->getName() !== 'UTC') {
+ $timestamp += (new \DateTime('now', $timezone))->getOffset();
+ }
+
+ // Circumvent DateTimeImmutable::createFromFormat() which always returns \DateTimeImmutable instead of `static`
+ // @link https://bugs.php.net/bug.php?id=60302
+ //
+ // So we create a DateTime but then format it so we
+ // can re-create one using the right class
+ $dt = self::createFromFormat('U.u', sprintf('%.6F', $timestamp));
+ $date = $dt->format('Y-m-d H:i:s.u');
+ }
+
+ parent::__construct($date, $timezone);
+ }
+
+ public function jsonSerialize(): string
+ {
+ if ($this->useMicroseconds) {
+ return $this->format('Y-m-d\TH:i:s.uP');
+ }
+
+ return $this->format('Y-m-d\TH:i:sP');
+ }
+
+ public function __toString(): string
+ {
+ return $this->jsonSerialize();
+ }
+}
diff --git a/src/Monolog/ErrorHandler.php b/src/Monolog/ErrorHandler.php
index 7bfcd83..d0b1aa6 100644
--- a/src/Monolog/ErrorHandler.php
+++ b/src/Monolog/ErrorHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,6 @@ namespace Monolog;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
-use Monolog\Handler\AbstractHandler;
/**
* Monolog error handler
@@ -29,7 +28,7 @@ class ErrorHandler
private $logger;
private $previousExceptionHandler;
- private $uncaughtExceptionLevel;
+ private $uncaughtExceptionLevelMap;
private $previousErrorHandler;
private $errorLevelMap;
@@ -38,7 +37,7 @@ class ErrorHandler
private $hasFatalErrorHandler;
private $fatalLevel;
private $reservedMemory;
- private static $fatalErrors = array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR);
+ private static $fatalErrors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
public function __construct(LoggerInterface $logger)
{
@@ -51,12 +50,12 @@ class ErrorHandler
* By default it will handle errors, exceptions and fatal errors
*
* @param LoggerInterface $logger
- * @param array|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling
- * @param int|false $exceptionLevel a LogLevel::* constant, or false to disable exception handling
- * @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling
+ * @param array|false $errorLevelMap an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling
+ * @param array|false $exceptionLevelMap an array of class name to LogLevel::* constant mapping, or false to disable exception handling
+ * @param int|false $fatalLevel a LogLevel::* constant, or false to disable fatal error handling
* @return ErrorHandler
*/
- public static function register(LoggerInterface $logger, $errorLevelMap = array(), $exceptionLevel = null, $fatalLevel = null)
+ public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null): self
{
//Forces the autoloader to run for LogLevel. Fixes an autoload issue at compile-time on PHP5.3. See https://github.com/Seldaek/monolog/pull/929
class_exists('\\Psr\\Log\\LogLevel', true);
@@ -65,8 +64,8 @@ class ErrorHandler
if ($errorLevelMap !== false) {
$handler->registerErrorHandler($errorLevelMap);
}
- if ($exceptionLevel !== false) {
- $handler->registerExceptionHandler($exceptionLevel);
+ if ($exceptionLevelMap !== false) {
+ $handler->registerExceptionHandler($exceptionLevelMap);
}
if ($fatalLevel !== false) {
$handler->registerFatalHandler($fatalLevel);
@@ -75,38 +74,57 @@ class ErrorHandler
return $handler;
}
- public function registerExceptionHandler($level = null, $callPrevious = true)
+ public function registerExceptionHandler($levelMap = [], $callPrevious = true): self
{
- $prev = set_exception_handler(array($this, 'handleException'));
- $this->uncaughtExceptionLevel = $level;
+ $prev = set_exception_handler([$this, 'handleException']);
+ $this->uncaughtExceptionLevelMap = $levelMap;
+ foreach ($this->defaultExceptionLevelMap() as $class => $level) {
+ if (!isset($this->uncaughtExceptionLevelMap[$class])) {
+ $this->uncaughtExceptionLevelMap[$class] = $level;
+ }
+ }
if ($callPrevious && $prev) {
$this->previousExceptionHandler = $prev;
}
+
+ return $this;
}
- public function registerErrorHandler(array $levelMap = array(), $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true)
+ public function registerErrorHandler(array $levelMap = [], $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true): self
{
- $prev = set_error_handler(array($this, 'handleError'), $errorTypes);
+ $prev = set_error_handler([$this, 'handleError'], $errorTypes);
$this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
if ($callPrevious) {
$this->previousErrorHandler = $prev ?: true;
}
$this->handleOnlyReportedErrors = $handleOnlyReportedErrors;
+
+ return $this;
}
- public function registerFatalHandler($level = null, $reservedMemorySize = 20)
+ public function registerFatalHandler($level = null, $reservedMemorySize = 20): self
{
- register_shutdown_function(array($this, 'handleFatalError'));
+ register_shutdown_function([$this, 'handleFatalError']);
$this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
$this->fatalLevel = $level;
$this->hasFatalErrorHandler = true;
+
+ return $this;
+ }
+
+ protected function defaultExceptionLevelMap(): array
+ {
+ return [
+ 'ParseError' => LogLevel::CRITICAL,
+ 'Throwable' => LogLevel::ERROR,
+ ];
}
- protected function defaultErrorLevelMap()
+ protected function defaultErrorLevelMap(): array
{
- return array(
+ return [
E_ERROR => LogLevel::CRITICAL,
E_WARNING => LogLevel::WARNING,
E_PARSE => LogLevel::ALERT,
@@ -122,7 +140,7 @@ class ErrorHandler
E_RECOVERABLE_ERROR => LogLevel::ERROR,
E_DEPRECATED => LogLevel::NOTICE,
E_USER_DEPRECATED => LogLevel::NOTICE,
- );
+ ];
}
/**
@@ -130,10 +148,18 @@ class ErrorHandler
*/
public function handleException($e)
{
+ $level = LogLevel::ERROR;
+ foreach ($this->uncaughtExceptionLevelMap as $class => $candidate) {
+ if ($e instanceof $class) {
+ $level = $candidate;
+ break;
+ }
+ }
+
$this->logger->log(
- $this->uncaughtExceptionLevel === null ? LogLevel::ERROR : $this->uncaughtExceptionLevel,
+ $level,
sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
- array('exception' => $e)
+ ['exception' => $e]
);
if ($this->previousExceptionHandler) {
@@ -146,7 +172,7 @@ class ErrorHandler
/**
* @private
*/
- public function handleError($code, $message, $file = '', $line = 0, $context = array())
+ public function handleError($code, $message, $file = '', $line = 0, $context = [])
{
if ($this->handleOnlyReportedErrors && !(error_reporting() & $code)) {
return;
@@ -154,8 +180,8 @@ class ErrorHandler
// fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries
if (!$this->hasFatalErrorHandler || !in_array($code, self::$fatalErrors, true)) {
- $level = isset($this->errorLevelMap[$code]) ? $this->errorLevelMap[$code] : LogLevel::CRITICAL;
- $this->logger->log($level, self::codeToString($code).': '.$message, array('code' => $code, 'message' => $message, 'file' => $file, 'line' => $line));
+ $level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL;
+ $this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]);
}
if ($this->previousErrorHandler === true) {
@@ -170,27 +196,25 @@ class ErrorHandler
*/
public function handleFatalError()
{
- $this->reservedMemory = null;
+ $this->reservedMemory = '';
$lastError = error_get_last();
if ($lastError && in_array($lastError['type'], self::$fatalErrors, true)) {
$this->logger->log(
$this->fatalLevel === null ? LogLevel::ALERT : $this->fatalLevel,
'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'],
- array('code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'])
+ ['code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line']]
);
if ($this->logger instanceof Logger) {
foreach ($this->logger->getHandlers() as $handler) {
- if ($handler instanceof AbstractHandler) {
- $handler->close();
- }
+ $handler->close();
}
}
}
}
- private static function codeToString($code)
+ private static function codeToString($code): string
{
switch ($code) {
case E_ERROR:
diff --git a/src/Monolog/Formatter/ChromePHPFormatter.php b/src/Monolog/Formatter/ChromePHPFormatter.php
index 9beda1e..2b4d649 100644
--- a/src/Monolog/Formatter/ChromePHPFormatter.php
+++ b/src/Monolog/Formatter/ChromePHPFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -23,7 +23,7 @@ class ChromePHPFormatter implements FormatterInterface
/**
* Translates Monolog log levels to Wildfire levels.
*/
- private $logLevels = array(
+ private $logLevels = [
Logger::DEBUG => 'log',
Logger::INFO => 'info',
Logger::NOTICE => 'info',
@@ -32,7 +32,7 @@ class ChromePHPFormatter implements FormatterInterface
Logger::CRITICAL => 'error',
Logger::ALERT => 'error',
Logger::EMERGENCY => 'error',
- );
+ ];
/**
* {@inheritdoc}
@@ -46,7 +46,7 @@ class ChromePHPFormatter implements FormatterInterface
unset($record['extra']['file'], $record['extra']['line']);
}
- $message = array('message' => $record['message']);
+ $message = ['message' => $record['message']];
if ($record['context']) {
$message['context'] = $record['context'];
}
@@ -57,17 +57,20 @@ class ChromePHPFormatter implements FormatterInterface
$message = reset($message);
}
- return array(
+ return [
$record['channel'],
$message,
$backtrace,
$this->logLevels[$record['level']],
- );
+ ];
}
+ /**
+ * {@inheritdoc}
+ */
public function formatBatch(array $records)
{
- $formatted = array();
+ $formatted = [];
foreach ($records as $record) {
$formatted[] = $this->format($record);
diff --git a/src/Monolog/Formatter/ElasticaFormatter.php b/src/Monolog/Formatter/ElasticaFormatter.php
index 4c556cf..a6354f5 100644
--- a/src/Monolog/Formatter/ElasticaFormatter.php
+++ b/src/Monolog/Formatter/ElasticaFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -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);
diff --git a/src/Monolog/Formatter/FlowdockFormatter.php b/src/Monolog/Formatter/FlowdockFormatter.php
index 5094af3..301b74b 100644
--- a/src/Monolog/Formatter/FlowdockFormatter.php
+++ b/src/Monolog/Formatter/FlowdockFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -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,13 +37,13 @@ class FlowdockFormatter implements FormatterInterface
/**
* {@inheritdoc}
*/
- public function format(array $record)
+ public function format(array $record): array
{
- $tags = array(
+ $tags = [
'#logs',
'#' . strtolower($record['level_name']),
'#' . $record['channel'],
- );
+ ];
foreach ($record['extra'] as $value) {
$tags[] = '#' . $value;
@@ -60,14 +56,14 @@ class FlowdockFormatter implements FormatterInterface
$this->getShortMessage($record['message'])
);
- $record['flowdock'] = array(
+ $record['flowdock'] = [
'source' => $this->source,
'from_address' => $this->sourceEmail,
'subject' => $subject,
'content' => $record['message'],
'tags' => $tags,
'project' => $this->source,
- );
+ ];
return $record;
}
@@ -75,9 +71,9 @@ class FlowdockFormatter implements FormatterInterface
/**
* {@inheritdoc}
*/
- public function formatBatch(array $records)
+ public function formatBatch(array $records): array
{
- $formatted = array();
+ $formatted = [];
foreach ($records as $record) {
$formatted[] = $this->format($record);
@@ -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;
diff --git a/src/Monolog/Formatter/FluentdFormatter.php b/src/Monolog/Formatter/FluentdFormatter.php
index 02632bb..a84f826 100644
--- a/src/Monolog/Formatter/FluentdFormatter.php
+++ b/src/Monolog/Formatter/FluentdFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -39,41 +39,41 @@ 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) {
$tag .= '.' . strtolower($record['level_name']);
}
- $message = array(
+ $message = [
'message' => $record['message'],
'extra' => $record['extra'],
- );
+ ];
if (!$this->levelTag) {
$message['level'] = $record['level'];
$message['level_name'] = $record['level_name'];
}
- return json_encode(array($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 = '';
foreach ($records as $record) {
diff --git a/src/Monolog/Formatter/FormatterInterface.php b/src/Monolog/Formatter/FormatterInterface.php
index b5de751..7442134 100644
--- a/src/Monolog/Formatter/FormatterInterface.php
+++ b/src/Monolog/Formatter/FormatterInterface.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
diff --git a/src/Monolog/Formatter/GelfMessageFormatter.php b/src/Monolog/Formatter/GelfMessageFormatter.php
index 2c1b0e8..4e95a6e 100644
--- a/src/Monolog/Formatter/GelfMessageFormatter.php
+++ b/src/Monolog/Formatter/GelfMessageFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -47,7 +47,7 @@ class GelfMessageFormatter extends NormalizerFormatter
/**
* Translates Monolog log levels to Graylog2 log priorities.
*/
- private $logLevels = array(
+ private $logLevels = [
Logger::DEBUG => 7,
Logger::INFO => 6,
Logger::NOTICE => 5,
@@ -56,9 +56,9 @@ class GelfMessageFormatter extends NormalizerFormatter
Logger::CRITICAL => 2,
Logger::ALERT => 1,
Logger::EMERGENCY => 0,
- );
+ ];
- public function __construct($systemName = null, $extraPrefix = null, $contextPrefix = 'ctxt_', $maxLength = null)
+ public function __construct(string $systemName = null, string $extraPrefix = null, string $contextPrefix = 'ctxt_', int $maxLength = null)
{
parent::__construct('U.u');
@@ -72,9 +72,14 @@ class GelfMessageFormatter extends NormalizerFormatter
/**
* {@inheritdoc}
*/
- public function format(array $record)
+ public function format(array $record): Message
{
- $record = parent::format($record);
+ if (isset($record['context'])) {
+ $record['context'] = parent::format($record['context']);
+ }
+ if (isset($record['extra'])) {
+ $record['extra'] = parent::format($record['extra']);
+ }
if (!isset($record['datetime'], $record['message'], $record['level'])) {
throw new \InvalidArgumentException('The record should at least contain datetime, message and level keys, '.var_export($record, true).' given');
@@ -87,7 +92,7 @@ class GelfMessageFormatter extends NormalizerFormatter
->setHost($this->systemName)
->setLevel($this->logLevels[$record['level']]);
- // message length + system name length + 200 for padding / metadata
+ // message length + system name length + 200 for padding / metadata
$len = 200 + strlen((string) $record['message']) + strlen($this->systemName);
if ($len > $this->maxLength) {
diff --git a/src/Monolog/Formatter/HtmlFormatter.php b/src/Monolog/Formatter/HtmlFormatter.php
index 3eec95f..a343b06 100644
--- a/src/Monolog/Formatter/HtmlFormatter.php
+++ b/src/Monolog/Formatter/HtmlFormatter.php
@@ -1,4 +1,5 @@
-<?php
+<?php declare(strict_types=1);
+
/*
* This file is part of the Monolog package.
*
@@ -24,7 +25,7 @@ class HtmlFormatter extends NormalizerFormatter
/**
* Translates Monolog log levels to html color priorities.
*/
- protected $logLevels = array(
+ protected $logLevels = [
Logger::DEBUG => '#cccccc',
Logger::INFO => '#468847',
Logger::NOTICE => '#3a87ad',
@@ -33,12 +34,12 @@ class HtmlFormatter extends NormalizerFormatter
Logger::CRITICAL => '#FF7708',
Logger::ALERT => '#C12A19',
Logger::EMERGENCY => '#000000',
- );
+ ];
/**
* @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);
}
@@ -51,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) {
@@ -68,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');
@@ -81,13 +82,13 @@ 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">';
$output .= $this->addRow('Message', (string) $record['message']);
- $output .= $this->addRow('Time', $record['datetime']->format($this->dateFormat));
+ $output .= $this->addRow('Time', $this->formatDate($record['datetime']));
$output .= $this->addRow('Channel', $record['channel']);
if ($record['context']) {
$embeddedTable = '<table cellspacing="1" width="100%">';
@@ -115,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) {
@@ -125,17 +126,14 @@ class HtmlFormatter extends NormalizerFormatter
return $message;
}
- protected function convertToString($data)
+ protected function convertToString($data): string
{
if (null === $data || is_scalar($data)) {
return (string) $data;
}
$data = $this->normalize($data);
- if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
- return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
- }
- return str_replace('\\/', '/', json_encode($data));
+ return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
}
diff --git a/src/Monolog/Formatter/JsonFormatter.php b/src/Monolog/Formatter/JsonFormatter.php
index 0782f14..8e2f2fd 100644
--- a/src/Monolog/Formatter/JsonFormatter.php
+++ b/src/Monolog/Formatter/JsonFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,6 @@
namespace Monolog\Formatter;
-use Exception;
use Throwable;
/**
@@ -34,11 +33,7 @@ class JsonFormatter extends NormalizerFormatter
*/
protected $includeStacktraces = false;
- /**
- * @param int $batchMode
- * @param bool $appendNewline
- */
- 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;
@@ -50,20 +45,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;
}
@@ -71,7 +62,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" : '');
}
@@ -79,7 +70,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,21 +82,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);
}
@@ -113,11 +98,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;
@@ -138,10 +120,14 @@ class JsonFormatter extends NormalizerFormatter
*
* @return mixed
*/
- protected function normalize($data)
+ protected function normalize($data, int $depth = 0)
{
+ if ($depth > 9) {
+ return 'Over 9 levels deep, aborting normalization';
+ }
+
if (is_array($data) || $data instanceof \Traversable) {
- $normalized = array();
+ $normalized = [];
$count = 1;
foreach ($data as $key => $value) {
@@ -149,14 +135,14 @@ class JsonFormatter extends NormalizerFormatter
$normalized['...'] = 'Over 1000 items, aborting normalization';
break;
}
- $normalized[$key] = $this->normalize($value);
+ $normalized[$key] = $this->normalize($value, $depth + 1);
}
return $normalized;
}
- if ($data instanceof Exception || $data instanceof Throwable) {
- return $this->normalizeException($data);
+ if ($data instanceof Throwable) {
+ return $this->normalizeException($data, $depth);
}
return $data;
@@ -165,24 +151,15 @@ class JsonFormatter extends NormalizerFormatter
/**
* Normalizes given exception with or without its own stack trace based on
* `includeStacktraces` property.
- *
- * @param Exception|Throwable $e
- *
- * @return array
*/
- protected function normalizeException($e)
+ protected function normalizeException(Throwable $e, int $depth = 0): array
{
- // TODO 2.0 only check for Throwable
- if (!$e instanceof Exception && !$e instanceof Throwable) {
- throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.get_class($e));
- }
-
- $data = array(
+ $data = [
'class' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile().':'.$e->getLine(),
- );
+ ];
if ($this->includeStacktraces) {
$trace = $e->getTrace();
@@ -200,7 +177,7 @@ class JsonFormatter extends NormalizerFormatter
}
if ($previous = $e->getPrevious()) {
- $data['previous'] = $this->normalizeException($previous);
+ $data['previous'] = $this->normalizeException($previous, $depth + 1);
}
return $data;
diff --git a/src/Monolog/Formatter/LineFormatter.php b/src/Monolog/Formatter/LineFormatter.php
index d3e209e..9d4ef1d 100644
--- a/src/Monolog/Formatter/LineFormatter.php
+++ b/src/Monolog/Formatter/LineFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -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);
@@ -76,7 +76,6 @@ class LineFormatter extends NormalizerFormatter
}
}
-
foreach ($vars['context'] as $var => $val) {
if (false !== strpos($output, '%context.'.$var.'%')) {
$output = str_replace('%context.'.$var.'%', $this->stringify($val), $output);
@@ -110,7 +109,7 @@ class LineFormatter extends NormalizerFormatter
return $output;
}
- public function formatBatch(array $records)
+ public function formatBatch(array $records): string
{
$message = '';
foreach ($records as $record) {
@@ -120,18 +119,13 @@ class LineFormatter extends NormalizerFormatter
return $message;
}
- public function stringify($value)
+ public function stringify($value): string
{
return $this->replaceNewlines($this->convertToString($value));
}
- protected function normalizeException($e)
+ protected function normalizeException(\Throwable $e, int $depth = 0): string
{
- // TODO 2.0 only check for Throwable
- if (!$e instanceof \Exception && !$e instanceof \Throwable) {
- throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.get_class($e));
- }
-
$previousText = '';
if ($previous = $e->getPrevious()) {
do {
@@ -147,7 +141,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);
@@ -157,14 +151,10 @@ class LineFormatter extends NormalizerFormatter
return (string) $data;
}
- if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
- return $this->toJson($data, true);
- }
-
- return str_replace('\\/', '/', @json_encode($data));
+ return (string) $this->toJson($data, true);
}
- protected function replaceNewlines($str)
+ protected function replaceNewlines(string $str): string
{
if ($this->allowInlineLineBreaks) {
if (0 === strpos($str, '{')) {
@@ -174,6 +164,6 @@ class LineFormatter extends NormalizerFormatter
return $str;
}
- return str_replace(array("\r\n", "\r", "\n"), ' ', $str);
+ return str_replace(["\r\n", "\r", "\n"], ' ', $str);
}
}
diff --git a/src/Monolog/Formatter/LogglyFormatter.php b/src/Monolog/Formatter/LogglyFormatter.php
index 401859b..29841aa 100644
--- a/src/Monolog/Formatter/LogglyFormatter.php
+++ b/src/Monolog/Formatter/LogglyFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -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,11 +33,11 @@ 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 \DateTime)) {
+ if (isset($record["datetime"]) && ($record["datetime"] instanceof \DateTimeInterface)) {
$record["timestamp"] = $record["datetime"]->format("Y-m-d\TH:i:s.uO");
- // TODO 2.0 unset the 'datetime' parameter, retained for BC
+ unset($record["datetime"]);
}
return parent::format($record);
diff --git a/src/Monolog/Formatter/LogmaticFormatter.php b/src/Monolog/Formatter/LogmaticFormatter.php
new file mode 100644
index 0000000..7a75e00
--- /dev/null
+++ b/src/Monolog/Formatter/LogmaticFormatter.php
@@ -0,0 +1,72 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Formatter;
+
+/**
+ * Encodes message information into JSON in a format compatible with Logmatic.
+ *
+ * @author Julien Breux <julien.breux@gmail.com>
+ */
+class LogmaticFormatter extends JsonFormatter
+{
+ const MARKERS = ["sourcecode", "php"];
+
+ /**
+ * @param string
+ */
+ protected $hostname = '';
+
+ /**
+ * @param 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;
+ }
+
+ /**
+ * Appends the 'hostname' and 'appname' parameter for indexing by Logmatic.
+ *
+ * @see http://doc.logmatic.io/docs/basics-to-send-data
+ * @see \Monolog\Formatter\JsonFormatter::format()
+ */
+ public function format(array $record): string
+ {
+ if (!empty($this->hostname)) {
+ $record["hostname"] = $this->hostname;
+ }
+ if (!empty($this->appname)) {
+ $record["appname"] = $this->appname;
+ }
+
+ $record["@marker"] = self::MARKERS;
+
+ return parent::format($record);
+ }
+}
diff --git a/src/Monolog/Formatter/LogstashFormatter.php b/src/Monolog/Formatter/LogstashFormatter.php
index 8f83bec..3cf31dd 100644
--- a/src/Monolog/Formatter/LogstashFormatter.php
+++ b/src/Monolog/Formatter/LogstashFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -15,15 +15,12 @@ namespace Monolog\Formatter;
* Serializes a log message to Logstash Event Format
*
* @see http://logstash.net/
- * @see https://github.com/logstash/logstash/blob/master/lib/logstash/event.rb
+ * @see https://github.com/elastic/logstash/blob/master/logstash-core-event/lib/logstash/event.rb
*
* @author Tim Mower <timothy.mower@gmail.com>
*/
class LogstashFormatter extends NormalizerFormatter
{
- const V0 = 0;
- const V1 = 1;
-
/**
* @var string the name of the system for the Logstash log message, used to fill the @source field
*/
@@ -45,18 +42,12 @@ class LogstashFormatter extends NormalizerFormatter
protected $contextPrefix;
/**
- * @var int logstash format version to use
- */
- protected $version;
-
- /**
* @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 $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_', $version = self::V0)
+ 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');
@@ -65,78 +56,23 @@ class LogstashFormatter extends NormalizerFormatter
$this->applicationName = $applicationName;
$this->extraPrefix = $extraPrefix;
$this->contextPrefix = $contextPrefix;
- $this->version = $version;
}
/**
* {@inheritdoc}
*/
- public function format(array $record)
+ public function format(array $record): string
{
$record = parent::format($record);
- if ($this->version === self::V1) {
- $message = $this->formatV1($record);
- } else {
- $message = $this->formatV0($record);
- }
-
- return $this->toJson($message) . "\n";
- }
-
- protected function formatV0(array $record)
- {
if (empty($record['datetime'])) {
$record['datetime'] = gmdate('c');
}
- $message = array(
- '@timestamp' => $record['datetime'],
- '@source' => $this->systemName,
- '@fields' => array(),
- );
- if (isset($record['message'])) {
- $message['@message'] = $record['message'];
- }
- if (isset($record['channel'])) {
- $message['@tags'] = array($record['channel']);
- $message['@fields']['channel'] = $record['channel'];
- }
- if (isset($record['level'])) {
- $message['@fields']['level'] = $record['level'];
- }
- if ($this->applicationName) {
- $message['@type'] = $this->applicationName;
- }
- if (isset($record['extra']['server'])) {
- $message['@source_host'] = $record['extra']['server'];
- }
- if (isset($record['extra']['url'])) {
- $message['@source_path'] = $record['extra']['url'];
- }
- if (!empty($record['extra'])) {
- foreach ($record['extra'] as $key => $val) {
- $message['@fields'][$this->extraPrefix . $key] = $val;
- }
- }
- if (!empty($record['context'])) {
- foreach ($record['context'] as $key => $val) {
- $message['@fields'][$this->contextPrefix . $key] = $val;
- }
- }
-
- return $message;
- }
-
- protected function formatV1(array $record)
- {
- if (empty($record['datetime'])) {
- $record['datetime'] = gmdate('c');
- }
- $message = array(
+ $message = [
'@timestamp' => $record['datetime'],
'@version' => 1,
'host' => $this->systemName,
- );
+ ];
if (isset($record['message'])) {
$message['message'] = $record['message'];
}
@@ -147,20 +83,19 @@ class LogstashFormatter extends NormalizerFormatter
if (isset($record['level_name'])) {
$message['level'] = $record['level_name'];
}
+ if (isset($record['level'])) {
+ $message['monolog_level'] = $record['level'];
+ }
if ($this->applicationName) {
$message['type'] = $this->applicationName;
}
if (!empty($record['extra'])) {
- foreach ($record['extra'] as $key => $val) {
- $message[$this->extraPrefix . $key] = $val;
- }
+ $message[$this->extraPrefix.'extra'] = $record['extra'];
}
if (!empty($record['context'])) {
- foreach ($record['context'] as $key => $val) {
- $message[$this->contextPrefix . $key] = $val;
- }
+ $message[$this->contextPrefix.'context'] = $record['context'];
}
- return $message;
+ return $this->toJson($message) . "\n";
}
}
diff --git a/src/Monolog/Formatter/MongoDBFormatter.php b/src/Monolog/Formatter/MongoDBFormatter.php
index eb067bb..8c40e3e 100644
--- a/src/Monolog/Formatter/MongoDBFormatter.php
+++ b/src/Monolog/Formatter/MongoDBFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,6 +11,8 @@
namespace Monolog\Formatter;
+use MongoDB\BSON\UTCDateTime;
+
/**
* Formats a record for use with the MongoDBHandler.
*
@@ -20,21 +22,24 @@ class MongoDBFormatter implements FormatterInterface
{
private $exceptionTraceAsString;
private $maxNestingLevel;
+ private $isLegacyMongoExt;
/**
* @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;
+
+ $this->isLegacyMongoExt = version_compare(phpversion('mongodb'), '1.1.9', '<=');
}
/**
* {@inheritDoc}
*/
- public function format(array $record)
+ public function format(array $record): array
{
return $this->formatArray($record);
}
@@ -42,7 +47,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);
@@ -51,13 +56,16 @@ 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) {
- if ($value instanceof \DateTime) {
+ if ($value instanceof \DateTimeInterface) {
$record[$name] = $this->formatDate($value, $nestingLevel + 1);
- } elseif ($value instanceof \Exception) {
+ } elseif ($value instanceof \Throwable) {
$record[$name] = $this->formatException($value, $nestingLevel + 1);
} elseif (is_array($value)) {
$record[$name] = $this->formatArray($value, $nestingLevel + 1);
@@ -72,7 +80,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);
@@ -80,14 +88,14 @@ class MongoDBFormatter implements FormatterInterface
return $this->formatArray($objectVars, $nestingLevel);
}
- protected function formatException(\Exception $exception, $nestingLevel)
+ protected function formatException(\Throwable $exception, int $nestingLevel)
{
- $formattedException = array(
+ $formattedException = [
'class' => get_class($exception),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(),
- );
+ ];
if ($this->exceptionTraceAsString === true) {
$formattedException['trace'] = $exception->getTraceAsString();
@@ -98,8 +106,35 @@ class MongoDBFormatter implements FormatterInterface
return $this->formatArray($formattedException, $nestingLevel);
}
- protected function formatDate(\DateTime $value, $nestingLevel)
+ protected function formatDate(\DateTimeInterface $value, int $nestingLevel): UTCDateTime
+ {
+ if ($this->isLegacyMongoExt) {
+ return $this->legacyGetMongoDbDateTime($value);
+ }
+
+ return $this->getMongoDbDateTime($value);
+ }
+
+ private function getMongoDbDateTime(\DateTimeInterface $value): UTCDateTime
+ {
+ return new UTCDateTime((int) (string) floor($value->format('U.u') * 1000));
+ }
+
+ /**
+ * This is needed to support MongoDB Driver v1.19 and below
+ *
+ * See https://github.com/mongodb/mongo-php-driver/issues/426
+ *
+ * It can probably be removed in 2.1 or later once MongoDB's 1.2 is released and widely adopted
+ */
+ private function legacyGetMongoDbDateTime(\DateTimeInterface $value): UTCDateTime
{
- return new \MongoDate($value->getTimestamp());
+ $milliseconds = floor($value->format('U.u') * 1000);
+
+ $milliseconds = (PHP_INT_SIZE == 8) //64-bit OS?
+ ? (int) $milliseconds
+ : (string) $milliseconds;
+
+ return new UTCDateTime($milliseconds);
}
}
diff --git a/src/Monolog/Formatter/NormalizerFormatter.php b/src/Monolog/Formatter/NormalizerFormatter.php
index d441488..84f644c 100644
--- a/src/Monolog/Formatter/NormalizerFormatter.php
+++ b/src/Monolog/Formatter/NormalizerFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,8 @@
namespace Monolog\Formatter;
-use Exception;
+use Throwable;
+use Monolog\DateTimeImmutable;
/**
* Normalizes incoming records to remove objects/resources so it's easier to dump to various targets
@@ -20,16 +21,16 @@ use Exception;
*/
class NormalizerFormatter implements FormatterInterface
{
- const SIMPLE_DATE = "Y-m-d H:i:s";
+ const SIMPLE_DATE = "Y-m-d\TH:i:sP";
protected $dateFormat;
/**
* @param string $dateFormat The format of the timestamp: one supported by DateTime::format
*/
- public function __construct($dateFormat = null)
+ public function __construct(string $dateFormat = null)
{
- $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
+ $this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat;
if (!function_exists('json_encode')) {
throw new \RuntimeException('PHP\'s json extension is required to use Monolog\'s NormalizerFormatter');
}
@@ -55,8 +56,16 @@ class NormalizerFormatter implements FormatterInterface
return $records;
}
- protected function normalize($data)
+ /**
+ * @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';
+ }
+
if (null === $data || is_scalar($data)) {
if (is_float($data)) {
if (is_infinite($data)) {
@@ -71,7 +80,7 @@ class NormalizerFormatter implements FormatterInterface
}
if (is_array($data)) {
- $normalized = array();
+ $normalized = [];
$count = 1;
foreach ($data as $key => $value) {
@@ -79,53 +88,56 @@ class NormalizerFormatter implements FormatterInterface
$normalized['...'] = 'Over 1000 items ('.count($data).' total), aborting normalization';
break;
}
- $normalized[$key] = $this->normalize($value);
+ $normalized[$key] = $this->normalize($value, $depth + 1);
}
return $normalized;
}
- if ($data instanceof \DateTime) {
- return $data->format($this->dateFormat);
+ if ($data instanceof \DateTimeInterface) {
+ return $this->formatDate($data);
}
if (is_object($data)) {
- // TODO 2.0 only check for Throwable
- if ($data instanceof Exception || (PHP_VERSION_ID > 70000 && $data instanceof \Throwable)) {
- return $this->normalizeException($data);
+ if ($data instanceof Throwable) {
+ return $this->normalizeException($data, $depth);
}
- // non-serializable objects that implement __toString stringified
- if (method_exists($data, '__toString') && !$data instanceof \JsonSerializable) {
+ if ($data instanceof \JsonSerializable) {
+ $value = $data->jsonSerialize();
+ } elseif (method_exists($data, '__toString')) {
$value = $data->__toString();
} else {
- // the rest is json-serialized in some way
- $value = $this->toJson($data, true);
+ // the rest is normalized by json encoding and decoding it
+ $encoded = $this->toJson($data, true);
+ if ($encoded === false) {
+ $value = 'JSON_ERROR';
+ } else {
+ $value = json_decode($encoded, true);
+ }
}
- return sprintf("[object] (%s: %s)", get_class($data), $value);
+ return [get_class($data) => $value];
}
if (is_resource($data)) {
- return sprintf('[resource] (%s)', get_resource_type($data));
+ return sprintf('[resource(%s)]', get_resource_type($data));
}
return '[unknown('.gettype($data).')]';
}
- protected function normalizeException($e)
+ /**
+ * @return array
+ */
+ protected function normalizeException(Throwable $e, int $depth = 0)
{
- // TODO 2.0 only check for Throwable
- if (!$e instanceof Exception && !$e instanceof \Throwable) {
- throw new \InvalidArgumentException('Exception/Throwable expected, got '.gettype($e).' / '.get_class($e));
- }
-
- $data = array(
+ $data = [
'class' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode(),
'file' => $e->getFile().':'.$e->getLine(),
- );
+ ];
if ($e instanceof \SoapFault) {
if (isset($e->faultcode)) {
@@ -150,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;
@@ -165,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
+ * @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) {
@@ -186,16 +197,12 @@ class NormalizerFormatter implements FormatterInterface
}
/**
- * @param mixed $data
- * @return string JSON encoded data or null on failure
+ * @param mixed $data
+ * @return string|bool JSON encoded data or false on failure
*/
private function jsonEncode($data)
{
- if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
- return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
- }
-
- return json_encode($data);
+ return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION);
}
/**
@@ -203,7 +210,7 @@ class NormalizerFormatter implements FormatterInterface
*
* If the failure is due to invalid string encoding, try to clean the
* input and encode again. If the second encoding attempt fails, the
- * inital error is not encoding related or the input can't be cleaned then
+ * initial error is not encoding related or the input can't be cleaned then
* raise a descriptive exception.
*
* @param int $code return code of json_last_error function
@@ -211,7 +218,7 @@ class NormalizerFormatter implements FormatterInterface
* @throws \RuntimeException if failure can't be corrected
* @return string JSON encoded data after error correction
*/
- private function handleJsonError($code, $data)
+ private function handleJsonError(int $code, $data): string
{
if ($code !== JSON_ERROR_UTF8) {
$this->throwEncodeError($code, $data);
@@ -220,7 +227,7 @@ class NormalizerFormatter implements FormatterInterface
if (is_string($data)) {
$this->detectAndCleanUtf8($data);
} elseif (is_array($data)) {
- array_walk_recursive($data, array($this, 'detectAndCleanUtf8'));
+ array_walk_recursive($data, [$this, 'detectAndCleanUtf8']);
} else {
$this->throwEncodeError($code, $data);
}
@@ -241,7 +248,7 @@ class NormalizerFormatter implements FormatterInterface
* @param mixed $data data that was meant to be encoded
* @throws \RuntimeException
*/
- private function throwEncodeError($code, $data)
+ private function throwEncodeError(int $code, $data)
{
switch ($code) {
case JSON_ERROR_DEPTH:
@@ -284,14 +291,27 @@ class NormalizerFormatter implements FormatterInterface
if (is_string($data) && !preg_match('//u', $data)) {
$data = preg_replace_callback(
'/[\x80-\xFF]+/',
- function ($m) { return utf8_encode($m[0]); },
+ function ($m) {
+ return utf8_encode($m[0]);
+ },
$data
);
$data = str_replace(
- array('¤', '¦', '¨', '´', '¸', '¼', '½', '¾'),
- array('€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'),
+ ['¤', '¦', '¨', '´', '¸', '¼', '½', '¾'],
+ ['€', 'Š', 'š', 'Ž', 'ž', 'Œ', 'œ', 'Ÿ'],
$data
);
}
}
+
+ protected function formatDate(\DateTimeInterface $date)
+ {
+ // in case the date format isn't custom then we defer to the custom DateTimeImmutable
+ // formatting logic, which will pick the right format based on whether useMicroseconds is on
+ if ($this->dateFormat === self::SIMPLE_DATE && $date instanceof DateTimeImmutable) {
+ return (string) $date;
+ }
+
+ return $date->format($this->dateFormat);
+ }
}
diff --git a/src/Monolog/Formatter/ScalarFormatter.php b/src/Monolog/Formatter/ScalarFormatter.php
index 5d345d5..8d560e7 100644
--- a/src/Monolog/Formatter/ScalarFormatter.php
+++ b/src/Monolog/Formatter/ScalarFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -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);
diff --git a/src/Monolog/Formatter/WildfireFormatter.php b/src/Monolog/Formatter/WildfireFormatter.php
index 654710a..c8a3bb4 100644
--- a/src/Monolog/Formatter/WildfireFormatter.php
+++ b/src/Monolog/Formatter/WildfireFormatter.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -27,7 +27,7 @@ class WildfireFormatter extends NormalizerFormatter
/**
* Translates Monolog log levels to Wildfire levels.
*/
- private $logLevels = array(
+ private $logLevels = [
Logger::DEBUG => 'LOG',
Logger::INFO => 'INFO',
Logger::NOTICE => 'INFO',
@@ -36,12 +36,12 @@ class WildfireFormatter extends NormalizerFormatter
Logger::CRITICAL => 'ERROR',
Logger::ALERT => 'ERROR',
Logger::EMERGENCY => 'ERROR',
- );
+ ];
/**
* {@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 = '';
@@ -55,7 +55,7 @@ class WildfireFormatter extends NormalizerFormatter
}
$record = $this->normalize($record);
- $message = array('message' => $record['message']);
+ $message = ['message' => $record['message']];
$handleError = false;
if ($record['context']) {
$message['context'] = $record['context'];
@@ -79,15 +79,15 @@ class WildfireFormatter extends NormalizerFormatter
}
// Create JSON object describing the appearance of the message in the console
- $json = $this->toJson(array(
- array(
+ $json = $this->toJson([
+ [
'Type' => $type,
'File' => $file,
'Line' => $line,
'Label' => $label,
- ),
+ ],
$message,
- ), $handleError);
+ ], $handleError);
// The message itself is a serialization of the above JSON object + it's length
return sprintf(
@@ -97,17 +97,23 @@ 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)
+ /**
+ * {@inheritdoc}
+ */
+ protected function normalize($data, int $depth = 0)
{
- if (is_object($data) && !$data instanceof \DateTime) {
+ if (is_object($data) && !$data instanceof \DateTimeInterface) {
return $data;
}
- return parent::normalize($data);
+ return parent::normalize($data, $depth);
}
}
diff --git a/src/Monolog/Handler/AbstractHandler.php b/src/Monolog/Handler/AbstractHandler.php
index 758a425..ea79ec9 100644
--- a/src/Monolog/Handler/AbstractHandler.php
+++ b/src/Monolog/Handler/AbstractHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,26 +12,18 @@
namespace Monolog\Handler;
use Monolog\Logger;
-use Monolog\Formatter\FormatterInterface;
-use Monolog\Formatter\LineFormatter;
/**
- * Base Handler class providing the Handler structure
+ * Base Handler class providing basic level/bubble support
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
-abstract class AbstractHandler implements HandlerInterface
+abstract class AbstractHandler extends Handler
{
protected $level = Logger::DEBUG;
protected $bubble = true;
/**
- * @var FormatterInterface
- */
- protected $formatter;
- protected $processors = array();
-
- /**
* @param int $level The minimum logging level at which this handler will be triggered
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/
@@ -44,84 +36,18 @@ abstract class AbstractHandler implements HandlerInterface
/**
* {@inheritdoc}
*/
- public function isHandling(array $record)
+ public function isHandling(array $record): bool
{
return $record['level'] >= $this->level;
}
/**
- * {@inheritdoc}
- */
- public function handleBatch(array $records)
- {
- foreach ($records as $record) {
- $this->handle($record);
- }
- }
-
- /**
- * Closes the handler.
- *
- * This will be called automatically when the object is destroyed
- */
- public function close()
- {
- }
-
- /**
- * {@inheritdoc}
- */
- public function pushProcessor($callback)
- {
- if (!is_callable($callback)) {
- throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
- }
- array_unshift($this->processors, $callback);
-
- return $this;
- }
-
- /**
- * {@inheritdoc}
- */
- public function popProcessor()
- {
- if (!$this->processors) {
- throw new \LogicException('You tried to pop from an empty processor stack.');
- }
-
- return array_shift($this->processors);
- }
-
- /**
- * {@inheritdoc}
- */
- public function setFormatter(FormatterInterface $formatter)
- {
- $this->formatter = $formatter;
-
- return $this;
- }
-
- /**
- * {@inheritdoc}
- */
- public function getFormatter()
- {
- if (!$this->formatter) {
- $this->formatter = $this->getDefaultFormatter();
- }
-
- return $this->formatter;
- }
-
- /**
* Sets minimum logging level at which this handler will be triggered.
*
* @param int|string $level Level or level name
* @return self
*/
- public function setLevel($level)
+ public function setLevel($level): self
{
$this->level = Logger::toMonologLevel($level);
@@ -133,7 +59,7 @@ abstract class AbstractHandler implements HandlerInterface
*
* @return int
*/
- public function getLevel()
+ public function getLevel(): int
{
return $this->level;
}
@@ -145,7 +71,7 @@ abstract class AbstractHandler implements HandlerInterface
* false means that bubbling is not permitted.
* @return self
*/
- public function setBubble($bubble)
+ public function setBubble(bool $bubble): self
{
$this->bubble = $bubble;
@@ -158,29 +84,8 @@ abstract class AbstractHandler implements HandlerInterface
* @return Boolean true means that this handler allows bubbling.
* false means that bubbling is not permitted.
*/
- public function getBubble()
+ public function getBubble(): bool
{
return $this->bubble;
}
-
- public function __destruct()
- {
- try {
- $this->close();
- } catch (\Exception $e) {
- // do nothing
- } catch (\Throwable $e) {
- // do nothing
- }
- }
-
- /**
- * Gets the default formatter.
- *
- * @return FormatterInterface
- */
- protected function getDefaultFormatter()
- {
- return new LineFormatter();
- }
}
diff --git a/src/Monolog/Handler/AbstractProcessingHandler.php b/src/Monolog/Handler/AbstractProcessingHandler.php
index 6f18f72..654e671 100644
--- a/src/Monolog/Handler/AbstractProcessingHandler.php
+++ b/src/Monolog/Handler/AbstractProcessingHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -19,18 +19,23 @@ namespace Monolog\Handler;
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Christophe Coevoet <stof@notk.org>
*/
-abstract class AbstractProcessingHandler extends AbstractHandler
+abstract class AbstractProcessingHandler extends AbstractHandler implements ProcessableHandlerInterface, FormattableHandlerInterface
{
+ use ProcessableHandlerTrait;
+ use FormattableHandlerTrait;
+
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
if (!$this->isHandling($record)) {
return false;
}
- $record = $this->processRecord($record);
+ if ($this->processors) {
+ $record = $this->processRecord($record);
+ }
$record['formatted'] = $this->getFormatter()->format($record);
@@ -46,21 +51,4 @@ abstract class AbstractProcessingHandler extends AbstractHandler
* @return void
*/
abstract protected function write(array $record);
-
- /**
- * Processes a record.
- *
- * @param array $record
- * @return array
- */
- protected function processRecord(array $record)
- {
- if ($this->processors) {
- foreach ($this->processors as $processor) {
- $record = call_user_func($processor, $record);
- }
- }
-
- return $record;
- }
}
diff --git a/src/Monolog/Handler/AbstractSyslogHandler.php b/src/Monolog/Handler/AbstractSyslogHandler.php
index e2b2832..d6fc41e 100644
--- a/src/Monolog/Handler/AbstractSyslogHandler.php
+++ b/src/Monolog/Handler/AbstractSyslogHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Logger;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;
/**
@@ -24,7 +25,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
/**
* Translates Monolog log levels to syslog log priorities.
*/
- protected $logLevels = array(
+ protected $logLevels = [
Logger::DEBUG => LOG_DEBUG,
Logger::INFO => LOG_INFO,
Logger::NOTICE => LOG_NOTICE,
@@ -33,12 +34,12 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
Logger::CRITICAL => LOG_CRIT,
Logger::ALERT => LOG_ALERT,
Logger::EMERGENCY => LOG_EMERG,
- );
+ ];
/**
* List of valid log facility names.
*/
- protected $facilities = array(
+ protected $facilities = [
'auth' => LOG_AUTH,
'authpriv' => LOG_AUTHPRIV,
'cron' => LOG_CRON,
@@ -50,7 +51,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
'syslog' => LOG_SYSLOG,
'user' => LOG_USER,
'uucp' => LOG_UUCP,
- );
+ ];
/**
* @param mixed $facility
@@ -82,7 +83,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
}
// convert textual description of facility to syslog constant
- if (array_key_exists(strtolower($facility), $this->facilities)) {
+ if (is_string($facility) && array_key_exists(strtolower($facility), $this->facilities)) {
$facility = $this->facilities[strtolower($facility)];
} elseif (!in_array($facility, array_values($this->facilities), true)) {
throw new \UnexpectedValueException('Unknown facility value "'.$facility.'" given');
@@ -94,7 +95,7 @@ abstract class AbstractSyslogHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter('%channel%.%level_name%: %message% %context% %extra%');
}
diff --git a/src/Monolog/Handler/AmqpHandler.php b/src/Monolog/Handler/AmqpHandler.php
index e5a46bc..6e39a11 100644
--- a/src/Monolog/Handler/AmqpHandler.php
+++ b/src/Monolog/Handler/AmqpHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Logger;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\JsonFormatter;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Channel\AMQPChannel;
@@ -31,18 +32,18 @@ class AmqpHandler extends AbstractProcessingHandler
/**
* @param AMQPExchange|AMQPChannel $exchange AMQPExchange (php AMQP ext) or PHP AMQP lib channel, ready for use
- * @param string $exchangeName
+ * @param string $exchangeName Optional exchange name, for AMQPChannel (PhpAmqpLib) only
* @param int $level
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
*/
- public function __construct($exchange, $exchangeName = 'log', $level = Logger::DEBUG, $bubble = true)
+ public function __construct($exchange, $exchangeName = null, $level = Logger::DEBUG, $bubble = true)
{
- if ($exchange instanceof AMQPExchange) {
- $exchange->setName($exchangeName);
- } elseif ($exchange instanceof AMQPChannel) {
+ if ($exchange instanceof AMQPChannel) {
$this->exchangeName = $exchangeName;
- } else {
+ } elseif (!$exchange instanceof AMQPExchange) {
throw new \InvalidArgumentException('PhpAmqpLib\Channel\AMQPChannel or AMQPExchange instance required');
+ } elseif ($exchangeName) {
+ @trigger_error('The $exchangeName parameter can only be passed when using PhpAmqpLib, if using an AMQPExchange instance configure it beforehand', E_USER_DEPRECATED);
}
$this->exchange = $exchange;
@@ -62,10 +63,10 @@ class AmqpHandler extends AbstractProcessingHandler
$data,
$routingKey,
0,
- array(
+ [
'delivery_mode' => 2,
'content_type' => 'application/json',
- )
+ ]
);
} else {
$this->exchange->basic_publish(
@@ -113,12 +114,7 @@ class AmqpHandler extends AbstractProcessingHandler
*/
protected function getRoutingKey(array $record)
{
- $routingKey = sprintf(
- '%s.%s',
- // TODO 2.0 remove substr call
- substr($record['level_name'], 0, 4),
- $record['channel']
- );
+ $routingKey = sprintf('%s.%s', $record['level_name'], $record['channel']);
return strtolower($routingKey);
}
@@ -131,17 +127,17 @@ class AmqpHandler extends AbstractProcessingHandler
{
return new AMQPMessage(
(string) $data,
- array(
+ [
'delivery_mode' => 2,
'content_type' => 'application/json',
- )
+ ]
);
}
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
}
diff --git a/src/Monolog/Handler/BrowserConsoleHandler.php b/src/Monolog/Handler/BrowserConsoleHandler.php
index b3a21bd..4879d24 100644
--- a/src/Monolog/Handler/BrowserConsoleHandler.php
+++ b/src/Monolog/Handler/BrowserConsoleHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter;
+use Monolog\Formatter\FormatterInterface;
/**
* Handler sending logs to browser's javascript console with no browser extension required
@@ -21,7 +22,7 @@ use Monolog\Formatter\LineFormatter;
class BrowserConsoleHandler extends AbstractProcessingHandler
{
protected static $initialized = false;
- protected static $records = array();
+ protected static $records = [];
/**
* {@inheritDoc}
@@ -32,7 +33,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
*
* You can do [[blue text]]{color: blue} or [[green background]]{background-color: green; color: white}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter('[[%channel%]]{macro: autolabel} [[%level_name%]]{font-weight: bold} %message%');
}
@@ -78,7 +79,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
*/
public static function reset()
{
- self::$records = array();
+ self::$records = [];
}
/**
@@ -87,7 +88,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
protected function registerShutdownFunction()
{
if (PHP_SAPI !== 'cli') {
- register_shutdown_function(array('Monolog\Handler\BrowserConsoleHandler', 'send'));
+ register_shutdown_function(['Monolog\Handler\BrowserConsoleHandler', 'send']);
}
}
@@ -132,7 +133,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function generateScript()
{
- $script = array();
+ $script = [];
foreach (self::$records as $record) {
$context = self::dump('Context', $record['context']);
$extra = self::dump('Extra', $record['extra']);
@@ -141,10 +142,10 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
$script[] = self::call_array('log', self::handleStyles($record['formatted']));
} else {
$script = array_merge($script,
- array(self::call_array('groupCollapsed', self::handleStyles($record['formatted']))),
+ [self::call_array('groupCollapsed', self::handleStyles($record['formatted']))],
$context,
$extra,
- array(self::call('groupEnd'))
+ [self::call('groupEnd')]
);
}
}
@@ -154,7 +155,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function handleStyles($formatted)
{
- $args = array(self::quote('font-weight: normal'));
+ $args = [self::quote('font-weight: normal')];
$format = '%c' . $formatted;
preg_match_all('/\[\[(.*?)\]\]\{([^}]*)\}/s', $format, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);
@@ -173,8 +174,8 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function handleCustomStyles($style, $string)
{
- static $colors = array('blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey');
- static $labels = array();
+ static $colors = ['blue', 'green', 'red', 'magenta', 'orange', 'black', 'grey'];
+ static $labels = [];
return preg_replace_callback('/macro\s*:(.*?)(?:;|$)/', function ($m) use ($string, &$colors, &$labels) {
if (trim($m[1]) === 'autolabel') {
@@ -193,7 +194,7 @@ class BrowserConsoleHandler extends AbstractProcessingHandler
private static function dump($title, array $dict)
{
- $script = array();
+ $script = [];
$dict = array_filter($dict);
if (empty($dict)) {
return $script;
diff --git a/src/Monolog/Handler/BufferHandler.php b/src/Monolog/Handler/BufferHandler.php
index 72f8953..5ce6c39 100644
--- a/src/Monolog/Handler/BufferHandler.php
+++ b/src/Monolog/Handler/BufferHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -21,13 +21,15 @@ use Monolog\Logger;
*
* @author Christophe Coevoet <stof@notk.org>
*/
-class BufferHandler extends AbstractHandler
+class BufferHandler extends AbstractHandler implements ProcessableHandlerInterface
{
+ use ProcessableHandlerTrait;
+
protected $handler;
protected $bufferSize = 0;
protected $bufferLimit;
protected $flushOnOverflow;
- protected $buffer = array();
+ protected $buffer = [];
protected $initialized = false;
/**
@@ -48,7 +50,7 @@ class BufferHandler extends AbstractHandler
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
if ($record['level'] < $this->level) {
return false;
@@ -56,7 +58,7 @@ class BufferHandler extends AbstractHandler
if (!$this->initialized) {
// __destructor() doesn't get called on Fatal errors
- register_shutdown_function(array($this, 'close'));
+ register_shutdown_function([$this, 'close']);
$this->initialized = true;
}
@@ -70,9 +72,7 @@ class BufferHandler extends AbstractHandler
}
if ($this->processors) {
- foreach ($this->processors as $processor) {
- $record = call_user_func($processor, $record);
- }
+ $record = $this->processRecord($record);
}
$this->buffer[] = $record;
@@ -112,6 +112,6 @@ class BufferHandler extends AbstractHandler
public function clear()
{
$this->bufferSize = 0;
- $this->buffer = array();
+ $this->buffer = [];
}
}
diff --git a/src/Monolog/Handler/ChromePHPHandler.php b/src/Monolog/Handler/ChromePHPHandler.php
index 785cb0c..4c6be69 100644
--- a/src/Monolog/Handler/ChromePHPHandler.php
+++ b/src/Monolog/Handler/ChromePHPHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Formatter\ChromePHPFormatter;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
/**
@@ -32,7 +33,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
* Header name
*/
const HEADER_NAME = 'X-ChromeLogger-Data';
-
+
/**
* Regular expression to detect supported browsers (matches any Chrome, or Firefox 43+)
*/
@@ -49,11 +50,11 @@ class ChromePHPHandler extends AbstractProcessingHandler
*/
protected static $overflowed = false;
- protected static $json = array(
+ protected static $json = [
'version' => self::VERSION,
- 'columns' => array('label', 'log', 'backtrace', 'type'),
- 'rows' => array(),
- );
+ 'columns' => ['label', 'log', 'backtrace', 'type'],
+ 'rows' => [],
+ ];
protected static $sendHeaders = true;
@@ -74,7 +75,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
*/
public function handleBatch(array $records)
{
- $messages = array();
+ $messages = [];
foreach ($records as $record) {
if ($record['level'] < $this->level) {
@@ -93,7 +94,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new ChromePHPFormatter();
}
@@ -131,7 +132,7 @@ class ChromePHPHandler extends AbstractProcessingHandler
return;
}
- self::$json['request_uri'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
+ self::$json['request_uri'] = $_SERVER['REQUEST_URI'] ?? '';
}
$json = @json_encode(self::$json);
@@ -139,15 +140,15 @@ class ChromePHPHandler extends AbstractProcessingHandler
if (strlen($data) > 240 * 1024) {
self::$overflowed = true;
- $record = array(
+ $record = [
'message' => 'Incomplete logs, chrome header size limit reached',
- 'context' => array(),
+ 'context' => [],
'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'monolog',
- 'datetime' => new \DateTime(),
- 'extra' => array(),
- );
+ 'datetime' => new \DateTimeImmutable(),
+ 'extra' => [],
+ ];
self::$json['rows'][count(self::$json['rows']) - 1] = $this->getFormatter()->format($record);
$json = @json_encode(self::$json);
$data = base64_encode(utf8_encode($json));
@@ -173,39 +174,13 @@ class ChromePHPHandler extends AbstractProcessingHandler
/**
* Verifies if the headers are accepted by the current user agent
- *
- * @return Boolean
*/
- protected function headersAccepted()
+ protected function headersAccepted(): bool
{
if (empty($_SERVER['HTTP_USER_AGENT'])) {
return false;
}
- return preg_match(self::USER_AGENT_REGEX, $_SERVER['HTTP_USER_AGENT']);
- }
-
- /**
- * BC getter for the sendHeaders property that has been made static
- */
- public function __get($property)
- {
- if ('sendHeaders' !== $property) {
- throw new \InvalidArgumentException('Undefined property '.$property);
- }
-
- return static::$sendHeaders;
- }
-
- /**
- * BC setter for the sendHeaders property that has been made static
- */
- public function __set($property, $value)
- {
- if ('sendHeaders' !== $property) {
- throw new \InvalidArgumentException('Undefined property '.$property);
- }
-
- static::$sendHeaders = $value;
+ return preg_match(self::USER_AGENT_REGEX, $_SERVER['HTTP_USER_AGENT']) === 1;
}
}
diff --git a/src/Monolog/Handler/CouchDBHandler.php b/src/Monolog/Handler/CouchDBHandler.php
index cc98697..e0603f3 100644
--- a/src/Monolog/Handler/CouchDBHandler.php
+++ b/src/Monolog/Handler/CouchDBHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,6 +11,7 @@
namespace Monolog\Handler;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\JsonFormatter;
use Monolog\Logger;
@@ -23,15 +24,15 @@ class CouchDBHandler extends AbstractProcessingHandler
{
private $options;
- public function __construct(array $options = array(), $level = Logger::DEBUG, $bubble = true)
+ public function __construct(array $options = [], $level = Logger::DEBUG, $bubble = true)
{
- $this->options = array_merge(array(
+ $this->options = array_merge([
'host' => 'localhost',
'port' => 5984,
'dbname' => 'logger',
'username' => null,
'password' => null,
- ), $options);
+ ], $options);
parent::__construct($level, $bubble);
}
@@ -47,17 +48,17 @@ class CouchDBHandler extends AbstractProcessingHandler
}
$url = 'http://'.$basicAuth.$this->options['host'].':'.$this->options['port'].'/'.$this->options['dbname'];
- $context = stream_context_create(array(
- 'http' => array(
+ $context = stream_context_create([
+ 'http' => [
'method' => 'POST',
'content' => $record['formatted'],
'ignore_errors' => true,
'max_redirects' => 0,
'header' => 'Content-type: application/json',
- ),
- ));
+ ],
+ ]);
- if (false === @file_get_contents($url, null, $context)) {
+ if (false === @file_get_contents($url, false, $context)) {
throw new \RuntimeException(sprintf('Could not connect to %s', $url));
}
}
@@ -65,7 +66,7 @@ class CouchDBHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
}
diff --git a/src/Monolog/Handler/CubeHandler.php b/src/Monolog/Handler/CubeHandler.php
index 96b3ca0..ab6e007 100644
--- a/src/Monolog/Handler/CubeHandler.php
+++ b/src/Monolog/Handler/CubeHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -26,7 +26,7 @@ class CubeHandler extends AbstractProcessingHandler
private $scheme;
private $host;
private $port;
- private $acceptedSchemes = array('http', 'udp');
+ private $acceptedSchemes = ['http', 'udp'];
/**
* Create a Cube handler
@@ -105,7 +105,7 @@ class CubeHandler extends AbstractProcessingHandler
{
$date = $record['datetime'];
- $data = array('time' => $date->format('Y-m-d\TH:i:s.uO'));
+ $data = ['time' => $date->format('Y-m-d\TH:i:s.uO')];
unset($record['datetime']);
if (isset($record['context']['type'])) {
@@ -141,10 +141,10 @@ class CubeHandler extends AbstractProcessingHandler
}
curl_setopt($this->httpConnection, CURLOPT_POSTFIELDS, '['.$data.']');
- curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, array(
+ curl_setopt($this->httpConnection, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen('['.$data.']'),
- ));
+ ]);
Curl\Util::execute($this->httpConnection, 5, false);
}
diff --git a/src/Monolog/Handler/Curl/Util.php b/src/Monolog/Handler/Curl/Util.php
index 48d30b3..b0bec3d 100644
--- a/src/Monolog/Handler/Curl/Util.php
+++ b/src/Monolog/Handler/Curl/Util.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,7 @@ namespace Monolog\Handler\Curl;
class Util
{
- private static $retriableErrorCodes = array(
+ private static $retriableErrorCodes = [
CURLE_COULDNT_RESOLVE_HOST,
CURLE_COULDNT_CONNECT,
CURLE_HTTP_NOT_FOUND,
@@ -21,7 +21,7 @@ class Util
CURLE_OPERATION_TIMEOUTED,
CURLE_HTTP_POST_ERROR,
CURLE_SSL_CONNECT_ERROR,
- );
+ ];
/**
* Executes a CURL request with optional retries and exception on failure
diff --git a/src/Monolog/Handler/DeduplicationHandler.php b/src/Monolog/Handler/DeduplicationHandler.php
index 7778c22..235b3b8 100644
--- a/src/Monolog/Handler/DeduplicationHandler.php
+++ b/src/Monolog/Handler/DeduplicationHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -81,7 +81,6 @@ class DeduplicationHandler extends BufferHandler
foreach ($this->buffer as $record) {
if ($record['level'] >= $this->deduplicationLevel) {
-
$passthru = $passthru || !$this->isDuplicate($record);
if ($passthru) {
$this->appendRecord($record);
@@ -139,13 +138,13 @@ class DeduplicationHandler extends BufferHandler
$handle = fopen($this->deduplicationStore, 'rw+');
flock($handle, LOCK_EX);
- $validLogs = array();
+ $validLogs = [];
$timestampValidity = time() - $this->time;
while (!feof($handle)) {
$log = fgets($handle);
- if (substr($log, 0, 10) >= $timestampValidity) {
+ if ($log && substr($log, 0, 10) >= $timestampValidity) {
$validLogs[] = $log;
}
}
diff --git a/src/Monolog/Handler/DoctrineCouchDBHandler.php b/src/Monolog/Handler/DoctrineCouchDBHandler.php
index b91ffec..13a08ee 100644
--- a/src/Monolog/Handler/DoctrineCouchDBHandler.php
+++ b/src/Monolog/Handler/DoctrineCouchDBHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,6 +13,7 @@ namespace Monolog\Handler;
use Monolog\Logger;
use Monolog\Formatter\NormalizerFormatter;
+use Monolog\Formatter\FormatterInterface;
use Doctrine\CouchDB\CouchDBClient;
/**
@@ -38,7 +39,7 @@ class DoctrineCouchDBHandler extends AbstractProcessingHandler
$this->client->postDocument($record['formatted']);
}
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new NormalizerFormatter;
}
diff --git a/src/Monolog/Handler/DynamoDbHandler.php b/src/Monolog/Handler/DynamoDbHandler.php
index 237b71f..a6991fa 100644
--- a/src/Monolog/Handler/DynamoDbHandler.php
+++ b/src/Monolog/Handler/DynamoDbHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,6 +13,7 @@ namespace Monolog\Handler;
use Aws\Sdk;
use Aws\DynamoDb\DynamoDbClient;
+use Monolog\Formatter\FormatterInterface;
use Aws\DynamoDb\Marshaler;
use Monolog\Formatter\ScalarFormatter;
use Monolog\Logger;
@@ -80,10 +81,10 @@ class DynamoDbHandler extends AbstractProcessingHandler
$formatted = $this->client->formatAttributes($filtered);
}
- $this->client->putItem(array(
+ $this->client->putItem([
'TableName' => $this->table,
'Item' => $formatted,
- ));
+ ]);
}
/**
@@ -100,7 +101,7 @@ class DynamoDbHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new ScalarFormatter(self::DATE_FORMAT);
}
diff --git a/src/Monolog/Handler/ElasticSearchHandler.php b/src/Monolog/Handler/ElasticSearchHandler.php
index 8196740..fbb999f 100644
--- a/src/Monolog/Handler/ElasticSearchHandler.php
+++ b/src/Monolog/Handler/ElasticSearchHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -43,7 +43,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
/**
* @var array Handler config options
*/
- protected $options = array();
+ protected $options = [];
/**
* @param Client $client Elastica Client object
@@ -51,16 +51,16 @@ class ElasticSearchHandler extends AbstractProcessingHandler
* @param int $level The minimum logging level at which this handler will be triggered
* @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/
- public function __construct(Client $client, array $options = array(), $level = Logger::DEBUG, $bubble = true)
+ public function __construct(Client $client, array $options = [], $level = Logger::DEBUG, $bubble = true)
{
parent::__construct($level, $bubble);
$this->client = $client;
$this->options = array_merge(
- array(
+ [
'index' => 'monolog', // Elastic index name
'type' => 'record', // Elastic document type
'ignore_error' => false, // Suppress Elastica exceptions
- ),
+ ],
$options
);
}
@@ -70,13 +70,13 @@ class ElasticSearchHandler extends AbstractProcessingHandler
*/
protected function write(array $record)
{
- $this->bulkSend(array($record['formatted']));
+ $this->bulkSend([$record['formatted']]);
}
/**
* {@inheritdoc}
*/
- public function setFormatter(FormatterInterface $formatter)
+ public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
if ($formatter instanceof ElasticaFormatter) {
return parent::setFormatter($formatter);
@@ -96,7 +96,7 @@ class ElasticSearchHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new ElasticaFormatter($this->options['index'], $this->options['type']);
}
diff --git a/src/Monolog/Handler/ErrorLogHandler.php b/src/Monolog/Handler/ErrorLogHandler.php
index 1447a58..2c80139 100644
--- a/src/Monolog/Handler/ErrorLogHandler.php
+++ b/src/Monolog/Handler/ErrorLogHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
/**
@@ -51,16 +52,16 @@ class ErrorLogHandler extends AbstractProcessingHandler
*/
public static function getAvailableTypes()
{
- return array(
+ return [
self::OPERATING_SYSTEM,
self::SAPI,
- );
+ ];
}
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter('[%datetime%] %channel%.%level_name%: %message% %context% %extra%');
}
@@ -70,13 +71,14 @@ class ErrorLogHandler extends AbstractProcessingHandler
*/
protected function write(array $record)
{
- if ($this->expandNewlines) {
- $lines = preg_split('{[\r\n]+}', (string) $record['formatted']);
- foreach ($lines as $line) {
- error_log($line, $this->messageType);
- }
- } else {
+ if (!$this->expandNewlines) {
error_log((string) $record['formatted'], $this->messageType);
+ return;
+ }
+
+ $lines = preg_split('{[\r\n]+}', (string) $record['formatted']);
+ foreach ($lines as $line) {
+ error_log($line, $this->messageType);
}
}
}
diff --git a/src/Monolog/Handler/FilterHandler.php b/src/Monolog/Handler/FilterHandler.php
index 2a0f7fd..da0634a 100644
--- a/src/Monolog/Handler/FilterHandler.php
+++ b/src/Monolog/Handler/FilterHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -21,8 +21,10 @@ use Monolog\Logger;
* @author Hennadiy Verkh
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
-class FilterHandler extends AbstractHandler
+class FilterHandler extends Handler implements ProcessableHandlerInterface
{
+ use ProcessableHandlerTrait;
+
/**
* Handler or factory callable($record, $this)
*
@@ -64,7 +66,7 @@ class FilterHandler extends AbstractHandler
/**
* @return array
*/
- public function getAcceptedLevels()
+ public function getAcceptedLevels(): array
{
return array_flip($this->acceptedLevels);
}
@@ -90,7 +92,7 @@ class FilterHandler extends AbstractHandler
/**
* {@inheritdoc}
*/
- public function isHandling(array $record)
+ public function isHandling(array $record): bool
{
return isset($this->acceptedLevels[$record['level']]);
}
@@ -98,7 +100,7 @@ class FilterHandler extends AbstractHandler
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
if (!$this->isHandling($record)) {
return false;
@@ -113,9 +115,7 @@ class FilterHandler extends AbstractHandler
}
if ($this->processors) {
- foreach ($this->processors as $processor) {
- $record = call_user_func($processor, $record);
- }
+ $record = $this->processRecord($record);
}
$this->handler->handle($record);
@@ -128,7 +128,7 @@ class FilterHandler extends AbstractHandler
*/
public function handleBatch(array $records)
{
- $filtered = array();
+ $filtered = [];
foreach ($records as $record) {
if ($this->isHandling($record)) {
$filtered[] = $record;
diff --git a/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php b/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php
index c3e42ef..f9cab61 100644
--- a/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php
+++ b/src/Monolog/Handler/FingersCrossed/ActivationStrategyInterface.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
diff --git a/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php b/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php
index 2a2a64d..63a14cb 100644
--- a/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php
+++ b/src/Monolog/Handler/FingersCrossed/ChannelLevelActivationStrategy.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -42,7 +42,7 @@ class ChannelLevelActivationStrategy implements ActivationStrategyInterface
* @param int $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, $channelToActionLevel = array())
+ public function __construct($defaultActionLevel, $channelToActionLevel = [])
{
$this->defaultActionLevel = Logger::toMonologLevel($defaultActionLevel);
$this->channelToActionLevel = array_map('Monolog\Logger::toMonologLevel', $channelToActionLevel);
diff --git a/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php b/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php
index 6e63085..d0ebd84 100644
--- a/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php
+++ b/src/Monolog/Handler/FingersCrossed/ErrorLevelActivationStrategy.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
diff --git a/src/Monolog/Handler/FingersCrossedHandler.php b/src/Monolog/Handler/FingersCrossedHandler.php
index d1dcaac..f0151d1 100644
--- a/src/Monolog/Handler/FingersCrossedHandler.php
+++ b/src/Monolog/Handler/FingersCrossedHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -27,13 +27,15 @@ use Monolog\Logger;
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
-class FingersCrossedHandler extends AbstractHandler
+class FingersCrossedHandler extends Handler implements ProcessableHandlerInterface
{
+ use ProcessableHandlerTrait;
+
protected $handler;
protected $activationStrategy;
protected $buffering = true;
protected $bufferSize;
- protected $buffer = array();
+ protected $buffer = [];
protected $stopBuffering;
protected $passthruLevel;
@@ -74,7 +76,7 @@ class FingersCrossedHandler extends AbstractHandler
/**
* {@inheritdoc}
*/
- public function isHandling(array $record)
+ public function isHandling(array $record): bool
{
return true;
}
@@ -96,18 +98,16 @@ class FingersCrossedHandler extends AbstractHandler
}
}
$this->handler->handleBatch($this->buffer);
- $this->buffer = array();
+ $this->buffer = [];
}
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
if ($this->processors) {
- foreach ($this->processors as $processor) {
- $record = call_user_func($processor, $record);
- }
+ $record = $this->processRecord($record);
}
if ($this->buffering) {
@@ -137,7 +137,7 @@ class FingersCrossedHandler extends AbstractHandler
});
if (count($this->buffer) > 0) {
$this->handler->handleBatch($this->buffer);
- $this->buffer = array();
+ $this->buffer = [];
}
}
}
@@ -157,7 +157,7 @@ class FingersCrossedHandler extends AbstractHandler
*/
public function clear()
{
- $this->buffer = array();
+ $this->buffer = [];
$this->reset();
}
}
diff --git a/src/Monolog/Handler/FirePHPHandler.php b/src/Monolog/Handler/FirePHPHandler.php
index fee4795..ac7230c 100644
--- a/src/Monolog/Handler/FirePHPHandler.php
+++ b/src/Monolog/Handler/FirePHPHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Formatter\WildfireFormatter;
+use Monolog\Formatter\FormatterInterface;
/**
* Simple FirePHP Handler (http://www.firephp.org/), which uses the Wildfire protocol.
@@ -60,26 +61,24 @@ class FirePHPHandler extends AbstractProcessingHandler
* @param string $message Log message
* @return array Complete header string ready for the client as key and message as value
*/
- protected function createHeader(array $meta, $message)
+ protected function createHeader(array $meta, string $message): array
{
$header = sprintf('%s-%s', self::HEADER_PREFIX, join('-', $meta));
- return array($header => $message);
+ return [$header => $message];
}
/**
* Creates message header from record
*
* @see createHeader()
- * @param array $record
- * @return string
*/
- protected function createRecordHeader(array $record)
+ protected function createRecordHeader(array $record): array
{
// Wildfire is extensible to support multiple protocols & plugins in a single request,
// but we're not taking advantage of that (yet), so we're using "1" for simplicity's sake.
return $this->createHeader(
- array(1, 1, 1, self::$messageIndex++),
+ [1, 1, 1, self::$messageIndex++],
$record['formatted']
);
}
@@ -87,7 +86,7 @@ class FirePHPHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new WildfireFormatter();
}
@@ -103,9 +102,9 @@ class FirePHPHandler extends AbstractProcessingHandler
{
// Initial payload consists of required headers for Wildfire
return array_merge(
- $this->createHeader(array('Protocol', 1), self::PROTOCOL_URI),
- $this->createHeader(array(1, 'Structure', 1), self::STRUCTURE_URI),
- $this->createHeader(array(1, 'Plugin', 1), self::PLUGIN_URI)
+ $this->createHeader(['Protocol', 1], self::PROTOCOL_URI),
+ $this->createHeader([1, 'Structure', 1], self::STRUCTURE_URI),
+ $this->createHeader([1, 'Plugin', 1], self::PLUGIN_URI)
);
}
@@ -168,28 +167,4 @@ class FirePHPHandler extends AbstractProcessingHandler
return isset($_SERVER['HTTP_X_FIREPHP_VERSION']);
}
-
- /**
- * BC getter for the sendHeaders property that has been made static
- */
- public function __get($property)
- {
- if ('sendHeaders' !== $property) {
- throw new \InvalidArgumentException('Undefined property '.$property);
- }
-
- return static::$sendHeaders;
- }
-
- /**
- * BC setter for the sendHeaders property that has been made static
- */
- public function __set($property, $value)
- {
- if ('sendHeaders' !== $property) {
- throw new \InvalidArgumentException('Undefined property '.$property);
- }
-
- static::$sendHeaders = $value;
- }
}
diff --git a/src/Monolog/Handler/FleepHookHandler.php b/src/Monolog/Handler/FleepHookHandler.php
index c43c013..748100b 100644
--- a/src/Monolog/Handler/FleepHookHandler.php
+++ b/src/Monolog/Handler/FleepHookHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,6 +11,7 @@
namespace Monolog\Handler;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LineFormatter;
use Monolog\Logger;
@@ -63,7 +64,7 @@ class FleepHookHandler extends SocketHandler
*
* @return LineFormatter
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter(null, null, true, true);
}
@@ -117,9 +118,9 @@ class FleepHookHandler extends SocketHandler
*/
private function buildContent($record)
{
- $dataArray = array(
+ $dataArray = [
'message' => $record['formatted'],
- );
+ ];
return http_build_query($dataArray);
}
diff --git a/src/Monolog/Handler/FlowdockHandler.php b/src/Monolog/Handler/FlowdockHandler.php
index dd9a361..67d1291 100644
--- a/src/Monolog/Handler/FlowdockHandler.php
+++ b/src/Monolog/Handler/FlowdockHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -53,7 +53,7 @@ class FlowdockHandler extends SocketHandler
/**
* {@inheritdoc}
*/
- public function setFormatter(FormatterInterface $formatter)
+ public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
if (!$formatter instanceof FlowdockFormatter) {
throw new \InvalidArgumentException('The FlowdockHandler requires an instance of Monolog\Formatter\FlowdockFormatter to function correctly');
@@ -65,9 +65,9 @@ class FlowdockHandler extends SocketHandler
/**
* Gets the default formatter.
*
- * @return FormatterInterface
+ * @suppress PhanTypeMissingReturn
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
throw new \InvalidArgumentException('The FlowdockHandler must be configured (via setFormatter) with an instance of Monolog\Formatter\FlowdockFormatter to function correctly');
}
diff --git a/src/Monolog/Handler/FormattableHandlerInterface.php b/src/Monolog/Handler/FormattableHandlerInterface.php
new file mode 100644
index 0000000..fc1693c
--- /dev/null
+++ b/src/Monolog/Handler/FormattableHandlerInterface.php
@@ -0,0 +1,37 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Monolog\Formatter\FormatterInterface;
+
+/**
+ * Interface to describe loggers that have a formatter
+ *
+ * @author Jordi Boggiano <j.boggiano@seld.be>
+ */
+interface FormattableHandlerInterface
+{
+ /**
+ * Sets the formatter.
+ *
+ * @param FormatterInterface $formatter
+ * @return HandlerInterface self
+ */
+ public function setFormatter(FormatterInterface $formatter): HandlerInterface;
+
+ /**
+ * Gets the formatter.
+ *
+ * @return FormatterInterface
+ */
+ public function getFormatter(): FormatterInterface;
+}
diff --git a/src/Monolog/Handler/FormattableHandlerTrait.php b/src/Monolog/Handler/FormattableHandlerTrait.php
new file mode 100644
index 0000000..2b7e56f
--- /dev/null
+++ b/src/Monolog/Handler/FormattableHandlerTrait.php
@@ -0,0 +1,60 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Monolog\Formatter\FormatterInterface;
+use Monolog\Formatter\LineFormatter;
+
+/**
+ * Helper trait for implementing FormattableInterface
+ *
+ * @author Jordi Boggiano <j.boggiano@seld.be>
+ */
+trait FormattableHandlerTrait
+{
+ /**
+ * @var FormatterInterface
+ */
+ protected $formatter;
+
+ /**
+ * {@inheritdoc}
+ */
+ public function setFormatter(FormatterInterface $formatter): HandlerInterface
+ {
+ $this->formatter = $formatter;
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function getFormatter(): FormatterInterface
+ {
+ if (!$this->formatter) {
+ $this->formatter = $this->getDefaultFormatter();
+ }
+
+ return $this->formatter;
+ }
+
+ /**
+ * Gets the default formatter.
+ *
+ * @return FormatterInterface
+ */
+ protected function getDefaultFormatter(): FormatterInterface
+ {
+ return new LineFormatter();
+ }
+}
diff --git a/src/Monolog/Handler/GelfHandler.php b/src/Monolog/Handler/GelfHandler.php
index d3847d8..b5c3a8c 100644
--- a/src/Monolog/Handler/GelfHandler.php
+++ b/src/Monolog/Handler/GelfHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,12 +11,10 @@
namespace Monolog\Handler;
-use Gelf\IMessagePublisher;
use Gelf\PublisherInterface;
-use Gelf\Publisher;
-use InvalidArgumentException;
use Monolog\Logger;
use Monolog\Formatter\GelfMessageFormatter;
+use Monolog\Formatter\FormatterInterface;
/**
* Handler to send messages to a Graylog2 (http://www.graylog2.org) server
@@ -27,23 +25,19 @@ use Monolog\Formatter\GelfMessageFormatter;
class GelfHandler extends AbstractProcessingHandler
{
/**
- * @var Publisher the publisher object that sends the message to the server
+ * @var PublisherInterface|null the publisher object that sends the message to the server
*/
protected $publisher;
/**
- * @param PublisherInterface|IMessagePublisher|Publisher $publisher a publisher object
- * @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 PublisherInterface $publisher a publisher object
+ * @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($publisher, $level = Logger::DEBUG, $bubble = true)
+ public function __construct(PublisherInterface $publisher, $level = Logger::DEBUG, $bubble = true)
{
parent::__construct($level, $bubble);
- if (!$publisher instanceof Publisher && !$publisher instanceof IMessagePublisher && !$publisher instanceof PublisherInterface) {
- throw new InvalidArgumentException('Invalid publisher, expected a Gelf\Publisher, Gelf\IMessagePublisher or Gelf\PublisherInterface instance');
- }
-
$this->publisher = $publisher;
}
@@ -66,7 +60,7 @@ class GelfHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new GelfMessageFormatter();
}
diff --git a/src/Monolog/Handler/GroupHandler.php b/src/Monolog/Handler/GroupHandler.php
index 663f5a9..ef1485f 100644
--- a/src/Monolog/Handler/GroupHandler.php
+++ b/src/Monolog/Handler/GroupHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -18,8 +18,10 @@ use Monolog\Formatter\FormatterInterface;
*
* @author Lenar Lõhmus <lenar@city.ee>
*/
-class GroupHandler extends AbstractHandler
+class GroupHandler extends Handler implements ProcessableHandlerInterface
{
+ use ProcessableHandlerTrait;
+
protected $handlers;
/**
@@ -41,7 +43,7 @@ class GroupHandler extends AbstractHandler
/**
* {@inheritdoc}
*/
- public function isHandling(array $record)
+ public function isHandling(array $record): bool
{
foreach ($this->handlers as $handler) {
if ($handler->isHandling($record)) {
@@ -55,12 +57,10 @@ class GroupHandler extends AbstractHandler
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
if ($this->processors) {
- foreach ($this->processors as $processor) {
- $record = call_user_func($processor, $record);
- }
+ $record = $this->processRecord($record);
}
foreach ($this->handlers as $handler) {
@@ -76,7 +76,7 @@ class GroupHandler extends AbstractHandler
public function handleBatch(array $records)
{
if ($this->processors) {
- $processed = array();
+ $processed = [];
foreach ($records as $record) {
foreach ($this->processors as $processor) {
$processed[] = call_user_func($processor, $record);
diff --git a/src/Monolog/Handler/Handler.php b/src/Monolog/Handler/Handler.php
new file mode 100644
index 0000000..347e7b7
--- /dev/null
+++ b/src/Monolog/Handler/Handler.php
@@ -0,0 +1,53 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+/**
+ * Base Handler class providing basic close() support as well as handleBatch
+ *
+ * @author Jordi Boggiano <j.boggiano@seld.be>
+ */
+abstract class Handler implements HandlerInterface
+{
+ /**
+ * {@inheritdoc}
+ */
+ public function handleBatch(array $records)
+ {
+ foreach ($records as $record) {
+ $this->handle($record);
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function close()
+ {
+ }
+
+ public function __destruct()
+ {
+ try {
+ $this->close();
+ } catch (\Throwable $e) {
+ // do nothing
+ }
+ }
+
+ public function __sleep()
+ {
+ $this->close();
+
+ return array_keys(get_object_vars($this));
+ }
+}
diff --git a/src/Monolog/Handler/HandlerInterface.php b/src/Monolog/Handler/HandlerInterface.php
index d920c4b..472fd31 100644
--- a/src/Monolog/Handler/HandlerInterface.php
+++ b/src/Monolog/Handler/HandlerInterface.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,8 +11,6 @@
namespace Monolog\Handler;
-use Monolog\Formatter\FormatterInterface;
-
/**
* Interface that all Monolog Handlers must implement
*
@@ -33,7 +31,7 @@ interface HandlerInterface
*
* @return Boolean
*/
- public function isHandling(array $record);
+ public function isHandling(array $record): bool;
/**
* Handles a record.
@@ -49,7 +47,7 @@ interface HandlerInterface
* @return Boolean true means that this handler handled the record, and that bubbling is not permitted.
* false means the record was either not processed or that this handler allows bubbling.
*/
- public function handle(array $record);
+ public function handle(array $record): bool;
/**
* Handles a set of records at once.
@@ -59,32 +57,12 @@ interface HandlerInterface
public function handleBatch(array $records);
/**
- * Adds a processor in the stack.
- *
- * @param callable $callback
- * @return self
- */
- public function pushProcessor($callback);
-
- /**
- * Removes the processor on top of the stack and returns it.
- *
- * @return callable
- */
- public function popProcessor();
-
- /**
- * Sets the formatter.
+ * Closes the handler.
*
- * @param FormatterInterface $formatter
- * @return self
- */
- public function setFormatter(FormatterInterface $formatter);
-
- /**
- * Gets the formatter.
+ * This will be called automatically when the object is destroyed if you extend Monolog\Handler\Handler
*
- * @return FormatterInterface
+ * 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 getFormatter();
+ public function close();
}
diff --git a/src/Monolog/Handler/HandlerWrapper.php b/src/Monolog/Handler/HandlerWrapper.php
index e540d80..28fe57d 100644
--- a/src/Monolog/Handler/HandlerWrapper.php
+++ b/src/Monolog/Handler/HandlerWrapper.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -30,7 +30,7 @@ use Monolog\Formatter\FormatterInterface;
*
* @author Alexey Karapetov <alexey@karapetov.com>
*/
-class HandlerWrapper implements HandlerInterface
+class HandlerWrapper implements HandlerInterface, ProcessableHandlerInterface, FormattableHandlerInterface
{
/**
* @var HandlerInterface
@@ -49,7 +49,7 @@ class HandlerWrapper implements HandlerInterface
/**
* {@inheritdoc}
*/
- public function isHandling(array $record)
+ public function isHandling(array $record): bool
{
return $this->handler->isHandling($record);
}
@@ -57,7 +57,7 @@ class HandlerWrapper implements HandlerInterface
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
return $this->handler->handle($record);
}
@@ -73,36 +73,58 @@ class HandlerWrapper implements HandlerInterface
/**
* {@inheritdoc}
*/
- public function pushProcessor($callback)
+ public function close()
{
- $this->handler->pushProcessor($callback);
+ return $this->handler->close();
+ }
- return $this;
+ /**
+ * {@inheritdoc}
+ */
+ public function pushProcessor(callable $callback): HandlerInterface
+ {
+ if ($this->handler instanceof ProcessableHandlerInterface) {
+ $this->handler->pushProcessor($callback);
+
+ return $this;
+ }
+
+ throw new \LogicException('The wrapped handler does not implement ' . ProcessableHandlerInterface::class);
}
/**
* {@inheritdoc}
*/
- public function popProcessor()
+ public function popProcessor(): callable
{
- return $this->handler->popProcessor();
+ if ($this->handler instanceof ProcessableHandlerInterface) {
+ return $this->handler->popProcessor();
+ }
+
+ throw new \LogicException('The wrapped handler does not implement ' . ProcessableHandlerInterface::class);
}
/**
* {@inheritdoc}
*/
- public function setFormatter(FormatterInterface $formatter)
+ public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
- $this->handler->setFormatter($formatter);
+ if ($this->handler instanceof FormattableHandlerInterface) {
+ $this->handler->setFormatter($formatter);
+ }
- return $this;
+ throw new \LogicException('The wrapped handler does not implement ' . FormattableHandlerInterface::class);
}
/**
* {@inheritdoc}
*/
- public function getFormatter()
+ public function getFormatter(): FormatterInterface
{
- return $this->handler->getFormatter();
+ if ($this->handler instanceof FormattableHandlerInterface) {
+ return $this->handler->getFormatter($formatter);
+ }
+
+ throw new \LogicException('The wrapped handler does not implement ' . FormattableHandlerInterface::class);
}
}
diff --git a/src/Monolog/Handler/HipChatHandler.php b/src/Monolog/Handler/HipChatHandler.php
index 73049f3..98441f3 100644
--- a/src/Monolog/Handler/HipChatHandler.php
+++ b/src/Monolog/Handler/HipChatHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -16,12 +16,13 @@ use Monolog\Logger;
/**
* Sends notifications through the hipchat api to a hipchat room
*
+ * This handler only supports the API v2
+ *
* Notes:
* API token - HipChat API token
* Room - HipChat Room Id or name, where messages are sent
* Name - Name used to send the message (from)
* notify - Should the message trigger a notification in the clients
- * version - The API version to use (HipChatHandler::API_V1 | HipChatHandler::API_V2)
*
* @author Rafael Dohms <rafael@doh.ms>
* @see https://www.hipchat.com/docs/api
@@ -29,16 +30,6 @@ use Monolog\Logger;
class HipChatHandler extends SocketHandler
{
/**
- * Use API version 1
- */
- const API_V1 = 'v1';
-
- /**
- * Use API version v2
- */
- const API_V2 = 'v2';
-
- /**
* The maximum allowed length for the name used in the "from" field.
*/
const MAXIMUM_NAME_LENGTH = 15;
@@ -79,28 +70,18 @@ class HipChatHandler extends SocketHandler
private $host;
/**
- * @var string
+ * @param string $token HipChat API Token
+ * @param string $room The room that should be alerted of the message (Id or Name)
+ * @param string $name Name used in the "from" field.
+ * @param bool $notify Trigger a notification in clients or not
+ * @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 bool $useSSL Whether to connect via SSL.
+ * @param string $format The format of the messages (default to text, can be set to html if you have html in the messages)
+ * @param string $host The HipChat server hostname.
*/
- private $version;
-
- /**
- * @param string $token HipChat API Token
- * @param string $room The room that should be alerted of the message (Id or Name)
- * @param string $name Name used in the "from" field.
- * @param bool $notify Trigger a notification in clients or not
- * @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 bool $useSSL Whether to connect via SSL.
- * @param string $format The format of the messages (default to text, can be set to html if you have html in the messages)
- * @param string $host The HipChat server hostname.
- * @param string $version The HipChat API version (default HipChatHandler::API_V1)
- */
- public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com', $version = self::API_V1)
+ public function __construct($token, $room, $name = 'Monolog', $notify = false, $level = Logger::CRITICAL, $bubble = true, $useSSL = true, $format = 'text', $host = 'api.hipchat.com')
{
- if ($version == self::API_V1 && !$this->validateStringLength($name, static::MAXIMUM_NAME_LENGTH)) {
- throw new \InvalidArgumentException('The supplied name is too long. HipChat\'s v1 API supports names up to 15 UTF-8 characters.');
- }
-
$connectionString = $useSSL ? 'ssl://'.$host.':443' : $host.':80';
parent::__construct($connectionString, $level, $bubble);
@@ -110,7 +91,6 @@ class HipChatHandler extends SocketHandler
$this->room = $room;
$this->format = $format;
$this->host = $host;
- $this->version = $version;
}
/**
@@ -134,14 +114,12 @@ class HipChatHandler extends SocketHandler
*/
private function buildContent($record)
{
- $dataArray = array(
- 'notify' => $this->version == self::API_V1 ?
- ($this->notify ? 1 : 0) :
- ($this->notify ? 'true' : 'false'),
+ $dataArray = [
+ 'notify' => $this->notify ? 'true' : 'false',
'message' => $record['formatted'],
'message_format' => $this->format,
'color' => $this->getAlertColor($record['level']),
- );
+ ];
if (!$this->validateStringLength($dataArray['message'], static::MAXIMUM_MESSAGE_LENGTH)) {
if (function_exists('mb_substr')) {
@@ -151,14 +129,9 @@ class HipChatHandler extends SocketHandler
}
}
- // if we are using the legacy API then we need to send some additional information
- if ($this->version == self::API_V1) {
- $dataArray['room_id'] = $this->room;
- }
-
// append the sender name if it is set
// always append it if we use the v1 api (it is required in v1)
- if ($this->version == self::API_V1 || $this->name !== null) {
+ if ($this->name !== null) {
$dataArray['from'] = (string) $this->name;
}
@@ -173,13 +146,9 @@ class HipChatHandler extends SocketHandler
*/
private function buildHeader($content)
{
- if ($this->version == self::API_V1) {
- $header = "POST /v1/rooms/message?format=json&auth_token={$this->token} HTTP/1.1\r\n";
- } else {
- // needed for rooms with special (spaces, etc) characters in the name
- $room = rawurlencode($this->room);
- $header = "POST /v2/room/{$room}/notification?auth_token={$this->token} HTTP/1.1\r\n";
- }
+ // needed for rooms with special (spaces, etc) characters in the name
+ $room = rawurlencode($this->room);
+ $header = "POST /v2/room/{$room}/notification?auth_token={$this->token} HTTP/1.1\r\n";
$header .= "Host: {$this->host}\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
@@ -259,9 +228,9 @@ class HipChatHandler extends SocketHandler
private function combineRecords($records)
{
$batchRecord = null;
- $batchRecords = array();
- $messages = array();
- $formattedMessages = array();
+ $batchRecords = [];
+ $messages = [];
+ $formattedMessages = [];
$level = 0;
$levelName = null;
$datetime = null;
@@ -283,12 +252,12 @@ class HipChatHandler extends SocketHandler
$formattedMessages[] = $this->getFormatter()->format($record);
$formattedMessageStr = implode('', $formattedMessages);
- $batchRecord = array(
+ $batchRecord = [
'message' => $messageStr,
'formatted' => $formattedMessageStr,
- 'context' => array(),
- 'extra' => array(),
- );
+ 'context' => [],
+ 'extra' => [],
+ ];
if (!$this->validateStringLength($batchRecord['formatted'], static::MAXIMUM_MESSAGE_LENGTH)) {
// Pop the last message and implode the remaining messages
@@ -298,8 +267,8 @@ class HipChatHandler extends SocketHandler
$batchRecord['formatted'] = implode('', $formattedMessages);
$batchRecords[] = $batchRecord;
- $messages = array($lastMessage);
- $formattedMessages = array($lastFormattedMessage);
+ $messages = [$lastMessage];
+ $formattedMessages = [$lastFormattedMessage];
$batchRecord = null;
}
@@ -313,11 +282,11 @@ class HipChatHandler extends SocketHandler
foreach ($batchRecords as &$batchRecord) {
$batchRecord = array_merge(
$batchRecord,
- array(
+ [
'level' => $level,
'level_name' => $levelName,
'datetime' => $datetime,
- )
+ ]
);
}
diff --git a/src/Monolog/Handler/IFTTTHandler.php b/src/Monolog/Handler/IFTTTHandler.php
index d60a3c8..46792ee 100644
--- a/src/Monolog/Handler/IFTTTHandler.php
+++ b/src/Monolog/Handler/IFTTTHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -48,11 +48,11 @@ class IFTTTHandler extends AbstractProcessingHandler
*/
public function write(array $record)
{
- $postData = array(
+ $postData = [
"value1" => $record["channel"],
"value2" => $record["level_name"],
"value3" => $record["message"],
- );
+ ];
$postString = json_encode($postData);
$ch = curl_init();
@@ -60,9 +60,9 @@ class IFTTTHandler extends AbstractProcessingHandler
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array(
+ curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json",
- ));
+ ]);
Curl\Util::execute($ch);
}
diff --git a/src/Monolog/Handler/LogEntriesHandler.php b/src/Monolog/Handler/LogEntriesHandler.php
index 494c605..c74b9d2 100644
--- a/src/Monolog/Handler/LogEntriesHandler.php
+++ b/src/Monolog/Handler/LogEntriesHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
diff --git a/src/Monolog/Handler/LogglyHandler.php b/src/Monolog/Handler/LogglyHandler.php
index bcd62e1..544e7c7 100644
--- a/src/Monolog/Handler/LogglyHandler.php
+++ b/src/Monolog/Handler/LogglyHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Logger;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\LogglyFormatter;
/**
@@ -29,7 +30,7 @@ class LogglyHandler extends AbstractProcessingHandler
protected $token;
- protected $tag = array();
+ protected $tag = [];
public function __construct($token, $level = Logger::DEBUG, $bubble = true)
{
@@ -44,14 +45,14 @@ class LogglyHandler extends AbstractProcessingHandler
public function setTag($tag)
{
- $tag = !empty($tag) ? $tag : array();
- $this->tag = is_array($tag) ? $tag : array($tag);
+ $tag = !empty($tag) ? $tag : [];
+ $this->tag = is_array($tag) ? $tag : [$tag];
}
public function addTag($tag)
{
if (!empty($tag)) {
- $tag = is_array($tag) ? $tag : array($tag);
+ $tag = is_array($tag) ? $tag : [$tag];
$this->tag = array_unique(array_merge($this->tag, $tag));
}
}
@@ -78,7 +79,7 @@ class LogglyHandler extends AbstractProcessingHandler
{
$url = sprintf("https://%s/%s/%s/", self::HOST, $endpoint, $this->token);
- $headers = array('Content-Type: application/json');
+ $headers = ['Content-Type: application/json'];
if (!empty($this->tag)) {
$headers[] = 'X-LOGGLY-TAG: '.implode(',', $this->tag);
@@ -95,7 +96,7 @@ class LogglyHandler extends AbstractProcessingHandler
Curl\Util::execute($ch);
}
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new LogglyFormatter();
}
diff --git a/src/Monolog/Handler/LogmaticHandler.php b/src/Monolog/Handler/LogmaticHandler.php
new file mode 100644
index 0000000..9747220
--- /dev/null
+++ b/src/Monolog/Handler/LogmaticHandler.php
@@ -0,0 +1,88 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Monolog\Logger;
+use Monolog\Formatter\FormatterInterface;
+use Monolog\Formatter\LogmaticFormatter;
+
+/**
+ * @author Julien Breux <julien.breux@gmail.com>
+ */
+class LogmaticHandler extends SocketHandler
+{
+ /**
+ * @var string
+ */
+ private $logToken;
+
+ /**
+ * @var string
+ */
+ private $hostname;
+
+ /**
+ * @var string
+ */
+ private $appname;
+
+ /**
+ * @param string $token Log token supplied by Logmatic.
+ * @param string $hostname Host name supplied by Logmatic.
+ * @param string $appname Application name supplied by Logmatic.
+ * @param bool $useSSL Whether or not SSL encryption should be used.
+ * @param int|string $level The minimum logging level to trigger this handler.
+ * @param bool $bubble Whether or not messages that are handled should bubble up the stack.
+ *
+ * @throws MissingExtensionException If SSL encryption is set to true and OpenSSL is missing
+ */
+ public function __construct(string $token, string $hostname = '', string $appname = '', bool $useSSL = true, $level = Logger::DEBUG, bool $bubble = true)
+ {
+ if ($useSSL && !extension_loaded('openssl')) {
+ throw new MissingExtensionException('The OpenSSL PHP extension is required to use SSL encrypted connection for LogmaticHandler');
+ }
+
+ $endpoint = $useSSL ? 'ssl://api.logmatic.io:10515' : 'api.logmatic.io:10514';
+ $endpoint .= '/v1/';
+
+ parent::__construct($endpoint, $level, $bubble);
+
+ $this->logToken = $token;
+ $this->hostname = $hostname;
+ $this->appname = $appname;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function generateDataStream($record): string
+ {
+ return $this->logToken . ' ' . $record['formatted'];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function getDefaultFormatter(): FormatterInterface
+ {
+ $formatter = new LogmaticFormatter();
+
+ if (!empty($this->hostname)) {
+ $formatter->setHostname($this->hostname);
+ }
+ if (!empty($this->appname)) {
+ $formatter->setAppname($this->appname);
+ }
+
+ return $formatter;
+ }
+}
diff --git a/src/Monolog/Handler/MailHandler.php b/src/Monolog/Handler/MailHandler.php
index 9e23283..634fbc1 100644
--- a/src/Monolog/Handler/MailHandler.php
+++ b/src/Monolog/Handler/MailHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,6 +11,9 @@
namespace Monolog\Handler;
+use Monolog\Formatter\FormatterInterface;
+use Monolog\Formatter\HtmlFormatter;
+
/**
* Base class for all mail handlers
*
@@ -23,7 +26,7 @@ abstract class MailHandler extends AbstractProcessingHandler
*/
public function handleBatch(array $records)
{
- $messages = array();
+ $messages = [];
foreach ($records as $record) {
if ($record['level'] < $this->level) {
@@ -43,14 +46,14 @@ 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($content, array $records);
+ abstract protected function send(string $content, array $records);
/**
* {@inheritdoc}
*/
protected function write(array $record)
{
- $this->send((string) $record['formatted'], array($record));
+ $this->send((string) $record['formatted'], [$record]);
}
protected function getHighestRecord(array $records)
@@ -64,4 +67,19 @@ abstract class MailHandler extends AbstractProcessingHandler
return $highestRecord;
}
+
+ protected function isHtmlBody($body)
+ {
+ return substr($body, 0, 1) === '<';
+ }
+
+ /**
+ * Gets the default formatter.
+ *
+ * @return FormatterInterface
+ */
+ protected function getDefaultFormatter(): FormatterInterface
+ {
+ return new HtmlFormatter();
+ }
}
diff --git a/src/Monolog/Handler/MandrillHandler.php b/src/Monolog/Handler/MandrillHandler.php
index ab95924..066c649 100644
--- a/src/Monolog/Handler/MandrillHandler.php
+++ b/src/Monolog/Handler/MandrillHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -46,10 +46,15 @@ class MandrillHandler extends MailHandler
/**
* {@inheritdoc}
*/
- protected function send($content, array $records)
+ protected function send(string $content, array $records)
{
+ $mime = null;
+ if ($this->isHtmlBody($content)) {
+ $mime = 'text/html';
+ }
+
$message = clone $this->message;
- $message->setBody($content);
+ $message->setBody($content, $mime);
$message->setDate(time());
$ch = curl_init();
@@ -57,11 +62,11 @@ class MandrillHandler extends MailHandler
curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array(
+ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'key' => $this->apiKey,
'raw_message' => (string) $message,
'async' => false,
- )));
+ ]));
Curl\Util::execute($ch);
}
diff --git a/src/Monolog/Handler/MissingExtensionException.php b/src/Monolog/Handler/MissingExtensionException.php
index 4724a7e..1554b34 100644
--- a/src/Monolog/Handler/MissingExtensionException.php
+++ b/src/Monolog/Handler/MissingExtensionException.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
diff --git a/src/Monolog/Handler/MongoDBHandler.php b/src/Monolog/Handler/MongoDBHandler.php
index 56fe755..f302d31 100644
--- a/src/Monolog/Handler/MongoDBHandler.php
+++ b/src/Monolog/Handler/MongoDBHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,49 +11,75 @@
namespace Monolog\Handler;
+use MongoDB\Driver\BulkWrite;
+use MongoDB\Driver\Manager;
+use MongoDB\Client;
use Monolog\Logger;
-use Monolog\Formatter\NormalizerFormatter;
+use Monolog\Formatter\FormatterInterface;
+use Monolog\Formatter\MongoDBFormatter;
/**
* Logs to a MongoDB database.
*
- * usage example:
+ * Usage example:
*
- * $log = new Logger('application');
- * $mongodb = new MongoDBHandler(new \Mongo("mongodb://localhost:27017"), "logs", "prod");
+ * $log = new \Monolog\Logger('application');
+ * $client = new \MongoDB\Client('mongodb://localhost:27017');
+ * $mongodb = new \Monolog\Handler\MongoDBHandler($client, 'logs', 'prod');
* $log->pushHandler($mongodb);
*
- * @author Thomas Tourlourat <thomas@tourlourat.com>
+ * The above examples uses the MongoDB PHP library's client class; however, the
+ * MongoDB\Driver\Manager class from ext-mongodb is also supported.
*/
class MongoDBHandler extends AbstractProcessingHandler
{
- protected $mongoCollection;
+ private $collection;
+ private $manager;
+ private $namespace;
- public function __construct($mongo, $database, $collection, $level = Logger::DEBUG, $bubble = true)
+ /**
+ * Constructor.
+ *
+ * @param Client|Manager $mongodb MongoDB library or driver client
+ * @param string $database Database name
+ * @param string $collection Collection name
+ * @param int $level The minimum logging level at which this handler will be triggered
+ * @param Boolean $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)
{
- if (!($mongo instanceof \MongoClient || $mongo instanceof \Mongo || $mongo instanceof \MongoDB\Client)) {
- throw new \InvalidArgumentException('MongoClient, Mongo or MongoDB\Client instance required');
+ if (!($mongodb instanceof Client || $mongodb instanceof Manager)) {
+ throw new \InvalidArgumentException('MongoDB\Client or MongoDB\Driver\Manager instance required');
}
- $this->mongoCollection = $mongo->selectCollection($database, $collection);
+ if ($mongodb instanceof Client) {
+ $this->collection = $mongodb->selectCollection($database, $collection);
+ } else {
+ $this->manager = $mongodb;
+ $this->namespace = $database . '.' . $collection;
+ }
parent::__construct($level, $bubble);
}
protected function write(array $record)
{
- if ($this->mongoCollection instanceof \MongoDB\Collection) {
- $this->mongoCollection->insertOne($record["formatted"]);
- } else {
- $this->mongoCollection->save($record["formatted"]);
+ if (isset($this->collection)) {
+ $this->collection->insertOne($record['formatted']);
+ }
+
+ if (isset($this->manager, $this->namespace)) {
+ $bulk = new BulkWrite;
+ $bulk->insert($record["formatted"]);
+ $this->manager->executeBulkWrite($this->namespace, $bulk);
}
}
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
- return new NormalizerFormatter();
+ return new MongoDBFormatter;
}
}
diff --git a/src/Monolog/Handler/NativeMailerHandler.php b/src/Monolog/Handler/NativeMailerHandler.php
index d7807fd..b597761 100644
--- a/src/Monolog/Handler/NativeMailerHandler.php
+++ b/src/Monolog/Handler/NativeMailerHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -38,13 +38,13 @@ class NativeMailerHandler extends MailHandler
* Optional headers for the message
* @var array
*/
- protected $headers = array();
+ protected $headers = [];
/**
* Optional parameters for the message
* @var array
*/
- protected $parameters = array();
+ protected $parameters = [];
/**
* The wordwrap length for the message
@@ -56,7 +56,7 @@ class NativeMailerHandler extends MailHandler
* The Content-type for the message
* @var string
*/
- protected $contentType = 'text/plain';
+ protected $contentType;
/**
* The encoding for the message
@@ -75,7 +75,7 @@ class NativeMailerHandler extends MailHandler
public function __construct($to, $subject, $from, $level = Logger::ERROR, $bubble = true, $maxColumnWidth = 70)
{
parent::__construct($level, $bubble);
- $this->to = is_array($to) ? $to : array($to);
+ $this->to = (array) $to;
$this->subject = $subject;
$this->addHeader(sprintf('From: %s', $from));
$this->maxColumnWidth = $maxColumnWidth;
@@ -115,12 +115,17 @@ class NativeMailerHandler extends MailHandler
/**
* {@inheritdoc}
*/
- protected function send($content, array $records)
+ protected function send(string $content, array $records)
{
- $content = wordwrap($content, $this->maxColumnWidth);
+ $contentType = $this->getContentType() ?: ($this->isHtmlBody($content) ? 'text/html' : 'text/plain');
+
+ if ($contentType !== 'text/html') {
+ $content = wordwrap($content, $this->maxColumnWidth);
+ }
+
$headers = ltrim(implode("\r\n", $this->headers) . "\r\n", "\r\n");
- $headers .= 'Content-type: ' . $this->getContentType() . '; charset=' . $this->getEncoding() . "\r\n";
- if ($this->getContentType() == 'text/html' && false === strpos($headers, 'MIME-Version:')) {
+ $headers .= 'Content-type: ' . $contentType . '; charset=' . $this->getEncoding() . "\r\n";
+ if ($contentType === 'text/html' && false === strpos($headers, 'MIME-Version:')) {
$headers .= 'MIME-Version: 1.0' . "\r\n";
}
diff --git a/src/Monolog/Handler/NewRelicHandler.php b/src/Monolog/Handler/NewRelicHandler.php
index 6718e9e..fb03778 100644
--- a/src/Monolog/Handler/NewRelicHandler.php
+++ b/src/Monolog/Handler/NewRelicHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,6 +13,7 @@ namespace Monolog\Handler;
use Monolog\Logger;
use Monolog\Formatter\NormalizerFormatter;
+use Monolog\Formatter\FormatterInterface;
/**
* Class to record a log on a NewRelic application.
@@ -195,7 +196,7 @@ class NewRelicHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new NormalizerFormatter();
}
diff --git a/src/Monolog/Handler/NoopHandler.php b/src/Monolog/Handler/NoopHandler.php
new file mode 100644
index 0000000..8ee2b4c
--- /dev/null
+++ b/src/Monolog/Handler/NoopHandler.php
@@ -0,0 +1,40 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+/**
+ * No-op
+ *
+ * This handler handles anything, but does nothing, and does not stop bubbling to the rest of the stack.
+ * This can be used for testing, or to disable a handler when overriding a configuration without
+ * influencing the rest of the stack.
+ *
+ * @author Roel Harbers <roelharbers@gmail.com>
+ */
+class NoopHandler extends Handler
+{
+ /**
+ * {@inheritdoc}
+ */
+ public function isHandling(array $record): bool
+ {
+ return true;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function handle(array $record): bool
+ {
+ return false;
+ }
+}
diff --git a/src/Monolog/Handler/NullHandler.php b/src/Monolog/Handler/NullHandler.php
index 4b84588..93678e8 100644
--- a/src/Monolog/Handler/NullHandler.php
+++ b/src/Monolog/Handler/NullHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -21,20 +21,30 @@ use Monolog\Logger;
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
-class NullHandler extends AbstractHandler
+class NullHandler extends Handler
{
+ private $level;
+
/**
* @param int $level The minimum logging level at which this handler will be triggered
*/
- public function __construct($level = Logger::DEBUG)
+ public function __construct(int $level = Logger::DEBUG)
+ {
+ $this->level = $level;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function isHandling(array $record): bool
{
- parent::__construct($level, false);
+ return $record['level'] >= $this->level;
}
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
if ($record['level'] < $this->level) {
return false;
diff --git a/src/Monolog/Handler/PHPConsoleHandler.php b/src/Monolog/Handler/PHPConsoleHandler.php
index 1f2076a..c2b7b3e 100644
--- a/src/Monolog/Handler/PHPConsoleHandler.php
+++ b/src/Monolog/Handler/PHPConsoleHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,11 +11,11 @@
namespace Monolog\Handler;
-use Exception;
use Monolog\Formatter\LineFormatter;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
use PhpConsole\Connector;
-use PhpConsole\Handler;
+use PhpConsole\Handler as VendorPhpConsoleHandler;
use PhpConsole\Helper;
/**
@@ -32,17 +32,17 @@ use PhpConsole\Helper;
* $logger = new \Monolog\Logger('all', array(new \Monolog\Handler\PHPConsoleHandler()));
* \Monolog\ErrorHandler::register($logger);
* echo $undefinedVar;
- * $logger->addDebug('SELECT * FROM users', array('db', 'time' => 0.012));
+ * $logger->debug('SELECT * FROM users', array('db', 'time' => 0.012));
* PC::debug($_SERVER); // PHP Console debugger for any type of vars
*
* @author Sergey Barbushin https://www.linkedin.com/in/barbushin
*/
class PHPConsoleHandler extends AbstractProcessingHandler
{
- private $options = array(
+ private $options = [
'enabled' => true, // bool Is PHP Console server enabled
- 'classesPartialsTraceIgnore' => array('Monolog\\'), // array Hide calls of classes started with...
- 'debugTagsKeysInContext' => array(0, 'tag'), // bool Is PHP Console server enabled
+ 'classesPartialsTraceIgnore' => ['Monolog\\'], // array Hide calls of classes started with...
+ 'debugTagsKeysInContext' => [0, 'tag'], // bool Is PHP Console server enabled
'useOwnErrorsHandler' => false, // bool Enable errors handling
'useOwnExceptionsHandler' => false, // bool Enable exceptions handling
'sourcesBasePath' => null, // string Base path of all project sources to strip in errors source paths
@@ -51,7 +51,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
'headersLimit' => null, // int|null Set headers size limit for your web-server
'password' => null, // string|null Protect PHP Console connection by password
'enableSslOnlyMode' => false, // bool Force connection by SSL for clients with PHP Console installed
- 'ipMasks' => array(), // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1')
+ 'ipMasks' => [], // array Set IP masks of clients that will be allowed to connect to PHP Console: array('192.168.*.*', '127.0.0.1')
'enableEvalListener' => false, // bool Enable eval request to be handled by eval dispatcher(if enabled, 'password' option is also required)
'dumperDetectCallbacks' => false, // bool Convert callback items in dumper vars to (callback SomeClass::someMethod) strings
'dumperLevelLimit' => 5, // int Maximum dumped vars array or object nested dump level
@@ -60,22 +60,22 @@ class PHPConsoleHandler extends AbstractProcessingHandler
'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)
- );
+ ];
/** @var Connector */
private $connector;
/**
- * @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 bool $bubble
- * @throws Exception
+ * @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 bool $bubble
+ * @throws \RuntimeException
*/
- public function __construct(array $options = array(), Connector $connector = null, $level = Logger::DEBUG, $bubble = true)
+ public function __construct(array $options = [], Connector $connector = null, $level = Logger::DEBUG, $bubble = true)
{
if (!class_exists('PhpConsole\Connector')) {
- throw new Exception('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
+ throw new \RuntimeException('PHP Console library not found. See https://github.com/barbushin/php-console#installation');
}
parent::__construct($level, $bubble);
$this->options = $this->initOptions($options);
@@ -86,7 +86,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
{
$wrongOptions = array_diff(array_keys($options), array_keys($this->options));
if ($wrongOptions) {
- throw new Exception('Unknown options: ' . implode(', ', $wrongOptions));
+ throw new \RuntimeException('Unknown options: ' . implode(', ', $wrongOptions));
}
return array_replace($this->options, $options);
@@ -107,7 +107,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
if ($this->options['enabled'] && $connector->isActiveClient()) {
if ($this->options['useOwnErrorsHandler'] || $this->options['useOwnExceptionsHandler']) {
- $handler = Handler::getInstance();
+ $handler = VendorPhpConsoleHandler::getInstance();
$handler->setHandleErrors($this->options['useOwnErrorsHandler']);
$handler->setHandleExceptions($this->options['useOwnExceptionsHandler']);
$handler->start();
@@ -157,7 +157,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
return $this->options;
}
- public function handle(array $record)
+ public function handle(array $record): bool
{
if ($this->options['enabled'] && $this->connector->isActiveClient()) {
return parent::handle($record);
@@ -176,7 +176,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
{
if ($record['level'] < Logger::NOTICE) {
$this->handleDebugRecord($record);
- } elseif (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) {
+ } elseif (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Throwable) {
$this->handleExceptionRecord($record);
} else {
$this->handleErrorRecord($record);
@@ -203,10 +203,10 @@ class PHPConsoleHandler extends AbstractProcessingHandler
$context = $record['context'];
$this->connector->getErrorsDispatcher()->dispatchError(
- isset($context['code']) ? $context['code'] : null,
- isset($context['message']) ? $context['message'] : $record['message'],
- isset($context['file']) ? $context['file'] : null,
- isset($context['line']) ? $context['line'] : null,
+ $context['code'] ?? null,
+ $context['message'] ?? $record['message'],
+ $context['file'] ?? null,
+ $context['line'] ?? null,
$this->options['classesPartialsTraceIgnore']
);
}
@@ -235,7 +235,7 @@ class PHPConsoleHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter('%message%');
}
diff --git a/src/Monolog/Handler/ProcessHandler.php b/src/Monolog/Handler/ProcessHandler.php
new file mode 100644
index 0000000..8cf6087
--- /dev/null
+++ b/src/Monolog/Handler/ProcessHandler.php
@@ -0,0 +1,202 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Monolog\Logger;
+
+/**
+ * Stores to STDIN of any process, specified by a command.
+ *
+ * Usage example:
+ * <pre>
+ * $log = new Logger('myLogger');
+ * $log->pushHandler(new ProcessHandler('/usr/bin/php /var/www/monolog/someScript.php'));
+ * </pre>
+ *
+ * @author Kolja Zuelsdorf <koljaz@web.de>
+ */
+class ProcessHandler extends AbstractProcessingHandler
+{
+ /**
+ * Holds the process to receive data on its STDIN.
+ *
+ * @var resource|bool|null
+ */
+ private $process;
+
+ /**
+ * @var string
+ */
+ private $command;
+
+ /**
+ * @var string
+ */
+ private $cwd;
+
+ /**
+ * @var array
+ */
+ private $pipes = [];
+
+ /**
+ * @var array
+ */
+ const DESCRIPTOR_SPEC = [
+ 0 => ['pipe', 'r'], // STDIN is a pipe that the child will read from
+ 1 => ['pipe', 'w'], // STDOUT is a pipe that the child will write to
+ 2 => ['pipe', 'w'], // STDERR is a pipe to catch the any errors
+ ];
+
+ /**
+ * @param string $command Command for the process to start. Absolute paths are recommended,
+ * especially if you do not use the $cwd parameter.
+ * @param string|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.
+ * @throws \InvalidArgumentException
+ */
+ 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.');
+ }
+ if ($cwd === '') {
+ throw new \InvalidArgumentException('The optional CWD argument must be a non-empty string or null.');
+ }
+
+ parent::__construct($level, $bubble);
+
+ $this->command = $command;
+ $this->cwd = $cwd;
+ }
+
+ /**
+ * Writes the record down to the log of the implementing handler
+ *
+ * @param array $record
+ * @throws \UnexpectedValueException
+ * @return void
+ */
+ protected function write(array $record)
+ {
+ $this->ensureProcessIsStarted();
+
+ $this->writeProcessInput($record['formatted']);
+
+ $errors = $this->readProcessErrors();
+ if (empty($errors) === false) {
+ throw new \UnexpectedValueException(sprintf('Errors while writing to process: %s', $errors));
+ }
+ }
+
+ /**
+ * Makes sure that the process is actually started, and if not, starts it,
+ * assigns the stream pipes, and handles startup errors, if any.
+ *
+ * @return void
+ */
+ private function ensureProcessIsStarted()
+ {
+ if (is_resource($this->process) === false) {
+ $this->startProcess();
+
+ $this->handleStartupErrors();
+ }
+ }
+
+ /**
+ * Starts the actual process and sets all streams to non-blocking.
+ *
+ * @return void
+ */
+ private function startProcess()
+ {
+ $this->process = proc_open($this->command, self::DESCRIPTOR_SPEC, $this->pipes, $this->cwd);
+
+ foreach ($this->pipes as $pipe) {
+ stream_set_blocking($pipe, false);
+ }
+ }
+
+ /**
+ * Selects the STDERR stream, handles upcoming startup errors, and throws an exception, if any.
+ *
+ * @throws \UnexpectedValueException
+ * @return void
+ */
+ private function handleStartupErrors()
+ {
+ $selected = $this->selectErrorStream();
+ if (false === $selected) {
+ throw new \UnexpectedValueException('Something went wrong while selecting a stream.');
+ }
+
+ $errors = $this->readProcessErrors();
+
+ if (is_resource($this->process) === false || empty($errors) === false) {
+ throw new \UnexpectedValueException(
+ sprintf('The process "%s" could not be opened: ' . $errors, $this->command)
+ );
+ }
+ }
+
+ /**
+ * Selects the STDERR stream.
+ *
+ * @return int|bool
+ */
+ protected function selectErrorStream()
+ {
+ $empty = [];
+ $errorPipes = [$this->pipes[2]];
+
+ return stream_select($errorPipes, $empty, $empty, 1);
+ }
+
+ /**
+ * Reads the errors of the process, if there are any.
+ *
+ * @codeCoverageIgnore
+ * @return string Empty string if there are no errors.
+ */
+ protected function readProcessErrors()
+ {
+ return stream_get_contents($this->pipes[2]);
+ }
+
+ /**
+ * Writes to the input stream of the opened process.
+ *
+ * @codeCoverageIgnore
+ * @param $string
+ * @return void
+ */
+ protected function writeProcessInput($string)
+ {
+ fwrite($this->pipes[0], (string) $string);
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function close()
+ {
+ if (is_resource($this->process)) {
+ foreach ($this->pipes as $pipe) {
+ fclose($pipe);
+ }
+ proc_close($this->process);
+ $this->process = null;
+ }
+ }
+}
diff --git a/src/Monolog/Handler/ProcessableHandlerInterface.php b/src/Monolog/Handler/ProcessableHandlerInterface.php
new file mode 100644
index 0000000..9556f98
--- /dev/null
+++ b/src/Monolog/Handler/ProcessableHandlerInterface.php
@@ -0,0 +1,36 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+/**
+ * Interface to describe loggers that have processors
+ *
+ * @author Jordi Boggiano <j.boggiano@seld.be>
+ */
+interface ProcessableHandlerInterface
+{
+ /**
+ * Adds a processor in the stack.
+ *
+ * @param callable $callback
+ * @return HandlerInterface self
+ */
+ public function pushProcessor(callable $callback): HandlerInterface;
+
+ /**
+ * Removes the processor on top of the stack and returns it.
+ *
+ * @throws \LogicException In case the processor stack is empty
+ * @return callable
+ */
+ public function popProcessor(): callable;
+}
diff --git a/src/Monolog/Handler/ProcessableHandlerTrait.php b/src/Monolog/Handler/ProcessableHandlerTrait.php
new file mode 100644
index 0000000..bba940e
--- /dev/null
+++ b/src/Monolog/Handler/ProcessableHandlerTrait.php
@@ -0,0 +1,62 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+/**
+ * Helper trait for implementing ProcessableInterface
+ *
+ * @author Jordi Boggiano <j.boggiano@seld.be>
+ */
+trait ProcessableHandlerTrait
+{
+ /**
+ * @var callable[]
+ */
+ protected $processors = [];
+
+ /**
+ * {@inheritdoc}
+ */
+ public function pushProcessor(callable $callback): HandlerInterface
+ {
+ array_unshift($this->processors, $callback);
+
+ return $this;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function popProcessor(): callable
+ {
+ if (!$this->processors) {
+ throw new \LogicException('You tried to pop from an empty processor stack.');
+ }
+
+ return array_shift($this->processors);
+ }
+
+ /**
+ * Processes a record.
+ *
+ * @param array $record
+ * @return array
+ */
+ protected function processRecord(array $record)
+ {
+ foreach ($this->processors as $processor) {
+ $record = $processor($record);
+ }
+
+ return $record;
+ }
+}
diff --git a/src/Monolog/Handler/PsrHandler.php b/src/Monolog/Handler/PsrHandler.php
index 1ae8584..415b45f 100644
--- a/src/Monolog/Handler/PsrHandler.php
+++ b/src/Monolog/Handler/PsrHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -43,7 +43,7 @@ class PsrHandler extends AbstractHandler
/**
* {@inheritDoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
if (!$this->isHandling($record)) {
return false;
diff --git a/src/Monolog/Handler/PushoverHandler.php b/src/Monolog/Handler/PushoverHandler.php
index bba7200..b53ce6c 100644
--- a/src/Monolog/Handler/PushoverHandler.php
+++ b/src/Monolog/Handler/PushoverHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -37,7 +37,7 @@ class PushoverHandler extends SocketHandler
* @see https://pushover.net/api
* @var array
*/
- private $parameterNames = array(
+ private $parameterNames = [
'token' => true,
'user' => true,
'message' => true,
@@ -51,18 +51,18 @@ class PushoverHandler extends SocketHandler
'retry' => true,
'expire' => true,
'callback' => true,
- );
+ ];
/**
* Sounds the api supports by default
* @see https://pushover.net/api#sounds
* @var array
*/
- private $sounds = array(
+ private $sounds = [
'pushover', 'bike', 'bugle', 'cashregister', 'classical', 'cosmic', 'falling', 'gamelan', 'incoming',
'intermission', 'magic', 'mechanical', 'pianobar', 'siren', 'spacealarm', 'tugboat', 'alien', 'climb',
'persistent', 'echo', 'updown', 'none',
- );
+ ];
/**
* @param string $token Pushover api token
@@ -110,13 +110,13 @@ class PushoverHandler extends SocketHandler
$timestamp = $record['datetime']->getTimestamp();
- $dataArray = array(
+ $dataArray = [
'token' => $this->token,
'user' => $this->user,
'message' => $message,
'title' => $this->title,
'timestamp' => $timestamp,
- );
+ ];
if (isset($record['level']) && $record['level'] >= $this->emergencyLevel) {
$dataArray['priority'] = 2;
diff --git a/src/Monolog/Handler/RavenHandler.php b/src/Monolog/Handler/RavenHandler.php
index 53a8b39..1c8e718 100644
--- a/src/Monolog/Handler/RavenHandler.php
+++ b/src/Monolog/Handler/RavenHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -27,7 +27,7 @@ class RavenHandler extends AbstractProcessingHandler
/**
* Translates Monolog log levels to Raven log levels.
*/
- private $logLevels = array(
+ private $logLevels = [
Logger::DEBUG => Raven_Client::DEBUG,
Logger::INFO => Raven_Client::INFO,
Logger::NOTICE => Raven_Client::INFO,
@@ -36,7 +36,7 @@ class RavenHandler extends AbstractProcessingHandler
Logger::CRITICAL => Raven_Client::FATAL,
Logger::ALERT => Raven_Client::FATAL,
Logger::EMERGENCY => Raven_Client::FATAL,
- );
+ ];
/**
* @var string should represent the current version of the calling
@@ -92,7 +92,7 @@ class RavenHandler extends AbstractProcessingHandler
});
// the other ones are added as a context item
- $logs = array();
+ $logs = [];
foreach ($records as $r) {
$logs[] = $this->processRecord($r);
}
@@ -133,10 +133,11 @@ class RavenHandler extends AbstractProcessingHandler
*/
protected function write(array $record)
{
+ /** @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;
- $options = array();
+ $options = [];
$options['level'] = $this->logLevels[$record['level']];
- $options['tags'] = array();
+ $options['tags'] = [];
if (!empty($record['extra']['tags'])) {
$options['tags'] = array_merge($options['tags'], $record['extra']['tags']);
unset($record['extra']['tags']);
@@ -156,7 +157,7 @@ class RavenHandler extends AbstractProcessingHandler
$options['logger'] = $record['channel'];
}
foreach ($this->getExtraParameters() as $key) {
- foreach (array('extra', 'context') as $source) {
+ foreach (['extra', 'context'] as $source) {
if (!empty($record[$source][$key])) {
$options[$key] = $record[$source][$key];
unset($record[$source][$key]);
@@ -179,14 +180,15 @@ class RavenHandler extends AbstractProcessingHandler
$options['release'] = $this->release;
}
- if (isset($record['context']['exception']) && ($record['context']['exception'] instanceof \Exception || (PHP_VERSION_ID >= 70000 && $record['context']['exception'] instanceof \Throwable))) {
+ if (isset($record['context']['exception']) && $record['context']['exception'] instanceof \Throwable) {
$options['extra']['message'] = $record['formatted'];
$this->ravenClient->captureException($record['context']['exception'], $options);
} else {
- $this->ravenClient->captureMessage($record['formatted'], array(), $options);
+ $this->ravenClient->captureMessage($record['formatted'], [], $options);
}
- if ($previousUserContext !== false) {
+ // restore the user context if it was modified
+ if (!is_bool($previousUserContext)) {
$this->ravenClient->user_context($previousUserContext);
}
}
@@ -194,7 +196,7 @@ class RavenHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter('[%channel%] %message%');
}
@@ -216,11 +218,11 @@ class RavenHandler extends AbstractProcessingHandler
*/
protected function getExtraParameters()
{
- return array('checksum', 'release', 'event_id');
+ return ['checksum', 'release', 'event_id'];
}
/**
- * @param string $value
+ * @param string $value
* @return self
*/
public function setRelease($value)
diff --git a/src/Monolog/Handler/RedisHandler.php b/src/Monolog/Handler/RedisHandler.php
index 590f996..e7ddb44 100644
--- a/src/Monolog/Handler/RedisHandler.php
+++ b/src/Monolog/Handler/RedisHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,6 +12,7 @@
namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Logger;
/**
@@ -36,9 +37,9 @@ class RedisHandler extends AbstractProcessingHandler
* @param string $key The key name to push records to
* @param int $level The minimum logging level at which this handler will be triggered
* @param bool $bubble Whether the messages that are handled can bubble up the stack or not
- * @param int $capSize Number of entries to limit list size to
+ * @param int $capSize Number of entries to limit list size to, 0 = unlimited
*/
- public function __construct($redis, $key, $level = Logger::DEBUG, $bubble = true, $capSize = false)
+ public function __construct($redis, string $key, $level = Logger::DEBUG, bool $bubble = true, int $capSize = 0)
{
if (!(($redis instanceof \Predis\Client) || ($redis instanceof \Redis))) {
throw new \InvalidArgumentException('Predis\Client or Redis instance required');
@@ -90,7 +91,7 @@ class RedisHandler extends AbstractProcessingHandler
/**
* {@inheritDoc}
*/
- protected function getDefaultFormatter()
+ protected function getDefaultFormatter(): FormatterInterface
{
return new LineFormatter();
}
diff --git a/src/Monolog/Handler/RollbarHandler.php b/src/Monolog/Handler/RollbarHandler.php
index 6c8a3e3..5b6678e 100644
--- a/src/Monolog/Handler/RollbarHandler.php
+++ b/src/Monolog/Handler/RollbarHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use RollbarNotifier;
-use Exception;
+use Throwable;
use Monolog\Logger;
/**
@@ -40,7 +40,7 @@ class RollbarHandler extends AbstractProcessingHandler
*/
protected $rollbarNotifier;
- protected $levelMap = array(
+ protected $levelMap = [
Logger::DEBUG => 'debug',
Logger::INFO => 'info',
Logger::NOTICE => 'info',
@@ -49,7 +49,7 @@ class RollbarHandler extends AbstractProcessingHandler
Logger::CRITICAL => 'critical',
Logger::ALERT => 'critical',
Logger::EMERGENCY => 'critical',
- );
+ ];
/**
* Records whether any log records have been added since the last flush of the rollbar notifier
@@ -84,19 +84,19 @@ class RollbarHandler extends AbstractProcessingHandler
}
$context = $record['context'];
- $payload = array();
+ $payload = [];
if (isset($context['payload'])) {
$payload = $context['payload'];
unset($context['payload']);
}
- $context = array_merge($context, $record['extra'], array(
+ $context = array_merge($context, $record['extra'], [
'level' => $this->levelMap[$record['level']],
'monolog_level' => $record['level_name'],
'channel' => $record['channel'],
'datetime' => $record['datetime']->format('U'),
- ));
+ ]);
- if (isset($context['exception']) && $context['exception'] instanceof Exception) {
+ if (isset($context['exception']) && $context['exception'] instanceof Throwable) {
$payload['level'] = $context['level'];
$exception = $context['exception'];
unset($context['exception']);
diff --git a/src/Monolog/Handler/RotatingFileHandler.php b/src/Monolog/Handler/RotatingFileHandler.php
index 3b60b3d..a4a5ba4 100644
--- a/src/Monolog/Handler/RotatingFileHandler.php
+++ b/src/Monolog/Handler/RotatingFileHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,6 +11,7 @@
namespace Monolog\Handler;
+use InvalidArgumentException;
use Monolog\Logger;
/**
@@ -47,7 +48,7 @@ class RotatingFileHandler extends StreamHandler
{
$this->filename = $filename;
$this->maxFiles = (int) $maxFiles;
- $this->nextRotation = new \DateTime('tomorrow');
+ $this->nextRotation = new \DateTimeImmutable('tomorrow');
$this->filenameFormat = '{filename}-{date}';
$this->dateFormat = 'Y-m-d';
@@ -69,18 +70,16 @@ class RotatingFileHandler extends StreamHandler
public function setFilenameFormat($filenameFormat, $dateFormat)
{
if (!preg_match('{^Y(([/_.-]?m)([/_.-]?d)?)?$}', $dateFormat)) {
- trigger_error(
+ throw new InvalidArgumentException(
'Invalid date format - format must be one of '.
'RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), RotatingFileHandler::FILE_PER_MONTH ("Y-m") '.
'or RotatingFileHandler::FILE_PER_YEAR ("Y"), or you can set one of the '.
- 'date formats using slashes, underscores and/or dots instead of dashes.',
- E_USER_DEPRECATED
+ 'date formats using slashes, underscores and/or dots instead of dashes.'
);
}
if (substr_count($filenameFormat, '{date}') === 0) {
- trigger_error(
- 'Invalid filename format - format should contain at least `{date}`, because otherwise rotating is impossible.',
- E_USER_DEPRECATED
+ throw new InvalidArgumentException(
+ 'Invalid filename format - format must contain at least `{date}`, because otherwise rotating is impossible.'
);
}
$this->filenameFormat = $filenameFormat;
@@ -114,7 +113,7 @@ class RotatingFileHandler extends StreamHandler
{
// update filename
$this->url = $this->getTimedFilename();
- $this->nextRotation = new \DateTime('tomorrow');
+ $this->nextRotation = new \DateTimeImmutable('tomorrow');
// skip GC of old logs if files are unlimited
if (0 === $this->maxFiles) {
@@ -136,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 ($errno, $errstr, $errfile, $errline) {
+ });
unlink($file);
restore_error_handler();
}
@@ -149,8 +149,8 @@ class RotatingFileHandler extends StreamHandler
{
$fileInfo = pathinfo($this->filename);
$timedFilename = str_replace(
- array('{filename}', '{date}'),
- array($fileInfo['filename'], date($this->dateFormat)),
+ ['{filename}', '{date}'],
+ [$fileInfo['filename'], date($this->dateFormat)],
$fileInfo['dirname'] . '/' . $this->filenameFormat
);
@@ -165,8 +165,8 @@ class RotatingFileHandler extends StreamHandler
{
$fileInfo = pathinfo($this->filename);
$glob = str_replace(
- array('{filename}', '{date}'),
- array($fileInfo['filename'], '*'),
+ ['{filename}', '{date}'],
+ [$fileInfo['filename'], '*'],
$fileInfo['dirname'] . '/' . $this->filenameFormat
);
if (!empty($fileInfo['extension'])) {
diff --git a/src/Monolog/Handler/SamplingHandler.php b/src/Monolog/Handler/SamplingHandler.php
index 9509ae3..8a25cbb 100644
--- a/src/Monolog/Handler/SamplingHandler.php
+++ b/src/Monolog/Handler/SamplingHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -25,8 +25,10 @@ namespace Monolog\Handler;
* @author Bryan Davis <bd808@wikimedia.org>
* @author Kunal Mehta <legoktm@gmail.com>
*/
-class SamplingHandler extends AbstractHandler
+class SamplingHandler extends AbstractHandler implements ProcessableHandlerInterface
{
+ use ProcessableHandlerTrait;
+
/**
* @var callable|HandlerInterface $handler
*/
@@ -52,12 +54,12 @@ class SamplingHandler extends AbstractHandler
}
}
- public function isHandling(array $record)
+ public function isHandling(array $record): bool
{
return $this->handler->isHandling($record);
}
- public function handle(array $record)
+ public function handle(array $record): bool
{
if ($this->isHandling($record) && mt_rand(1, $this->factor) === 1) {
// The same logic as in FingersCrossedHandler
@@ -69,9 +71,7 @@ class SamplingHandler extends AbstractHandler
}
if ($this->processors) {
- foreach ($this->processors as $processor) {
- $record = call_user_func($processor, $record);
- }
+ $record = $this->processRecord($record);
}
$this->handler->handle($record);
diff --git a/src/Monolog/Handler/SendGridHandler.php b/src/Monolog/Handler/SendGridHandler.php
new file mode 100644
index 0000000..7d82d94
--- /dev/null
+++ b/src/Monolog/Handler/SendGridHandler.php
@@ -0,0 +1,100 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Monolog\Logger;
+
+/**
+ * SendGridrHandler uses the SendGrid API v2 function to send Log emails, more information in https://sendgrid.com/docs/API_Reference/Web_API/mail.html
+ *
+ * @author Ricardo Fontanelli <ricardo.fontanelli@hotmail.com>
+ */
+class SendGridHandler extends MailHandler
+{
+ /**
+ * The SendGrid API User
+ * @var string
+ */
+ protected $apiUser;
+
+ /**
+ * The SendGrid API Key
+ * @var string
+ */
+ protected $apiKey;
+
+ /**
+ * The email addresses to which the message will be sent
+ * @var string
+ */
+ protected $from;
+
+ /**
+ * The email addresses to which the message will be sent
+ * @var array
+ */
+ protected $to;
+
+ /**
+ * The subject of the email
+ * @var string
+ */
+ protected $subject;
+
+ /**
+ * @param string $apiUser The SendGrid API User
+ * @param string $apiKey The SendGrid API Key
+ * @param string $from The sender of the email
+ * @param string|array $to The recipients of the email
+ * @param string $subject The subject of the mail
+ * @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(string $apiUser, string $apiKey, string $from, $to, string $subject, int $level = Logger::ERROR, bool $bubble = true)
+ {
+ parent::__construct($level, $bubble);
+ $this->apiUser = $apiUser;
+ $this->apiKey = $apiKey;
+ $this->from = $from;
+ $this->to = (array) $to;
+ $this->subject = $subject;
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ protected function send(string $content, array $records)
+ {
+ $message = [];
+ $message['api_user'] = $this->apiUser;
+ $message['api_key'] = $this->apiKey;
+ $message['from'] = $this->from;
+ foreach ($this->to as $recipient) {
+ $message['to[]'] = $recipient;
+ }
+ $message['subject'] = $this->subject;
+ $message['date'] = date('r');
+
+ if ($this->isHtmlBody($content)) {
+ $message['html'] = $content;
+ } else {
+ $message['text'] = $content;
+ }
+
+ $ch = curl_init();
+ curl_setopt($ch, CURLOPT_URL, 'https://api.sendgrid.com/api/mail.send.json');
+ curl_setopt($ch, CURLOPT_POST, 1);
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($message));
+ Curl\Util::execute($ch, 2);
+ }
+}
diff --git a/src/Monolog/Handler/Slack/SlackRecord.php b/src/Monolog/Handler/Slack/SlackRecord.php
index 38bc838..d9e6a4c 100644
--- a/src/Monolog/Handler/Slack/SlackRecord.php
+++ b/src/Monolog/Handler/Slack/SlackRecord.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -89,7 +89,7 @@ class SlackRecord
{
$this->channel = $channel;
$this->username = $username;
- $this->userIcon = trim($userIcon, ':');
+ $this->userIcon = $userIcon !== null ? trim($userIcon, ':') : null;
$this->useAttachment = $useAttachment;
$this->useShortAttachment = $useShortAttachment;
$this->includeContextAndExtra = $includeContextAndExtra;
@@ -127,7 +127,7 @@ class SlackRecord
'color' => $this->getAttachmentColor($record['level']),
'fields' => array(),
'mrkdwn_in' => array('fields'),
- 'ts' => $record['datetime']->getTimestamp()
+ 'ts' => $record['datetime']->getTimestamp(),
);
if ($this->useShortAttachment) {
@@ -137,7 +137,6 @@ class SlackRecord
$attachment['fields'][] = $this->generateAttachmentField('Level', $record['level_name']);
}
-
if ($this->includeContextAndExtra) {
foreach (array('extra', 'context') as $key) {
if (empty($record[$key])) {
@@ -229,7 +228,7 @@ class SlackRecord
/**
* Generates attachment field
*
- * @param string $title
+ * @param string $title
* @param string|array $value\
*
* @return array
@@ -243,7 +242,7 @@ class SlackRecord
return array(
'title' => $title,
'value' => $value,
- 'short' => false
+ 'short' => false,
);
}
diff --git a/src/Monolog/Handler/SlackHandler.php b/src/Monolog/Handler/SlackHandler.php
index 3ac4d83..a99872f 100644
--- a/src/Monolog/Handler/SlackHandler.php
+++ b/src/Monolog/Handler/SlackHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -197,7 +197,7 @@ class SlackHandler extends SocketHandler
return $this->slackRecord->stringify($fields);
}
- public function setFormatter(FormatterInterface $formatter)
+ public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
parent::setFormatter($formatter);
$this->slackRecord->setFormatter($formatter);
@@ -205,7 +205,7 @@ class SlackHandler extends SocketHandler
return $this;
}
- public function getFormatter()
+ public function getFormatter(): FormatterInterface
{
$formatter = parent::getFormatter();
$this->slackRecord->setFormatter($formatter);
diff --git a/src/Monolog/Handler/SlackWebhookHandler.php b/src/Monolog/Handler/SlackWebhookHandler.php
index 9a1bbb4..a2ea52a 100644
--- a/src/Monolog/Handler/SlackWebhookHandler.php
+++ b/src/Monolog/Handler/SlackWebhookHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -36,16 +36,16 @@ class SlackWebhookHandler extends AbstractProcessingHandler
private $slackRecord;
/**
- * @param string $webhookUrl Slack Webhook URL
- * @param string|null $channel Slack channel (encoded ID or name)
- * @param string|null $username Name of a bot
- * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
- * @param string|null $iconEmoji The emoji name to use (or null)
- * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
- * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
- * @param int $level The minimum logging level at which this handler will be triggered
- * @param bool $bubble Whether the messages that are handled can bubble up the stack or not
- * @param array $excludeFields Dot separated list of fields to exclude from slack message. E.g. ['context.field1', 'extra.field2']
+ * @param string $webhookUrl Slack Webhook URL
+ * @param string|null $channel Slack channel (encoded ID or name)
+ * @param string|null $username Name of a bot
+ * @param bool $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
+ * @param string|null $iconEmoji The emoji name to use (or null)
+ * @param bool $useShortAttachment Whether the the context/extra messages added to Slack as attachments are in a short style
+ * @param bool $includeContextAndExtra Whether the attachment should include context and extra data
+ * @param int $level The minimum logging level at which this handler will be triggered
+ * @param 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())
{
@@ -97,7 +97,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
Curl\Util::execute($ch);
}
- public function setFormatter(FormatterInterface $formatter)
+ public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
parent::setFormatter($formatter);
$this->slackRecord->setFormatter($formatter);
@@ -105,7 +105,7 @@ class SlackWebhookHandler extends AbstractProcessingHandler
return $this;
}
- public function getFormatter()
+ public function getFormatter(): FormatterInterface
{
$formatter = parent::getFormatter();
$this->slackRecord->setFormatter($formatter);
diff --git a/src/Monolog/Handler/SlackbotHandler.php b/src/Monolog/Handler/SlackbotHandler.php
index baead52..dd2db59 100644
--- a/src/Monolog/Handler/SlackbotHandler.php
+++ b/src/Monolog/Handler/SlackbotHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -40,11 +40,11 @@ class SlackbotHandler extends AbstractProcessingHandler
private $channel;
/**
- * @param string $slackTeam Slack team slug
- * @param string $token Slackbot token
- * @param string $channel Slack channel (encoded ID or name)
- * @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 string $slackTeam Slack team slug
+ * @param string $token Slackbot token
+ * @param string $channel Slack channel (encoded ID or name)
+ * @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)
{
diff --git a/src/Monolog/Handler/SocketHandler.php b/src/Monolog/Handler/SocketHandler.php
index 7a61bf4..e2161ff 100644
--- a/src/Monolog/Handler/SocketHandler.php
+++ b/src/Monolog/Handler/SocketHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -23,8 +23,11 @@ class SocketHandler extends AbstractProcessingHandler
{
private $connectionString;
private $connectionTimeout;
+ /** @var resource|null */
private $resource;
+ /** @var float */
private $timeout = 0;
+ /** @var float */
private $writingTimeout = 10;
private $lastSentBytes = null;
private $persistent = false;
@@ -149,20 +152,16 @@ class SocketHandler extends AbstractProcessingHandler
/**
* Get current connection timeout setting
- *
- * @return float
*/
- public function getConnectionTimeout()
+ public function getConnectionTimeout(): float
{
return $this->connectionTimeout;
}
/**
* Get current in-transfer timeout
- *
- * @return float
*/
- public function getTimeout()
+ public function getTimeout(): float
{
return $this->timeout;
}
@@ -172,7 +171,7 @@ class SocketHandler extends AbstractProcessingHandler
*
* @return float
*/
- public function getWritingTimeout()
+ public function getWritingTimeout(): float
{
return $this->writingTimeout;
}
@@ -216,7 +215,7 @@ class SocketHandler extends AbstractProcessingHandler
$seconds = floor($this->timeout);
$microseconds = round(($this->timeout - $seconds) * 1e6);
- return stream_set_timeout($this->resource, $seconds, $microseconds);
+ return stream_set_timeout($this->resource, (int) $seconds, (int) $microseconds);
}
/**
diff --git a/src/Monolog/Handler/SqsHandler.php b/src/Monolog/Handler/SqsHandler.php
new file mode 100644
index 0000000..01c70dc
--- /dev/null
+++ b/src/Monolog/Handler/SqsHandler.php
@@ -0,0 +1,53 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Aws\Sqs\SqsClient;
+use Monolog\Logger;
+
+/**
+ * Writes to any sqs queue.
+ *
+ * @author Martijn van Calker <git@amvc.nl>
+ */
+class SqsHandler extends AbstractProcessingHandler
+{
+ /** @var SqsClient */
+ private $client;
+ /** @var string */
+ private $queueUrl;
+
+ public function __construct(SqsClient $sqsClient, $queueUrl, $level = Logger::DEBUG, $bubble = true)
+ {
+ parent::__construct($level, $bubble);
+
+ $this->client = $sqsClient;
+ $this->queueUrl = $queueUrl;
+ }
+
+ /**
+ * Writes the record down to the log of the implementing handler.
+ *
+ * @param array $record
+ */
+ protected function write(array $record)
+ {
+ if (!isset($record['formatted']) || 'string' !== gettype($record['formatted'])) {
+ throw new \InvalidArgumentException('SqsHandler accepts only formatted records as a string');
+ }
+
+ $this->client->sendMessage([
+ 'QueueUrl' => $this->queueUrl,
+ 'MessageBody' => $record['formatted'],
+ ]);
+ }
+}
diff --git a/src/Monolog/Handler/StreamHandler.php b/src/Monolog/Handler/StreamHandler.php
index 09a1573..5abbc59 100644
--- a/src/Monolog/Handler/StreamHandler.php
+++ b/src/Monolog/Handler/StreamHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -22,8 +22,10 @@ use Monolog\Logger;
*/
class StreamHandler extends AbstractProcessingHandler
{
+ /** @var resource|null */
protected $stream;
protected $url;
+ /** @var string|null */
private $errorMessage;
protected $filePermission;
protected $useLocking;
@@ -96,7 +98,7 @@ class StreamHandler extends AbstractProcessingHandler
}
$this->createDir();
$this->errorMessage = null;
- set_error_handler(array($this, 'customErrorHandler'));
+ set_error_handler([$this, 'customErrorHandler']);
$this->stream = fopen($this->url, 'a');
if ($this->filePermission !== null) {
@chmod($this->url, $this->filePermission);
@@ -123,7 +125,7 @@ class StreamHandler extends AbstractProcessingHandler
/**
* Write to stream
* @param resource $stream
- * @param array $record
+ * @param array $record
*/
protected function streamWrite($stream, array $record)
{
@@ -164,7 +166,7 @@ class StreamHandler extends AbstractProcessingHandler
$dir = $this->getDirFromStream($this->url);
if (null !== $dir && !is_dir($dir)) {
$this->errorMessage = null;
- set_error_handler(array($this, 'customErrorHandler'));
+ set_error_handler([$this, 'customErrorHandler']);
$status = mkdir($dir, 0777, true);
restore_error_handler();
if (false === $status) {
diff --git a/src/Monolog/Handler/SwiftMailerHandler.php b/src/Monolog/Handler/SwiftMailerHandler.php
index 72f44a5..3359ac8 100644
--- a/src/Monolog/Handler/SwiftMailerHandler.php
+++ b/src/Monolog/Handler/SwiftMailerHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,6 +13,7 @@ namespace Monolog\Handler;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
+use Swift_Message;
use Swift;
/**
@@ -26,12 +27,12 @@ class SwiftMailerHandler extends MailHandler
private $messageTemplate;
/**
- * @param \Swift_Mailer $mailer The mailer to use
- * @param callable|\Swift_Message $message An example message for real messages, only the body will be replaced
- * @param int $level The minimum logging level at which this handler will be triggered
- * @param Boolean $bubble Whether the messages that are handled can bubble up the stack or not
+ * @param \Swift_Mailer $mailer The mailer to use
+ * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced
+ * @param 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(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, $bubble = true)
+ public function __construct(\Swift_Mailer $mailer, $message, $level = Logger::ERROR, bool $bubble = true)
{
parent::__construct($level, $bubble);
@@ -42,7 +43,7 @@ class SwiftMailerHandler extends MailHandler
/**
* {@inheritdoc}
*/
- protected function send($content, array $records)
+ protected function send(string $content, array $records)
{
$this->mailer->send($this->buildMessage($content, $records));
}
@@ -50,21 +51,21 @@ class SwiftMailerHandler extends MailHandler
/**
* Creates instance of Swift_Message to be sent
*
- * @param string $content formatted email body to be sent
- * @param array $records Log records that formed the content
- * @return \Swift_Message
+ * @param string $content formatted email body to be sent
+ * @param array $records Log records that formed the content
+ * @return Swift_Message
*/
- protected function buildMessage($content, array $records)
+ protected function buildMessage(string $content, array $records): Swift_Message
{
$message = null;
- if ($this->messageTemplate instanceof \Swift_Message) {
+ if ($this->messageTemplate instanceof Swift_Message) {
$message = clone $this->messageTemplate;
$message->generateId();
} elseif (is_callable($this->messageTemplate)) {
$message = call_user_func($this->messageTemplate, $content, $records);
}
- if (!$message instanceof \Swift_Message) {
+ if (!$message instanceof Swift_Message) {
throw new \InvalidArgumentException('Could not resolve message as instance of Swift_Message or a callable returning it');
}
@@ -73,7 +74,12 @@ class SwiftMailerHandler extends MailHandler
$message->setSubject($subjectFormatter->format($this->getHighestRecord($records)));
}
- $message->setBody($content);
+ $mime = null;
+ if ($this->isHtmlBody($content)) {
+ $mime = 'text/html';
+ }
+
+ $message->setBody($content, $mime);
if (version_compare(Swift::VERSION, '6.0.0', '>=')) {
$message->setDate(new \DateTimeImmutable());
} else {
@@ -82,18 +88,4 @@ class SwiftMailerHandler extends MailHandler
return $message;
}
-
- /**
- * BC getter, to be removed in 2.0
- */
- public function __get($name)
- {
- if ($name === 'message') {
- trigger_error('SwiftMailerHandler->message is deprecated, use ->buildMessage() instead to retrieve the message', E_USER_DEPRECATED);
-
- return $this->buildMessage(null, array());
- }
-
- throw new \InvalidArgumentException('Invalid property '.$name);
- }
}
diff --git a/src/Monolog/Handler/SyslogHandler.php b/src/Monolog/Handler/SyslogHandler.php
index 376bc3b..863fc56 100644
--- a/src/Monolog/Handler/SyslogHandler.php
+++ b/src/Monolog/Handler/SyslogHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
diff --git a/src/Monolog/Handler/SyslogUdp/UdpSocket.php b/src/Monolog/Handler/SyslogUdp/UdpSocket.php
index 3bff085..f1801b3 100644
--- a/src/Monolog/Handler/SyslogUdp/UdpSocket.php
+++ b/src/Monolog/Handler/SyslogUdp/UdpSocket.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -17,6 +17,8 @@ class UdpSocket
protected $ip;
protected $port;
+
+ /** @var resource|null */
protected $socket;
public function __construct($ip, $port = 514)
@@ -42,7 +44,7 @@ class UdpSocket
protected function send($chunk)
{
if (!is_resource($this->socket)) {
- throw new \LogicException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
+ throw new \RuntimeException('The UdpSocket to '.$this->ip.':'.$this->port.' has been closed and can not be written to anymore');
}
socket_sendto($this->socket, $chunk, strlen($chunk), $flags = 0, $this->ip, $this->port);
}
diff --git a/src/Monolog/Handler/SyslogUdpHandler.php b/src/Monolog/Handler/SyslogUdpHandler.php
index 4718711..2258f56 100644
--- a/src/Monolog/Handler/SyslogUdpHandler.php
+++ b/src/Monolog/Handler/SyslogUdpHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -57,19 +57,19 @@ class SyslogUdpHandler extends AbstractSyslogHandler
$this->socket->close();
}
- private function splitMessageIntoLines($message)
+ private function splitMessageIntoLines($message): array
{
if (is_array($message)) {
$message = implode("\n", $message);
}
- return preg_split('/$\R?^/m', $message, -1, PREG_SPLIT_NO_EMPTY);
+ return preg_split('/$\R?^/m', (string) $message, -1, PREG_SPLIT_NO_EMPTY);
}
/**
* Make common syslog header (see rfc5424)
*/
- protected function makeCommonSyslogHeader($severity)
+ protected function makeCommonSyslogHeader($severity): string
{
$priority = $severity + $this->facility;
@@ -96,7 +96,7 @@ class SyslogUdpHandler extends AbstractSyslogHandler
/**
* Inject your own socket, mainly used for testing
*/
- public function setSocket($socket)
+ public function setSocket(UdpSocket $socket)
{
$this->socket = $socket;
}
diff --git a/src/Monolog/Handler/TestHandler.php b/src/Monolog/Handler/TestHandler.php
index e39cfc6..3df7b6d 100644
--- a/src/Monolog/Handler/TestHandler.php
+++ b/src/Monolog/Handler/TestHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -65,8 +65,8 @@ namespace Monolog\Handler;
*/
class TestHandler extends AbstractProcessingHandler
{
- protected $records = array();
- protected $recordsByLevel = array();
+ protected $records = [];
+ protected $recordsByLevel = [];
public function getRecords()
{
@@ -75,8 +75,8 @@ class TestHandler extends AbstractProcessingHandler
public function clear()
{
- $this->records = array();
- $this->recordsByLevel = array();
+ $this->records = [];
+ $this->recordsByLevel = [];
}
public function hasRecords($level)
@@ -109,12 +109,8 @@ class TestHandler extends AbstractProcessingHandler
}, $level);
}
- public function hasRecordThatPasses($predicate, $level)
+ public function hasRecordThatPasses(callable $predicate, $level)
{
- if (!is_callable($predicate)) {
- throw new \InvalidArgumentException("Expected a callable for hasRecordThatSucceeds");
- }
-
if (!isset($this->recordsByLevel[$level])) {
return false;
}
@@ -145,7 +141,7 @@ class TestHandler extends AbstractProcessingHandler
if (method_exists($this, $genericMethod)) {
$args[] = $level;
- return call_user_func_array(array($this, $genericMethod), $args);
+ return call_user_func_array([$this, $genericMethod], $args);
}
}
diff --git a/src/Monolog/Handler/WhatFailureGroupHandler.php b/src/Monolog/Handler/WhatFailureGroupHandler.php
index 2732ba3..42c2336 100644
--- a/src/Monolog/Handler/WhatFailureGroupHandler.php
+++ b/src/Monolog/Handler/WhatFailureGroupHandler.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -22,7 +22,7 @@ class WhatFailureGroupHandler extends GroupHandler
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
if ($this->processors) {
foreach ($this->processors as $processor) {
@@ -33,8 +33,6 @@ class WhatFailureGroupHandler extends GroupHandler
foreach ($this->handlers as $handler) {
try {
$handler->handle($record);
- } catch (\Exception $e) {
- // What failure?
} catch (\Throwable $e) {
// What failure?
}
@@ -51,8 +49,6 @@ class WhatFailureGroupHandler extends GroupHandler
foreach ($this->handlers as $handler) {
try {
$handler->handleBatch($records);
- } catch (\Exception $e) {
- // What failure?
} catch (\Throwable $e) {
// What failure?
}
diff --git a/src/Monolog/Handler/ZendMonitorHandler.php b/src/Monolog/Handler/ZendMonitorHandler.php
index f22cf21..c0bceb4 100644
--- a/src/Monolog/Handler/ZendMonitorHandler.php
+++ b/src/Monolog/Handler/ZendMonitorHandler.php
@@ -1,4 +1,5 @@
-<?php
+<?php declare(strict_types=1);
+
/*
* This file is part of the Monolog package.
*
@@ -10,6 +11,7 @@
namespace Monolog\Handler;
+use Monolog\Formatter\FormatterInterface;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Logger;
@@ -25,7 +27,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
*
* @var array
*/
- protected $levelMap = array(
+ protected $levelMap = [
Logger::DEBUG => 1,
Logger::INFO => 2,
Logger::NOTICE => 3,
@@ -34,7 +36,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
Logger::CRITICAL => 6,
Logger::ALERT => 7,
Logger::EMERGENCY => 0,
- );
+ ];
/**
* Construct
@@ -78,7 +80,7 @@ class ZendMonitorHandler extends AbstractProcessingHandler
/**
* {@inheritdoc}
*/
- public function getDefaultFormatter()
+ public function getDefaultFormatter(): FormatterInterface
{
return new NormalizerFormatter();
}
diff --git a/src/Monolog/Logger.php b/src/Monolog/Logger.php
index 49d00af..88ecf0d 100644
--- a/src/Monolog/Logger.php
+++ b/src/Monolog/Logger.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,8 +11,8 @@
namespace Monolog;
+use DateTimeZone;
use Monolog\Handler\HandlerInterface;
-use Monolog\Handler\StreamHandler;
use Psr\Log\LoggerInterface;
use Psr\Log\InvalidArgumentException;
@@ -84,14 +84,16 @@ class Logger implements LoggerInterface
*
* @var int
*/
- const API = 1;
+ const API = 2;
/**
* Logging levels from syslog protocol defined in RFC 5424
*
- * @var array $levels Logging levels
+ * This is a static variable and not a constant to serve as an extension point for custom levels
+ *
+ * @var string[] $levels Logging levels with the levels as key
*/
- protected static $levels = array(
+ protected static $levels = [
self::DEBUG => 'DEBUG',
self::INFO => 'INFO',
self::NOTICE => 'NOTICE',
@@ -100,12 +102,7 @@ class Logger implements LoggerInterface
self::CRITICAL => 'CRITICAL',
self::ALERT => 'ALERT',
self::EMERGENCY => 'EMERGENCY',
- );
-
- /**
- * @var \DateTimeZone
- */
- protected static $timezone;
+ ];
/**
* @var string
@@ -134,31 +131,33 @@ class Logger implements LoggerInterface
protected $microsecondTimestamps = true;
/**
- * @param string $name The logging channel
+ * @var DateTimeZone
+ */
+ protected $timezone;
+
+ /**
+ * @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
*/
- public function __construct($name, array $handlers = array(), array $processors = array())
+ public function __construct(string $name, array $handlers = [], array $processors = [], DateTimeZone $timezone = null)
{
$this->name = $name;
$this->handlers = $handlers;
$this->processors = $processors;
+ $this->timezone = $timezone ?: new DateTimeZone(date_default_timezone_get() ?: 'UTC');
}
- /**
- * @return string
- */
- public function getName()
+ public function getName(): string
{
return $this->name;
}
/**
* Return a new cloned instance with the name changed
- *
- * @return static
*/
- public function withName($name)
+ public function withName(string $name): self
{
$new = clone $this;
$new->name = $name;
@@ -168,11 +167,8 @@ class Logger implements LoggerInterface
/**
* Pushes a handler on to the stack.
- *
- * @param HandlerInterface $handler
- * @return $this
*/
- public function pushHandler(HandlerInterface $handler)
+ public function pushHandler(HandlerInterface $handler): self
{
array_unshift($this->handlers, $handler);
@@ -182,9 +178,9 @@ class Logger implements LoggerInterface
/**
* Pops a handler from the stack
*
- * @return HandlerInterface
+ * @throws \LogicException If empty handler stack
*/
- public function popHandler()
+ public function popHandler(): HandlerInterface
{
if (!$this->handlers) {
throw new \LogicException('You tried to pop from an empty handler stack.');
@@ -198,12 +194,11 @@ class Logger implements LoggerInterface
*
* If a map is passed, keys will be ignored.
*
- * @param HandlerInterface[] $handlers
- * @return $this
+ * @param HandlerInterface[] $handlers
*/
- public function setHandlers(array $handlers)
+ public function setHandlers(array $handlers): self
{
- $this->handlers = array();
+ $this->handlers = [];
foreach (array_reverse($handlers) as $handler) {
$this->pushHandler($handler);
}
@@ -214,22 +209,16 @@ class Logger implements LoggerInterface
/**
* @return HandlerInterface[]
*/
- public function getHandlers()
+ public function getHandlers(): array
{
return $this->handlers;
}
/**
* Adds a processor on to the stack.
- *
- * @param callable $callback
- * @return $this
*/
- public function pushProcessor($callback)
+ public function pushProcessor(callable $callback): self
{
- if (!is_callable($callback)) {
- throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
- }
array_unshift($this->processors, $callback);
return $this;
@@ -238,9 +227,10 @@ class Logger implements LoggerInterface
/**
* Removes the processor on top of the stack and returns it.
*
+ * @throws \LogicException If empty processor stack
* @return callable
*/
- public function popProcessor()
+ public function popProcessor(): callable
{
if (!$this->processors) {
throw new \LogicException('You tried to pop from an empty processor stack.');
@@ -252,7 +242,7 @@ class Logger implements LoggerInterface
/**
* @return callable[]
*/
- public function getProcessors()
+ public function getProcessors(): array
{
return $this->processors;
}
@@ -261,18 +251,22 @@ class Logger implements LoggerInterface
* Control the use of microsecond resolution timestamps in the 'datetime'
* member of new records.
*
- * Generating microsecond resolution timestamps by calling
+ * On PHP7.0, generating microsecond resolution timestamps by calling
* microtime(true), formatting the result via sprintf() and then parsing
* the resulting string via \DateTime::createFromFormat() can incur
* a measurable runtime overhead vs simple usage of DateTime to capture
* a second resolution timestamp in systems which generate a large number
* of log events.
*
+ * On PHP7.1 however microseconds are always included by the engine, so
+ * this setting can be left alone unless you really want to suppress
+ * microseconds in the output.
+ *
* @param bool $micro True to use microtime() to create timestamps
*/
- public function useMicrosecondTimestamps($micro)
+ public function useMicrosecondTimestamps(bool $micro)
{
- $this->microsecondTimestamps = (bool) $micro;
+ $this->microsecondTimestamps = $micro;
}
/**
@@ -283,56 +277,43 @@ class Logger implements LoggerInterface
* @param array $context The log context
* @return Boolean Whether the record has been processed
*/
- public function addRecord($level, $message, array $context = array())
+ public function addRecord(int $level, string $message, array $context = []): bool
{
- if (!$this->handlers) {
- $this->pushHandler(new StreamHandler('php://stderr', static::DEBUG));
- }
-
- $levelName = static::getLevelName($level);
-
// check if any handler will handle this message so we can return early and save cycles
$handlerKey = null;
- reset($this->handlers);
- while ($handler = current($this->handlers)) {
- if ($handler->isHandling(array('level' => $level))) {
- $handlerKey = key($this->handlers);
+ foreach ($this->handlers as $key => $handler) {
+ if ($handler->isHandling(['level' => $level])) {
+ $handlerKey = $key;
break;
}
-
- next($this->handlers);
}
if (null === $handlerKey) {
return false;
}
- if (!static::$timezone) {
- static::$timezone = new \DateTimeZone(date_default_timezone_get() ?: 'UTC');
- }
-
- // php7.1+ always has microseconds enabled, so we do not need this hack
- if ($this->microsecondTimestamps && PHP_VERSION_ID < 70100) {
- $ts = \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true)), static::$timezone);
- } else {
- $ts = new \DateTime(null, static::$timezone);
- }
- $ts->setTimezone(static::$timezone);
+ $levelName = static::getLevelName($level);
- $record = array(
- 'message' => (string) $message,
+ $record = [
+ 'message' => $message,
'context' => $context,
'level' => $level,
'level_name' => $levelName,
'channel' => $this->name,
- 'datetime' => $ts,
- 'extra' => array(),
- );
+ 'datetime' => new DateTimeImmutable($this->microsecondTimestamps, $this->timezone),
+ 'extra' => [],
+ ];
foreach ($this->processors as $processor) {
$record = call_user_func($processor, $record);
}
+ // advance the array pointer to the first handler that will handle this record
+ reset($this->handlers);
+ while ($handlerKey !== key($this->handlers)) {
+ next($this->handlers);
+ }
+
while ($handler = current($this->handlers)) {
if (true === $handler->handle($record)) {
break;
@@ -345,107 +326,11 @@ class Logger implements LoggerInterface
}
/**
- * Adds a log record at the DEBUG level.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function addDebug($message, array $context = array())
- {
- return $this->addRecord(static::DEBUG, $message, $context);
- }
-
- /**
- * Adds a log record at the INFO level.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function addInfo($message, array $context = array())
- {
- return $this->addRecord(static::INFO, $message, $context);
- }
-
- /**
- * Adds a log record at the NOTICE level.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function addNotice($message, array $context = array())
- {
- return $this->addRecord(static::NOTICE, $message, $context);
- }
-
- /**
- * Adds a log record at the WARNING level.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function addWarning($message, array $context = array())
- {
- return $this->addRecord(static::WARNING, $message, $context);
- }
-
- /**
- * Adds a log record at the ERROR level.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function addError($message, array $context = array())
- {
- return $this->addRecord(static::ERROR, $message, $context);
- }
-
- /**
- * Adds a log record at the CRITICAL level.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function addCritical($message, array $context = array())
- {
- return $this->addRecord(static::CRITICAL, $message, $context);
- }
-
- /**
- * Adds a log record at the ALERT level.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function addAlert($message, array $context = array())
- {
- return $this->addRecord(static::ALERT, $message, $context);
- }
-
- /**
- * Adds a log record at the EMERGENCY level.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function addEmergency($message, array $context = array())
- {
- return $this->addRecord(static::EMERGENCY, $message, $context);
- }
-
- /**
* Gets all supported logging levels.
*
* @return array Assoc array with human-readable level names => level codes.
*/
- public static function getLevels()
+ public static function getLevels(): array
{
return array_flip(static::$levels);
}
@@ -453,10 +338,11 @@ class Logger implements LoggerInterface
/**
* Gets the name of the logging level.
*
- * @param int $level
+ * @param int $level
+ * @throws \Psr\Log\InvalidArgumentException If level is not defined
* @return string
*/
- public static function getLevelName($level)
+ public static function getLevelName(int $level): string
{
if (!isset(static::$levels[$level])) {
throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
@@ -469,12 +355,17 @@ class Logger implements LoggerInterface
* Converts PSR-3 levels to Monolog ones if necessary
*
* @param string|int Level number (monolog) or name (PSR-3)
+ * @throws \Psr\Log\InvalidArgumentException If level is not defined
* @return int
*/
- public static function toMonologLevel($level)
+ public static function toMonologLevel($level): int
{
- if (is_string($level) && defined(__CLASS__.'::'.strtoupper($level))) {
- return constant(__CLASS__.'::'.strtoupper($level));
+ if (is_string($level)) {
+ if (defined(__CLASS__.'::'.strtoupper($level))) {
+ return constant(__CLASS__.'::'.strtoupper($level));
+ }
+
+ throw new InvalidArgumentException('Level "'.$level.'" is not defined, use one of: '.implode(', ', array_keys(static::$levels)));
}
return $level;
@@ -486,11 +377,11 @@ class Logger implements LoggerInterface
* @param int $level
* @return Boolean
*/
- public function isHandling($level)
+ public function isHandling(int $level): bool
{
- $record = array(
+ $record = [
'level' => $level,
- );
+ ];
foreach ($this->handlers as $handler) {
if ($handler->isHandling($record)) {
@@ -506,16 +397,15 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param mixed $level The log level
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param mixed $level The log level
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function log($level, $message, array $context = array())
+ public function log($level, $message, array $context = [])
{
$level = static::toMonologLevel($level);
- return $this->addRecord($level, $message, $context);
+ $this->addRecord($level, (string) $message, $context);
}
/**
@@ -523,13 +413,12 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function debug($message, array $context = array())
+ public function debug($message, array $context = [])
{
- return $this->addRecord(static::DEBUG, $message, $context);
+ $this->addRecord(static::DEBUG, (string) $message, $context);
}
/**
@@ -537,13 +426,12 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function info($message, array $context = array())
+ public function info($message, array $context = [])
{
- return $this->addRecord(static::INFO, $message, $context);
+ $this->addRecord(static::INFO, (string) $message, $context);
}
/**
@@ -551,13 +439,12 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function notice($message, array $context = array())
+ public function notice($message, array $context = [])
{
- return $this->addRecord(static::NOTICE, $message, $context);
+ $this->addRecord(static::NOTICE, (string) $message, $context);
}
/**
@@ -565,41 +452,12 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function warn($message, array $context = array())
- {
- return $this->addRecord(static::WARNING, $message, $context);
- }
-
- /**
- * Adds a log record at the WARNING level.
- *
- * This method allows for compatibility with common interfaces.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function warning($message, array $context = array())
- {
- return $this->addRecord(static::WARNING, $message, $context);
- }
-
- /**
- * Adds a log record at the ERROR level.
- *
- * This method allows for compatibility with common interfaces.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function err($message, array $context = array())
+ public function warning($message, array $context = [])
{
- return $this->addRecord(static::ERROR, $message, $context);
+ $this->addRecord(static::WARNING, (string) $message, $context);
}
/**
@@ -607,13 +465,12 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function error($message, array $context = array())
+ public function error($message, array $context = [])
{
- return $this->addRecord(static::ERROR, $message, $context);
+ $this->addRecord(static::ERROR, (string) $message, $context);
}
/**
@@ -621,27 +478,12 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function crit($message, array $context = array())
+ public function critical($message, array $context = [])
{
- return $this->addRecord(static::CRITICAL, $message, $context);
- }
-
- /**
- * Adds a log record at the CRITICAL level.
- *
- * This method allows for compatibility with common interfaces.
- *
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
- */
- public function critical($message, array $context = array())
- {
- return $this->addRecord(static::CRITICAL, $message, $context);
+ $this->addRecord(static::CRITICAL, (string) $message, $context);
}
/**
@@ -649,13 +491,12 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function alert($message, array $context = array())
+ public function alert($message, array $context = [])
{
- return $this->addRecord(static::ALERT, $message, $context);
+ $this->addRecord(static::ALERT, (string) $message, $context);
}
/**
@@ -663,38 +504,33 @@ class Logger implements LoggerInterface
*
* This method allows for compatibility with common interfaces.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param string $message The log message
+ * @param array $context The log context
*/
- public function emerg($message, array $context = array())
+ public function emergency($message, array $context = [])
{
- return $this->addRecord(static::EMERGENCY, $message, $context);
+ $this->addRecord(static::EMERGENCY, (string) $message, $context);
}
/**
- * Adds a log record at the EMERGENCY level.
- *
- * This method allows for compatibility with common interfaces.
+ * Set the timezone to be used for the timestamp of log records.
*
- * @param string $message The log message
- * @param array $context The log context
- * @return Boolean Whether the record has been processed
+ * @param DateTimeZone $tz Timezone object
*/
- public function emergency($message, array $context = array())
+ public function setTimezone(DateTimeZone $tz): self
{
- return $this->addRecord(static::EMERGENCY, $message, $context);
+ $this->timezone = $tz;
+
+ return $this;
}
/**
* Set the timezone to be used for the timestamp of log records.
*
- * This is stored globally for all Logger instances
- *
- * @param \DateTimeZone $tz Timezone object
+ * @return DateTimeZone
*/
- public static function setTimezone(\DateTimeZone $tz)
+ public function getTimezone(): DateTimeZone
{
- self::$timezone = $tz;
+ return $this->timezone;
}
}
diff --git a/src/Monolog/Processor/GitProcessor.php b/src/Monolog/Processor/GitProcessor.php
index 1899400..9eec186 100644
--- a/src/Monolog/Processor/GitProcessor.php
+++ b/src/Monolog/Processor/GitProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -29,11 +29,7 @@ class GitProcessor
$this->level = Logger::toMonologLevel($level);
}
- /**
- * @param array $record
- * @return array
- */
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
// return if the level is not high enough
if ($record['level'] < $this->level) {
@@ -45,7 +41,7 @@ class GitProcessor
return $record;
}
- private static function getGitInfo()
+ private static function getGitInfo(): array
{
if (self::$cache) {
return self::$cache;
@@ -53,12 +49,12 @@ class GitProcessor
$branches = `git branch -v --no-abbrev`;
if (preg_match('{^\* (.+?)\s+([a-f0-9]{40})(?:\s|$)}m', $branches, $matches)) {
- return self::$cache = array(
+ return self::$cache = [
'branch' => $matches[1],
'commit' => $matches[2],
- );
+ ];
}
- return self::$cache = array();
+ return self::$cache = [];
}
}
diff --git a/src/Monolog/Processor/IntrospectionProcessor.php b/src/Monolog/Processor/IntrospectionProcessor.php
index 2c07cae..3a27529 100644
--- a/src/Monolog/Processor/IntrospectionProcessor.php
+++ b/src/Monolog/Processor/IntrospectionProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -32,23 +32,19 @@ class IntrospectionProcessor
private $skipStackFramesCount;
- private $skipFunctions = array(
+ private $skipFunctions = [
'call_user_func',
'call_user_func_array',
- );
+ ];
- public function __construct($level = Logger::DEBUG, array $skipClassesPartials = array(), $skipStackFramesCount = 0)
+ public function __construct($level = Logger::DEBUG, array $skipClassesPartials = [], int $skipStackFramesCount = 0)
{
$this->level = Logger::toMonologLevel($level);
- $this->skipClassesPartials = array_merge(array('Monolog\\'), $skipClassesPartials);
+ $this->skipClassesPartials = array_merge(['Monolog\\'], $skipClassesPartials);
$this->skipStackFramesCount = $skipStackFramesCount;
}
- /**
- * @param array $record
- * @return array
- */
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
// return if the level is not high enough
if ($record['level'] < $this->level) {
@@ -90,18 +86,18 @@ class IntrospectionProcessor
// we should have the call source now
$record['extra'] = array_merge(
$record['extra'],
- array(
+ [
'file' => isset($trace[$i - 1]['file']) ? $trace[$i - 1]['file'] : null,
'line' => isset($trace[$i - 1]['line']) ? $trace[$i - 1]['line'] : null,
'class' => isset($trace[$i]['class']) ? $trace[$i]['class'] : null,
'function' => isset($trace[$i]['function']) ? $trace[$i]['function'] : null,
- )
+ ]
);
return $record;
}
- private function isTraceClassOrSkippedFunction(array $trace, $index)
+ private function isTraceClassOrSkippedFunction(array $trace, int $index)
{
if (!isset($trace[$index])) {
return false;
diff --git a/src/Monolog/Processor/MemoryPeakUsageProcessor.php b/src/Monolog/Processor/MemoryPeakUsageProcessor.php
index 0543e92..b6f8acc 100644
--- a/src/Monolog/Processor/MemoryPeakUsageProcessor.php
+++ b/src/Monolog/Processor/MemoryPeakUsageProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -19,11 +19,7 @@ namespace Monolog\Processor;
*/
class MemoryPeakUsageProcessor extends MemoryProcessor
{
- /**
- * @param array $record
- * @return array
- */
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
$bytes = memory_get_peak_usage($this->realUsage);
$formatted = $this->formatBytes($bytes);
diff --git a/src/Monolog/Processor/MemoryProcessor.php b/src/Monolog/Processor/MemoryProcessor.php
index 85f9dc5..5b06c2e 100644
--- a/src/Monolog/Processor/MemoryProcessor.php
+++ b/src/Monolog/Processor/MemoryProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -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 $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->useFormatting = (boolean) $useFormatting;
+ $this->realUsage = $realUsage;
+ $this->useFormatting = $useFormatting;
}
/**
* Formats bytes into a human readable string if $this->useFormatting is true, otherwise return $bytes as is
*
* @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) {
return $bytes;
}
diff --git a/src/Monolog/Processor/MemoryUsageProcessor.php b/src/Monolog/Processor/MemoryUsageProcessor.php
index 2783d65..31c9396 100644
--- a/src/Monolog/Processor/MemoryUsageProcessor.php
+++ b/src/Monolog/Processor/MemoryUsageProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -19,11 +19,7 @@ namespace Monolog\Processor;
*/
class MemoryUsageProcessor extends MemoryProcessor
{
- /**
- * @param array $record
- * @return array
- */
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
$bytes = memory_get_usage($this->realUsage);
$formatted = $this->formatBytes($bytes);
diff --git a/src/Monolog/Processor/MercurialProcessor.php b/src/Monolog/Processor/MercurialProcessor.php
index 7c07a7e..6ab5bba 100644
--- a/src/Monolog/Processor/MercurialProcessor.php
+++ b/src/Monolog/Processor/MercurialProcessor.php
@@ -1,9 +1,9 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
- * (c) Jonathan A. Schweder <jonathanschweder@gmail.com>
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -28,11 +28,7 @@ class MercurialProcessor
$this->level = Logger::toMonologLevel($level);
}
- /**
- * @param array $record
- * @return array
- */
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
// return if the level is not high enough
if ($record['level'] < $this->level) {
@@ -44,20 +40,21 @@ class MercurialProcessor
return $record;
}
- private static function getMercurialInfo()
+ private static function getMercurialInfo(): array
{
if (self::$cache) {
return self::$cache;
}
$result = explode(' ', trim(`hg id -nb`));
+
if (count($result) >= 3) {
- return self::$cache = array(
+ return self::$cache = [
'branch' => $result[1],
'revision' => $result[2],
- );
+ ];
}
- return self::$cache = array();
+ return self::$cache = [];
}
}
diff --git a/src/Monolog/Processor/ProcessIdProcessor.php b/src/Monolog/Processor/ProcessIdProcessor.php
index 9d3f559..392bd13 100644
--- a/src/Monolog/Processor/ProcessIdProcessor.php
+++ b/src/Monolog/Processor/ProcessIdProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -18,11 +18,7 @@ namespace Monolog\Processor;
*/
class ProcessIdProcessor
{
- /**
- * @param array $record
- * @return array
- */
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
$record['extra']['process_id'] = getmypid();
diff --git a/src/Monolog/Processor/PsrLogMessageProcessor.php b/src/Monolog/Processor/PsrLogMessageProcessor.php
index c2686ce..8078403 100644
--- a/src/Monolog/Processor/PsrLogMessageProcessor.php
+++ b/src/Monolog/Processor/PsrLogMessageProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -20,20 +20,34 @@ namespace Monolog\Processor;
*/
class PsrLogMessageProcessor
{
+ const SIMPLE_DATE = "Y-m-d\TH:i:sP";
+
+ private $dateFormat;
+
+ /**
+ * @param string $dateFormat The format of the timestamp: one supported by DateTime::format
+ */
+ public function __construct(string $dateFormat = null)
+ {
+ $this->dateFormat = null === $dateFormat ? static::SIMPLE_DATE : $dateFormat;
+ }
+
/**
* @param array $record
* @return array
*/
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
if (false === strpos($record['message'], '{')) {
return $record;
}
- $replacements = array();
+ $replacements = [];
foreach ($record['context'] as $key => $val) {
if (is_null($val) || is_scalar($val) || (is_object($val) && method_exists($val, "__toString"))) {
$replacements['{'.$key.'}'] = $val;
+ } elseif ($val instanceof \DateTimeInterface) {
+ $replacements['{'.$key.'}'] = $val->format($this->dateFormat);
} elseif (is_object($val)) {
$replacements['{'.$key.'}'] = '[object '.get_class($val).']';
} else {
diff --git a/src/Monolog/Processor/TagProcessor.php b/src/Monolog/Processor/TagProcessor.php
index 7e2df2a..6371986 100644
--- a/src/Monolog/Processor/TagProcessor.php
+++ b/src/Monolog/Processor/TagProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -20,22 +20,22 @@ class TagProcessor
{
private $tags;
- public function __construct(array $tags = array())
+ public function __construct(array $tags = [])
{
$this->setTags($tags);
}
- public function addTags(array $tags = array())
+ public function addTags(array $tags = [])
{
$this->tags = array_merge($this->tags, $tags);
}
- public function setTags(array $tags = array())
+ public function setTags(array $tags = [])
{
$this->tags = $tags;
}
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
$record['extra']['tags'] = $this->tags;
diff --git a/src/Monolog/Processor/UidProcessor.php b/src/Monolog/Processor/UidProcessor.php
index 812707c..601171b 100644
--- a/src/Monolog/Processor/UidProcessor.php
+++ b/src/Monolog/Processor/UidProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -20,16 +20,16 @@ class UidProcessor
{
private $uid;
- public function __construct($length = 7)
+ public function __construct(int $length = 7)
{
if (!is_int($length) || $length > 32 || $length < 1) {
throw new \InvalidArgumentException('The uid length must be an integer between 1 and 32');
}
- $this->uid = substr(hash('md5', uniqid('', true)), 0, $length);
+ $this->uid = substr(bin2hex(random_bytes((int) ceil($length / 2))), 0, $length);
}
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
$record['extra']['uid'] = $this->uid;
@@ -39,7 +39,7 @@ class UidProcessor
/**
* @return string
*/
- public function getUid()
+ public function getUid(): string
{
return $this->uid;
}
diff --git a/src/Monolog/Processor/WebProcessor.php b/src/Monolog/Processor/WebProcessor.php
index ea1d897..37324af 100644
--- a/src/Monolog/Processor/WebProcessor.php
+++ b/src/Monolog/Processor/WebProcessor.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -30,13 +30,13 @@ class WebProcessor
*
* @var array
*/
- protected $extraFields = array(
+ protected $extraFields = [
'url' => 'REQUEST_URI',
'ip' => 'REMOTE_ADDR',
'http_method' => 'REQUEST_METHOD',
'server' => 'SERVER_NAME',
'referrer' => 'HTTP_REFERER',
- );
+ ];
/**
* @param array|\ArrayAccess $serverData Array or object w/ ArrayAccess that provides access to the $_SERVER data
@@ -65,11 +65,7 @@ class WebProcessor
}
}
- /**
- * @param array $record
- * @return array
- */
- public function __invoke(array $record)
+ public function __invoke(array $record): array
{
// skip processing if for some reason request data
// is not present (CLI or wonky SAPIs)
@@ -82,26 +78,17 @@ class WebProcessor
return $record;
}
- /**
- * @param string $extraName
- * @param string $serverName
- * @return $this
- */
- public function addExtraField($extraName, $serverName)
+ public function addExtraField(string $extraName, string $serverName): self
{
$this->extraFields[$extraName] = $serverName;
return $this;
}
- /**
- * @param array $extra
- * @return array
- */
- private function appendExtraFields(array $extra)
+ private function appendExtraFields(array $extra): array
{
foreach ($this->extraFields as $extraName => $serverName) {
- $extra[$extraName] = isset($this->serverData[$serverName]) ? $this->serverData[$serverName] : null;
+ $extra[$extraName] = $this->serverData[$serverName] ?? null;
}
if (isset($this->serverData['UNIQUE_ID'])) {
diff --git a/src/Monolog/Registry.php b/src/Monolog/Registry.php
index 159b751..99a4344 100644
--- a/src/Monolog/Registry.php
+++ b/src/Monolog/Registry.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -28,8 +28,8 @@ use InvalidArgumentException;
*
* function testLogger()
* {
- * Monolog\Registry::api()->addError('Sent to $api Logger instance');
- * Monolog\Registry::application()->addError('Sent to $application Logger instance');
+ * Monolog\Registry::api()->error('Sent to $api Logger instance');
+ * Monolog\Registry::application()->error('Sent to $application Logger instance');
* }
* </code>
*
@@ -42,7 +42,7 @@ class Registry
*
* @var Logger[]
*/
- private static $loggers = array();
+ private static $loggers = [];
/**
* Adds new logging channel to the registry
@@ -68,15 +68,15 @@ class Registry
*
* @param string|Logger $logger Name or logger instance
*/
- public static function hasLogger($logger)
+ public static function hasLogger($logger): bool
{
if ($logger instanceof Logger) {
$index = array_search($logger, self::$loggers, true);
return false !== $index;
- } else {
- return isset(self::$loggers[$logger]);
}
+
+ return isset(self::$loggers[$logger]);
}
/**
@@ -100,7 +100,7 @@ class Registry
*/
public static function clear()
{
- self::$loggers = array();
+ self::$loggers = [];
}
/**
@@ -108,9 +108,8 @@ class Registry
*
* @param string $name Name of the requested Logger instance
* @throws \InvalidArgumentException If named Logger instance is not in the registry
- * @return Logger Requested instance of Logger
*/
- public static function getInstance($name)
+ public static function getInstance($name): Logger
{
if (!isset(self::$loggers[$name])) {
throw new InvalidArgumentException(sprintf('Requested "%s" logger instance is not in the registry', $name));
diff --git a/tests/Monolog/TestCase.php b/src/Monolog/Test/TestCase.php
index 4eb7b4c..23cf9ad 100644
--- a/tests/Monolog/TestCase.php
+++ b/src/Monolog/Test/TestCase.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -9,24 +9,33 @@
* file that was distributed with this source code.
*/
-namespace Monolog;
+namespace Monolog\Test;
-class TestCase extends \PHPUnit_Framework_TestCase
+use Monolog\Logger;
+use Monolog\DateTimeImmutable;
+use Monolog\Formatter\FormatterInterface;
+
+/**
+ * Lets you easily generate log records and a dummy formatter for testing purposes
+ * *
+ * @author Jordi Boggiano <j.boggiano@seld.be>
+ */
+class TestCase extends \PHPUnit\Framework\TestCase
{
/**
* @return array Record
*/
- protected function getRecord($level = Logger::WARNING, $message = 'test', $context = array())
+ protected function getRecord($level = Logger::WARNING, $message = 'test', $context = [])
{
- return array(
+ return [
'message' => $message,
'context' => $context,
'level' => $level,
'level_name' => Logger::getLevelName($level),
'channel' => 'test',
- 'datetime' => \DateTime::createFromFormat('U.u', sprintf('%.6F', microtime(true))),
- 'extra' => array(),
- );
+ 'datetime' => new DateTimeImmutable(true),
+ 'extra' => [],
+ ];
}
/**
@@ -34,24 +43,23 @@ class TestCase extends \PHPUnit_Framework_TestCase
*/
protected function getMultipleRecords()
{
- return array(
+ return [
$this->getRecord(Logger::DEBUG, 'debug message 1'),
$this->getRecord(Logger::DEBUG, 'debug message 2'),
$this->getRecord(Logger::INFO, 'information'),
$this->getRecord(Logger::WARNING, 'warning'),
$this->getRecord(Logger::ERROR, 'error'),
- );
+ ];
}
- /**
- * @return Monolog\Formatter\FormatterInterface
- */
- protected function getIdentityFormatter()
+ protected function getIdentityFormatter(): FormatterInterface
{
- $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
+ $formatter = $this->createMock(FormatterInterface::class);
$formatter->expects($this->any())
->method('format')
- ->will($this->returnCallback(function ($record) { return $record['message']; }));
+ ->will($this->returnCallback(function ($record) {
+ return $record['message'];
+ }));
return $formatter;
}
diff --git a/tests/Monolog/ErrorHandlerTest.php b/tests/Monolog/ErrorHandlerTest.php
index a9a3f30..9a8a5be 100644
--- a/tests/Monolog/ErrorHandlerTest.php
+++ b/tests/Monolog/ErrorHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,20 +12,118 @@
namespace Monolog;
use Monolog\Handler\TestHandler;
+use Psr\Log\LogLevel;
-class ErrorHandlerTest extends \PHPUnit_Framework_TestCase
+class ErrorHandlerTest extends \PHPUnit\Framework\TestCase
{
+ public function testRegister()
+ {
+ $logger = new Logger('test', [$handler = new TestHandler]);
+
+ $this->assertInstanceOf(ErrorHandler::class, ErrorHandler::register($logger, false, false, false));
+ }
+
public function testHandleError()
{
- $logger = new Logger('test', array($handler = new TestHandler));
+ $logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new ErrorHandler($logger);
- $errHandler->registerErrorHandler(array(E_USER_NOTICE => Logger::EMERGENCY), false);
+ $resHandler = $errHandler->registerErrorHandler([E_USER_NOTICE => Logger::EMERGENCY], false);
+ $this->assertSame($errHandler, $resHandler);
trigger_error('Foo', E_USER_ERROR);
$this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasErrorRecords());
trigger_error('Foo', E_USER_NOTICE);
$this->assertCount(2, $handler->getRecords());
$this->assertTrue($handler->hasEmergencyRecords());
+
+ $errHandler->registerErrorHandler([], true);
+ $prop = $this->getPrivatePropertyValue($errHandler, 'previousErrorHandler');
+ $this->assertTrue(is_callable($prop));
}
+
+ public function fatalHandlerProvider()
+ {
+ return [
+ [null, 10, str_repeat(' ', 1024 * 10), null],
+ [E_ALL, 15, str_repeat(' ', 1024 * 15), E_ALL],
+ ];
+ }
+
+ protected function getPrivatePropertyValue($instance, $property)
+ {
+ $ref = new \ReflectionClass(get_class($instance));
+ $prop = $ref->getProperty($property);
+ $prop->setAccessible(true);
+
+ return $prop->getValue($instance);
+ }
+
+ /**
+ * @dataProvider fatalHandlerProvider
+ */
+ public function testFatalHandler(
+ $level,
+ $reservedMemorySize,
+ $expectedReservedMemory,
+ $expectedFatalLevel
+ ) {
+ $logger = new Logger('test', [$handler = new TestHandler]);
+ $errHandler = new ErrorHandler($logger);
+ $res = $errHandler->registerFatalHandler($level, $reservedMemorySize);
+
+ $this->assertSame($res, $errHandler);
+ $this->assertTrue($this->getPrivatePropertyValue($errHandler, 'hasFatalErrorHandler'));
+ $this->assertEquals($expectedReservedMemory, $this->getPrivatePropertyValue($errHandler, 'reservedMemory'));
+ $this->assertEquals($expectedFatalLevel, $this->getPrivatePropertyValue($errHandler, 'fatalLevel'));
+ }
+
+ public function testHandleException()
+ {
+ $logger = new Logger('test', [$handler = new TestHandler]);
+ $errHandler = new ErrorHandler($logger);
+
+ $resHandler = $errHandler->registerExceptionHandler($map = ['Monolog\CustomTestException' => LogLevel::DEBUG, 'TypeError' => LogLevel::NOTICE, 'Throwable' => LogLevel::WARNING], false);
+ $this->assertSame($errHandler, $resHandler);
+
+ $map['ParseError'] = LogLevel::CRITICAL;
+ $prop = $this->getPrivatePropertyValue($errHandler, 'uncaughtExceptionLevelMap');
+ $this->assertSame($map, $prop);
+
+ $errHandler->registerExceptionHandler([], true);
+ $prop = $this->getPrivatePropertyValue($errHandler, 'previousExceptionHandler');
+ $this->assertTrue(is_callable($prop));
+ }
+
+ public function testCodeToString()
+ {
+ $method = new \ReflectionMethod(ErrorHandler::class, 'codeToString');
+ $method->setAccessible(true);
+
+ $this->assertEquals('E_ERROR', $method->invokeArgs(null, [E_ERROR]));
+ $this->assertEquals('E_WARNING', $method->invokeArgs(null, [E_WARNING]));
+ $this->assertEquals('E_PARSE', $method->invokeArgs(null, [E_PARSE]));
+ $this->assertEquals('E_NOTICE', $method->invokeArgs(null, [E_NOTICE]));
+ $this->assertEquals('E_CORE_ERROR', $method->invokeArgs(null, [E_CORE_ERROR]));
+ $this->assertEquals('E_CORE_WARNING', $method->invokeArgs(null, [E_CORE_WARNING]));
+ $this->assertEquals('E_COMPILE_ERROR', $method->invokeArgs(null, [E_COMPILE_ERROR]));
+ $this->assertEquals('E_COMPILE_WARNING', $method->invokeArgs(null, [E_COMPILE_WARNING]));
+ $this->assertEquals('E_USER_ERROR', $method->invokeArgs(null, [E_USER_ERROR]));
+ $this->assertEquals('E_USER_WARNING', $method->invokeArgs(null, [E_USER_WARNING]));
+ $this->assertEquals('E_USER_NOTICE', $method->invokeArgs(null, [E_USER_NOTICE]));
+ $this->assertEquals('E_STRICT', $method->invokeArgs(null, [E_STRICT]));
+ $this->assertEquals('E_RECOVERABLE_ERROR', $method->invokeArgs(null, [E_RECOVERABLE_ERROR]));
+ $this->assertEquals('E_DEPRECATED', $method->invokeArgs(null, [E_DEPRECATED]));
+ $this->assertEquals('E_USER_DEPRECATED', $method->invokeArgs(null, [E_USER_DEPRECATED]));
+
+ $this->assertEquals('Unknown PHP error', $method->invokeArgs(null, ['RANDOM_TEXT']));
+ $this->assertEquals('Unknown PHP error', $method->invokeArgs(null, [E_ALL]));
+ }
+}
+
+class CustomTestException extends \Exception
+{
+}
+class CustomCustomException extends CustomTestException
+{
}
diff --git a/tests/Monolog/Formatter/ChromePHPFormatterTest.php b/tests/Monolog/Formatter/ChromePHPFormatterTest.php
index 71c4204..e44de85 100644
--- a/tests/Monolog/Formatter/ChromePHPFormatterTest.php
+++ b/tests/Monolog/Formatter/ChromePHPFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,7 @@ namespace Monolog\Formatter;
use Monolog\Logger;
-class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
+class ChromePHPFormatterTest extends \PHPUnit\Framework\TestCase
{
/**
* @covers Monolog\Formatter\ChromePHPFormatter::format
@@ -21,29 +21,29 @@ class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefaultFormat()
{
$formatter = new ChromePHPFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('ip' => '127.0.0.1'),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['ip' => '127.0.0.1'],
'message' => 'log',
- );
+ ];
$message = $formatter->format($record);
$this->assertEquals(
- array(
+ [
'meh',
- array(
+ [
'message' => 'log',
- 'context' => array('from' => 'logger'),
- 'extra' => array('ip' => '127.0.0.1'),
- ),
+ 'context' => ['from' => 'logger'],
+ 'extra' => ['ip' => '127.0.0.1'],
+ ],
'unknown',
'error',
- ),
+ ],
$message
);
}
@@ -54,29 +54,29 @@ class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithFileAndLine()
{
$formatter = new ChromePHPFormatter();
- $record = array(
+ $record = [
'level' => Logger::CRITICAL,
'level_name' => 'CRITICAL',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('ip' => '127.0.0.1', 'file' => 'test', 'line' => 14),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14],
'message' => 'log',
- );
+ ];
$message = $formatter->format($record);
$this->assertEquals(
- array(
+ [
'meh',
- array(
+ [
'message' => 'log',
- 'context' => array('from' => 'logger'),
- 'extra' => array('ip' => '127.0.0.1'),
- ),
+ 'context' => ['from' => 'logger'],
+ 'extra' => ['ip' => '127.0.0.1'],
+ ],
'test : 14',
'error',
- ),
+ ],
$message
);
}
@@ -87,25 +87,25 @@ class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithoutContext()
{
$formatter = new ChromePHPFormatter();
- $record = array(
+ $record = [
'level' => Logger::DEBUG,
'level_name' => 'DEBUG',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
$message = $formatter->format($record);
$this->assertEquals(
- array(
+ [
'meh',
'log',
'unknown',
'log',
- ),
+ ],
$message
);
}
@@ -116,42 +116,42 @@ class ChromePHPFormatterTest extends \PHPUnit_Framework_TestCase
public function testBatchFormatThrowException()
{
$formatter = new ChromePHPFormatter();
- $records = array(
- array(
+ $records = [
+ [
'level' => Logger::INFO,
'level_name' => 'INFO',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- ),
- array(
+ ],
+ [
'level' => Logger::WARNING,
'level_name' => 'WARNING',
'channel' => 'foo',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log2',
- ),
- );
+ ],
+ ];
$this->assertEquals(
- array(
- array(
+ [
+ [
'meh',
'log',
'unknown',
'info',
- ),
- array(
+ ],
+ [
'foo',
'log2',
'unknown',
'warn',
- ),
- ),
+ ],
+ ],
$formatter->formatBatch($records)
);
}
diff --git a/tests/Monolog/Formatter/ElasticaFormatterTest.php b/tests/Monolog/Formatter/ElasticaFormatterTest.php
index 90cc48d..5e4eeb9 100644
--- a/tests/Monolog/Formatter/ElasticaFormatterTest.php
+++ b/tests/Monolog/Formatter/ElasticaFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,7 @@ namespace Monolog\Formatter;
use Monolog\Logger;
-class ElasticaFormatterTest extends \PHPUnit_Framework_TestCase
+class ElasticaFormatterTest extends \PHPUnit\Framework\TestCase
{
public function setUp()
{
@@ -30,24 +30,24 @@ class ElasticaFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormat()
{
// test log message
- $msg = array(
+ $msg = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('foo' => 7, 'bar', 'class' => new \stdClass),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
// expected values
$expected = $msg;
$expected['datetime'] = '1970-01-01T00:00:00.000000+00:00';
- $expected['context'] = array(
- 'class' => '[object] (stdClass: {})',
+ $expected['context'] = [
+ 'class' => ['stdClass' => []],
'foo' => 7,
0 => 'bar',
- );
+ ];
// format log message
$formatter = new ElasticaFormatter('my_index', 'doc_type');
diff --git a/tests/Monolog/Formatter/FlowdockFormatterTest.php b/tests/Monolog/Formatter/FlowdockFormatterTest.php
index 1b2fd97..f922d53 100644
--- a/tests/Monolog/Formatter/FlowdockFormatterTest.php
+++ b/tests/Monolog/Formatter/FlowdockFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Formatter;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class FlowdockFormatterTest extends TestCase
{
@@ -24,14 +24,14 @@ class FlowdockFormatterTest extends TestCase
$formatter = new FlowdockFormatter('test_source', 'source@test.com');
$record = $this->getRecord();
- $expected = array(
+ $expected = [
'source' => 'test_source',
'from_address' => 'source@test.com',
'subject' => 'in test_source: WARNING - test',
'content' => 'test',
- 'tags' => array('#logs', '#warning', '#test'),
+ 'tags' => ['#logs', '#warning', '#test'],
'project' => 'test_source',
- );
+ ];
$formatted = $formatter->format($record);
$this->assertEquals($expected, $formatted['flowdock']);
@@ -43,10 +43,10 @@ class FlowdockFormatterTest extends TestCase
public function testFormatBatch()
{
$formatter = new FlowdockFormatter('test_source', 'source@test.com');
- $records = array(
+ $records = [
$this->getRecord(Logger::WARNING),
$this->getRecord(Logger::DEBUG),
- );
+ ];
$formatted = $formatter->formatBatch($records);
$this->assertArrayHasKey('flowdock', $formatted[0]);
diff --git a/tests/Monolog/Formatter/FluentdFormatterTest.php b/tests/Monolog/Formatter/FluentdFormatterTest.php
index 622b2ba..0be8d8f 100644
--- a/tests/Monolog/Formatter/FluentdFormatterTest.php
+++ b/tests/Monolog/Formatter/FluentdFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Formatter;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class FluentdFormatterTest extends TestCase
{
@@ -36,7 +36,7 @@ class FluentdFormatterTest extends TestCase
public function testFormat()
{
$record = $this->getRecord(Logger::WARNING);
- $record['datetime'] = new \DateTime("@0");
+ $record['datetime'] = new \DateTimeImmutable("@0");
$formatter = new FluentdFormatter();
$this->assertEquals(
@@ -51,7 +51,7 @@ class FluentdFormatterTest extends TestCase
public function testFormatWithTag()
{
$record = $this->getRecord(Logger::ERROR);
- $record['datetime'] = new \DateTime("@0");
+ $record['datetime'] = new \DateTimeImmutable("@0");
$formatter = new FluentdFormatter(true);
$this->assertEquals(
diff --git a/tests/Monolog/Formatter/GelfMessageFormatterTest.php b/tests/Monolog/Formatter/GelfMessageFormatterTest.php
index 4a24761..39eeaf7 100644
--- a/tests/Monolog/Formatter/GelfMessageFormatterTest.php
+++ b/tests/Monolog/Formatter/GelfMessageFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,12 +13,12 @@ namespace Monolog\Formatter;
use Monolog\Logger;
-class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
+class GelfMessageFormatterTest extends \PHPUnit\Framework\TestCase
{
public function setUp()
{
if (!class_exists('\Gelf\Message')) {
- $this->markTestSkipped("graylog2/gelf-php or mlehner/gelf-php is not installed");
+ $this->markTestSkipped("graylog2/gelf-php is not installed");
}
}
@@ -28,15 +28,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefaultFormatter()
{
$formatter = new GelfMessageFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
$message = $formatter->format($record);
@@ -63,15 +63,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithFileAndLine()
{
$formatter = new GelfMessageFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('file' => 'test', 'line' => 14),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['file' => 'test', 'line' => 14],
'message' => 'log',
- );
+ ];
$message = $formatter->format($record);
@@ -87,10 +87,10 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatInvalidFails()
{
$formatter = new GelfMessageFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
- );
+ ];
$formatter->format($record);
}
@@ -101,15 +101,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithContext()
{
$formatter = new GelfMessageFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => 'pair'),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['key' => 'pair'],
'message' => 'log',
- );
+ ];
$message = $formatter->format($record);
@@ -138,19 +138,19 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithContextContainingException()
{
$formatter = new GelfMessageFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger', 'exception' => array(
+ 'context' => ['from' => 'logger', 'exception' => [
'class' => '\Exception',
'file' => '/some/file/in/dir.php:56',
- 'trace' => array('/some/file/1.php:23', '/some/file/2.php:3'),
- )),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'trace' => ['/some/file/1.php:23', '/some/file/2.php:3'],
+ ]],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
$message = $formatter->format($record);
@@ -166,15 +166,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithExtra()
{
$formatter = new GelfMessageFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => 'pair'),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['key' => 'pair'],
'message' => 'log',
- );
+ ];
$message = $formatter->format($record);
@@ -200,15 +200,15 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithLargeData()
{
$formatter = new GelfMessageFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('exception' => str_repeat(' ', 32767)),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => str_repeat(' ', 32767)),
- 'message' => 'log'
- );
+ 'context' => ['exception' => str_repeat(' ', 32767)],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['key' => str_repeat(' ', 32767)],
+ 'message' => 'log',
+ ];
$message = $formatter->format($record);
$messageArray = $message->toArray();
@@ -216,7 +216,7 @@ class GelfMessageFormatterTest extends \PHPUnit_Framework_TestCase
$length = 200;
foreach ($messageArray as $key => $value) {
- if (!in_array($key, array('level', 'timestamp'))) {
+ if (!in_array($key, ['level', 'timestamp']) && is_string($value)) {
$length += strlen($value);
}
}
diff --git a/tests/Monolog/Formatter/JsonFormatterTest.php b/tests/Monolog/Formatter/JsonFormatterTest.php
index c9445f3..6dfdbb7 100644
--- a/tests/Monolog/Formatter/JsonFormatterTest.php
+++ b/tests/Monolog/Formatter/JsonFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Formatter;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class JsonFormatterTest extends TestCase
{
@@ -42,7 +42,7 @@ class JsonFormatterTest extends TestCase
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false);
$record = $this->getRecord();
- $this->assertEquals(json_encode($record), $formatter->format($record));
+ $this->assertEquals('{"message":"test","context":[],"level":300,"level_name":"WARNING","channel":"test","datetime":"'.$record['datetime']->format('Y-m-d\TH:i:s.uP').'","extra":[]}', $formatter->format($record));
}
/**
@@ -52,10 +52,10 @@ class JsonFormatterTest extends TestCase
public function testFormatBatch()
{
$formatter = new JsonFormatter();
- $records = array(
+ $records = [
$this->getRecord(Logger::WARNING),
$this->getRecord(Logger::DEBUG),
- );
+ ];
$this->assertEquals(json_encode($records), $formatter->formatBatch($records));
}
@@ -66,10 +66,10 @@ class JsonFormatterTest extends TestCase
public function testFormatBatchNewlines()
{
$formatter = new JsonFormatter(JsonFormatter::BATCH_MODE_NEWLINES);
- $records = $expected = array(
+ $records = $expected = [
$this->getRecord(Logger::WARNING),
$this->getRecord(Logger::DEBUG),
- );
+ ];
array_walk($expected, function (&$value, $key) {
$value = json_encode($value);
});
@@ -101,10 +101,6 @@ class JsonFormatterTest extends TestCase
public function testDefFormatWithThrowable()
{
- if (!class_exists('Error') || !is_subclass_of('Error', 'Throwable')) {
- $this->markTestSkipped('Requires PHP >=7');
- }
-
$formatter = new JsonFormatter();
$throwable = new \Error('Foo');
$formattedThrowable = $this->formatException($throwable);
@@ -129,21 +125,22 @@ class JsonFormatterTest extends TestCase
}
/**
- * @param JsonFormatter $formatter
+ * @param JsonFormatter $formatter
* @param \Exception|\Throwable $exception
*
* @return string
*/
private function formatRecordWithExceptionInContext(JsonFormatter $formatter, $exception)
{
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'CRITICAL',
'channel' => 'core',
- 'context' => array('exception' => $exception),
+ 'context' => ['exception' => $exception],
'datetime' => null,
- 'extra' => array(),
+ 'extra' => [],
'message' => 'foobar',
- ));
+ ]);
+
return $message;
}
@@ -154,11 +151,9 @@ class JsonFormatterTest extends TestCase
*/
private function formatExceptionFilePathWithLine($exception)
{
- $options = 0;
- if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
- $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
- }
+ $options = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
$path = substr(json_encode($exception->getFile(), $options), 1, -1);
+
return $path . ':' . $exception->getLine();
}
@@ -178,6 +173,7 @@ class JsonFormatterTest extends TestCase
',"file":"' . $this->formatExceptionFilePathWithLine($exception) .
($previous ? '","previous":' . $previous : '"') .
'}';
+
return $formattedException;
}
}
diff --git a/tests/Monolog/Formatter/LineFormatterTest.php b/tests/Monolog/Formatter/LineFormatterTest.php
index 310d93c..a8b55e4 100644
--- a/tests/Monolog/Formatter/LineFormatterTest.php
+++ b/tests/Monolog/Formatter/LineFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -14,141 +14,159 @@ namespace Monolog\Formatter;
/**
* @covers Monolog\Formatter\LineFormatter
*/
-class LineFormatterTest extends \PHPUnit_Framework_TestCase
+class LineFormatterTest extends \PHPUnit\Framework\TestCase
{
public function testDefFormatWithString()
{
$formatter = new LineFormatter(null, 'Y-m-d');
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'WARNING',
'channel' => 'log',
- 'context' => array(),
+ 'context' => [],
'message' => 'foo',
- 'datetime' => new \DateTime,
- 'extra' => array(),
- ));
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
+ ]);
$this->assertEquals('['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
}
public function testDefFormatWithArrayContext()
{
$formatter = new LineFormatter(null, 'Y-m-d');
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'ERROR',
'channel' => 'meh',
'message' => 'foo',
- 'datetime' => new \DateTime,
- 'extra' => array(),
- 'context' => array(
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
+ 'context' => [
'foo' => 'bar',
'baz' => 'qux',
'bool' => false,
'null' => null,
- ),
- ));
+ ],
+ ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foo {"foo":"bar","baz":"qux","bool":false,"null":null} []'."\n", $message);
}
public function testDefFormatExtras()
{
$formatter = new LineFormatter(null, 'Y-m-d');
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime,
- 'extra' => array('ip' => '127.0.0.1'),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => ['ip' => '127.0.0.1'],
'message' => 'log',
- ));
+ ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] {"ip":"127.0.0.1"}'."\n", $message);
}
public function testFormatExtras()
{
$formatter = new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context% %extra.file% %extra%\n", 'Y-m-d');
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime,
- 'extra' => array('ip' => '127.0.0.1', 'file' => 'test'),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => ['ip' => '127.0.0.1', 'file' => 'test'],
'message' => 'log',
- ));
+ ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log [] test {"ip":"127.0.0.1"}'."\n", $message);
}
public function testContextAndExtraOptionallyNotShownIfEmpty()
{
$formatter = new LineFormatter(null, 'Y-m-d', false, true);
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime,
- 'extra' => array(),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
'message' => 'log',
- ));
+ ]);
$this->assertEquals('['.date('Y-m-d').'] meh.ERROR: log '."\n", $message);
}
public function testContextAndExtraReplacement()
{
$formatter = new LineFormatter('%context.foo% => %extra.foo%');
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('foo' => 'bar'),
- 'datetime' => new \DateTime,
- 'extra' => array('foo' => 'xbar'),
+ 'context' => ['foo' => 'bar'],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => ['foo' => 'xbar'],
'message' => 'log',
- ));
+ ]);
$this->assertEquals('bar => xbar', $message);
}
public function testDefFormatWithObject()
{
$formatter = new LineFormatter(null, 'Y-m-d');
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime,
- 'extra' => array('foo' => new TestFoo, 'bar' => new TestBar, 'baz' => array(), 'res' => fopen('php://memory', 'rb')),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => ['foo' => new TestFoo, 'bar' => new TestBar, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
'message' => 'foobar',
- ));
+ ]);
- $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":"[object] (Monolog\\\\Formatter\\\\TestFoo: {\\"foo\\":\\"foo\\"})","bar":"[object] (Monolog\\\\Formatter\\\\TestBar: bar)","baz":[],"res":"[resource] (stream)"}'."\n", $message);
+ $this->assertEquals('['.date('Y-m-d').'] meh.ERROR: foobar [] {"foo":{"Monolog\\\\Formatter\\\\TestFoo":{"foo":"fooValue"}},"bar":{"Monolog\\\\Formatter\\\\TestBar":"bar"},"baz":[],"res":"[resource(stream)]"}'."\n", $message);
}
public function testDefFormatWithException()
{
$formatter = new LineFormatter(null, 'Y-m-d');
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'CRITICAL',
'channel' => 'core',
- 'context' => array('exception' => new \RuntimeException('Foo')),
- 'datetime' => new \DateTime,
- 'extra' => array(),
+ 'context' => ['exception' => new \RuntimeException('Foo')],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
'message' => 'foobar',
- ));
+ ]);
$path = str_replace('\\/', '/', json_encode(__FILE__));
$this->assertEquals('['.date('Y-m-d').'] core.CRITICAL: foobar {"exception":"[object] (RuntimeException(code: 0): Foo at '.substr($path, 1, -1).':'.(__LINE__ - 8).')"} []'."\n", $message);
}
+ public function testDefFormatWithExceptionAndStacktrace()
+ {
+ $formatter = new LineFormatter(null, 'Y-m-d');
+ $formatter->includeStacktraces();
+ $message = $formatter->format([
+ 'level_name' => 'CRITICAL',
+ 'channel' => 'core',
+ 'context' => ['exception' => new \RuntimeException('Foo')],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
+ 'message' => 'foobar',
+ ]);
+
+ $path = str_replace('\\/', '/', json_encode(__FILE__));
+
+ $this->assertRegexp('{^\['.date('Y-m-d').'] core\.CRITICAL: foobar \{"exception":"\[object] \(RuntimeException\(code: 0\): Foo at '.preg_quote(substr($path, 1, -1)).':'.(__LINE__ - 8).'\)\n\[stacktrace]\n#0}', $message);
+ }
+
public function testDefFormatWithPreviousException()
{
$formatter = new LineFormatter(null, 'Y-m-d');
$previous = new \LogicException('Wut?');
- $message = $formatter->format(array(
+ $message = $formatter->format([
'level_name' => 'CRITICAL',
'channel' => 'core',
- 'context' => array('exception' => new \RuntimeException('Foo', 0, $previous)),
- 'datetime' => new \DateTime,
- 'extra' => array(),
+ 'context' => ['exception' => new \RuntimeException('Foo', 0, $previous)],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
'message' => 'foobar',
- ));
+ ]);
$path = str_replace('\\/', '/', json_encode(__FILE__));
@@ -158,24 +176,24 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
public function testBatchFormat()
{
$formatter = new LineFormatter(null, 'Y-m-d');
- $message = $formatter->formatBatch(array(
- array(
+ $message = $formatter->formatBatch([
+ [
'level_name' => 'CRITICAL',
'channel' => 'test',
'message' => 'bar',
- 'context' => array(),
- 'datetime' => new \DateTime,
- 'extra' => array(),
- ),
- array(
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
+ ],
+ [
'level_name' => 'WARNING',
'channel' => 'log',
'message' => 'foo',
- 'context' => array(),
- 'datetime' => new \DateTime,
- 'extra' => array(),
- ),
- ));
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
+ ],
+ ]);
$this->assertEquals('['.date('Y-m-d').'] test.CRITICAL: bar [] []'."\n".'['.date('Y-m-d').'] log.WARNING: foo [] []'."\n", $message);
}
@@ -183,11 +201,11 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
{
$formatter = new LineFormatter(null, 'Y-m-d');
$message = $formatter->format(
- array(
+ [
'message' => "foo\nbar",
- 'context' => array(),
- 'extra' => array(),
- )
+ 'context' => [],
+ 'extra' => [],
+ ]
);
$this->assertRegExp('/foo bar/', $message);
@@ -197,11 +215,11 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
{
$formatter = new LineFormatter(null, 'Y-m-d', true);
$message = $formatter->format(
- array(
+ [
'message' => "foo\nbar",
- 'context' => array(),
- 'extra' => array(),
- )
+ 'context' => [],
+ 'extra' => [],
+ ]
);
$this->assertRegExp('/foo\nbar/', $message);
@@ -210,7 +228,7 @@ class LineFormatterTest extends \PHPUnit_Framework_TestCase
class TestFoo
{
- public $foo = 'foo';
+ public $foo = 'fooValue';
}
class TestBar
diff --git a/tests/Monolog/Formatter/LogglyFormatterTest.php b/tests/Monolog/Formatter/LogglyFormatterTest.php
index 6d59b3f..2eff4ac 100644
--- a/tests/Monolog/Formatter/LogglyFormatterTest.php
+++ b/tests/Monolog/Formatter/LogglyFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Formatter;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class LogglyFormatterTest extends TestCase
{
@@ -34,7 +34,8 @@ class LogglyFormatterTest extends TestCase
$formatter = new LogglyFormatter();
$record = $this->getRecord();
$formatted_decoded = json_decode($formatter->format($record), true);
+ $this->assertArrayNotHasKey("datetime", $formatted_decoded);
$this->assertArrayHasKey("timestamp", $formatted_decoded);
- $this->assertEquals(new \DateTime($formatted_decoded["timestamp"]), $record["datetime"]);
+ $this->assertEquals($record["datetime"]->format('Y-m-d\TH:i:s.uO'), $formatted_decoded["timestamp"]);
}
}
diff --git a/tests/Monolog/Formatter/LogmaticFormatterTest.php b/tests/Monolog/Formatter/LogmaticFormatterTest.php
new file mode 100644
index 0000000..d27670f
--- /dev/null
+++ b/tests/Monolog/Formatter/LogmaticFormatterTest.php
@@ -0,0 +1,36 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Formatter;
+
+use Monolog\Test\TestCase;
+
+/**
+ * @author Julien Breux <julien.breux@gmail.com>
+ */
+class LogmaticFormatterTest extends TestCase
+{
+ /**
+ * @covers Monolog\Formatter\LogmaticFormatter::format
+ */
+ public function testFormat()
+ {
+ $formatter = new LogmaticFormatter();
+ $formatter->setHostname('testHostname');
+ $formatter->setAppname('testAppname');
+ $record = $this->getRecord();
+ $formatted_decoded = json_decode($formatter->format($record), true);
+ $this->assertArrayHasKey('hostname', $formatted_decoded);
+ $this->assertArrayHasKey('appname', $formatted_decoded);
+ $this->assertEquals('testHostname', $formatted_decoded['hostname']);
+ $this->assertEquals('testAppname', $formatted_decoded['appname']);
+ }
+}
diff --git a/tests/Monolog/Formatter/LogstashFormatterTest.php b/tests/Monolog/Formatter/LogstashFormatterTest.php
index 9f6b1cc..2ca9f55 100644
--- a/tests/Monolog/Formatter/LogstashFormatterTest.php
+++ b/tests/Monolog/Formatter/LogstashFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,7 @@ namespace Monolog\Formatter;
use Monolog\Logger;
-class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
+class LogstashFormatterTest extends \PHPUnit\Framework\TestCase
{
public function tearDown()
{
@@ -25,158 +25,18 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
/**
* @covers Monolog\Formatter\LogstashFormatter::format
*/
- public function testDefaultFormatter()
- {
- $formatter = new LogstashFormatter('test', 'hostname');
- $record = array(
- 'level' => Logger::ERROR,
- 'level_name' => 'ERROR',
- 'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
- 'message' => 'log',
- );
-
- $message = json_decode($formatter->format($record), true);
-
- $this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']);
- $this->assertEquals('log', $message['@message']);
- $this->assertEquals('meh', $message['@fields']['channel']);
- $this->assertContains('meh', $message['@tags']);
- $this->assertEquals(Logger::ERROR, $message['@fields']['level']);
- $this->assertEquals('test', $message['@type']);
- $this->assertEquals('hostname', $message['@source']);
-
- $formatter = new LogstashFormatter('mysystem');
-
- $message = json_decode($formatter->format($record), true);
-
- $this->assertEquals('mysystem', $message['@type']);
- }
-
- /**
- * @covers Monolog\Formatter\LogstashFormatter::format
- */
- public function testFormatWithFileAndLine()
- {
- $formatter = new LogstashFormatter('test');
- $record = array(
- 'level' => Logger::ERROR,
- 'level_name' => 'ERROR',
- 'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('file' => 'test', 'line' => 14),
- 'message' => 'log',
- );
-
- $message = json_decode($formatter->format($record), true);
-
- $this->assertEquals('test', $message['@fields']['file']);
- $this->assertEquals(14, $message['@fields']['line']);
- }
-
- /**
- * @covers Monolog\Formatter\LogstashFormatter::format
- */
- public function testFormatWithContext()
- {
- $formatter = new LogstashFormatter('test');
- $record = array(
- 'level' => Logger::ERROR,
- 'level_name' => 'ERROR',
- 'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => 'pair'),
- 'message' => 'log',
- );
-
- $message = json_decode($formatter->format($record), true);
-
- $message_array = $message['@fields'];
-
- $this->assertArrayHasKey('ctxt_from', $message_array);
- $this->assertEquals('logger', $message_array['ctxt_from']);
-
- // Test with extraPrefix
- $formatter = new LogstashFormatter('test', null, null, 'CTX');
- $message = json_decode($formatter->format($record), true);
-
- $message_array = $message['@fields'];
-
- $this->assertArrayHasKey('CTXfrom', $message_array);
- $this->assertEquals('logger', $message_array['CTXfrom']);
- }
-
- /**
- * @covers Monolog\Formatter\LogstashFormatter::format
- */
- public function testFormatWithExtra()
- {
- $formatter = new LogstashFormatter('test');
- $record = array(
- 'level' => Logger::ERROR,
- 'level_name' => 'ERROR',
- 'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => 'pair'),
- 'message' => 'log',
- );
-
- $message = json_decode($formatter->format($record), true);
-
- $message_array = $message['@fields'];
-
- $this->assertArrayHasKey('key', $message_array);
- $this->assertEquals('pair', $message_array['key']);
-
- // Test with extraPrefix
- $formatter = new LogstashFormatter('test', null, 'EXT');
- $message = json_decode($formatter->format($record), true);
-
- $message_array = $message['@fields'];
-
- $this->assertArrayHasKey('EXTkey', $message_array);
- $this->assertEquals('pair', $message_array['EXTkey']);
- }
-
- public function testFormatWithApplicationName()
- {
- $formatter = new LogstashFormatter('app', 'test');
- $record = array(
- 'level' => Logger::ERROR,
- 'level_name' => 'ERROR',
- 'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => 'pair'),
- 'message' => 'log',
- );
-
- $message = json_decode($formatter->format($record), true);
-
- $this->assertArrayHasKey('@type', $message);
- $this->assertEquals('app', $message['@type']);
- }
-
- /**
- * @covers Monolog\Formatter\LogstashFormatter::format
- */
public function testDefaultFormatterV1()
{
- $formatter = new LogstashFormatter('test', 'hostname', null, 'ctxt_', LogstashFormatter::V1);
- $record = array(
+ $formatter = new LogstashFormatter('test', 'hostname', null, 'ctxt_');
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
$message = json_decode($formatter->format($record), true);
@@ -185,10 +45,11 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('log', $message['message']);
$this->assertEquals('meh', $message['channel']);
$this->assertEquals('ERROR', $message['level']);
+ $this->assertEquals(Logger::ERROR, $message['monolog_level']);
$this->assertEquals('test', $message['type']);
$this->assertEquals('hostname', $message['host']);
- $formatter = new LogstashFormatter('mysystem', null, null, 'ctxt_', LogstashFormatter::V1);
+ $formatter = new LogstashFormatter('mysystem', null, null, 'ctxt_');
$message = json_decode($formatter->format($record), true);
@@ -200,21 +61,21 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
*/
public function testFormatWithFileAndLineV1()
{
- $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1);
- $record = array(
+ $formatter = new LogstashFormatter('test', null, null, 'ctxt_');
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('file' => 'test', 'line' => 14),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['file' => 'test', 'line' => 14],
'message' => 'log',
- );
+ ];
$message = json_decode($formatter->format($record), true);
- $this->assertEquals('test', $message['file']);
- $this->assertEquals(14, $message['line']);
+ $this->assertEquals('test', $message['extra']['file']);
+ $this->assertEquals(14, $message['extra']['line']);
}
/**
@@ -222,28 +83,30 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
*/
public function testFormatWithContextV1()
{
- $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1);
- $record = array(
+ $formatter = new LogstashFormatter('test', null, null, 'ctxt_');
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => 'pair'),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['key' => 'pair'],
'message' => 'log',
- );
+ ];
$message = json_decode($formatter->format($record), true);
- $this->assertArrayHasKey('ctxt_from', $message);
- $this->assertEquals('logger', $message['ctxt_from']);
+ $this->assertArrayHasKey('ctxt_context', $message);
+ $this->assertArrayHasKey('from', $message['ctxt_context']);
+ $this->assertEquals('logger', $message['ctxt_context']['from']);
// Test with extraPrefix
- $formatter = new LogstashFormatter('test', null, null, 'CTX', LogstashFormatter::V1);
+ $formatter = new LogstashFormatter('test', null, null, 'CTX');
$message = json_decode($formatter->format($record), true);
- $this->assertArrayHasKey('CTXfrom', $message);
- $this->assertEquals('logger', $message['CTXfrom']);
+ $this->assertArrayHasKey('CTXcontext', $message);
+ $this->assertArrayHasKey('from', $message['CTXcontext']);
+ $this->assertEquals('logger', $message['CTXcontext']['from']);
}
/**
@@ -251,42 +114,44 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
*/
public function testFormatWithExtraV1()
{
- $formatter = new LogstashFormatter('test', null, null, 'ctxt_', LogstashFormatter::V1);
- $record = array(
+ $formatter = new LogstashFormatter('test', null, null, 'ctxt_');
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => 'pair'),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['key' => 'pair'],
'message' => 'log',
- );
+ ];
$message = json_decode($formatter->format($record), true);
- $this->assertArrayHasKey('key', $message);
- $this->assertEquals('pair', $message['key']);
+ $this->assertArrayHasKey('extra', $message);
+ $this->assertArrayHasKey('key', $message['extra']);
+ $this->assertEquals('pair', $message['extra']['key']);
// Test with extraPrefix
- $formatter = new LogstashFormatter('test', null, 'EXT', 'ctxt_', LogstashFormatter::V1);
+ $formatter = new LogstashFormatter('test', null, 'EXT', 'ctxt_');
$message = json_decode($formatter->format($record), true);
- $this->assertArrayHasKey('EXTkey', $message);
- $this->assertEquals('pair', $message['EXTkey']);
+ $this->assertArrayHasKey('EXTextra', $message);
+ $this->assertArrayHasKey('key', $message['EXTextra']);
+ $this->assertEquals('pair', $message['EXTextra']['key']);
}
public function testFormatWithApplicationNameV1()
{
- $formatter = new LogstashFormatter('app', 'test', null, 'ctxt_', LogstashFormatter::V1);
- $record = array(
+ $formatter = new LogstashFormatter('app', 'test', null, 'ctxt_');
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('key' => 'pair'),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['key' => 'pair'],
'message' => 'log',
- );
+ ];
$message = json_decode($formatter->format($record), true);
@@ -296,38 +161,27 @@ class LogstashFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithLatin9Data()
{
- if (version_compare(PHP_VERSION, '5.5.0', '<')) {
- // Ignore the warning that will be emitted by PHP <5.5.0
- \PHPUnit_Framework_Error_Warning::$enabled = false;
- }
$formatter = new LogstashFormatter('test', 'hostname');
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => '¯\_(ツ)_/¯',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [
'user_agent' => "\xD6WN; FBCR/OrangeEspa\xF1a; Vers\xE3o/4.0; F\xE4rist",
- ),
+ ],
'message' => 'log',
- );
+ ];
$message = json_decode($formatter->format($record), true);
$this->assertEquals("1970-01-01T00:00:00.000000+00:00", $message['@timestamp']);
- $this->assertEquals('log', $message['@message']);
- $this->assertEquals('¯\_(ツ)_/¯', $message['@fields']['channel']);
- $this->assertContains('¯\_(ツ)_/¯', $message['@tags']);
- $this->assertEquals(Logger::ERROR, $message['@fields']['level']);
- $this->assertEquals('test', $message['@type']);
- $this->assertEquals('hostname', $message['@source']);
- if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
- $this->assertEquals('ÖWN; FBCR/OrangeEspaña; Versão/4.0; Färist', $message['@fields']['user_agent']);
- } else {
- // PHP <5.5 does not return false for an element encoding failure,
- // instead it emits a warning (possibly) and nulls the value.
- $this->assertEquals(null, $message['@fields']['user_agent']);
- }
+ $this->assertEquals('log', $message['message']);
+ $this->assertEquals('¯\_(ツ)_/¯', $message['channel']);
+ $this->assertEquals('ERROR', $message['level']);
+ $this->assertEquals('test', $message['type']);
+ $this->assertEquals('hostname', $message['host']);
+ $this->assertEquals('ÖWN; FBCR/OrangeEspaña; Versão/4.0; Färist', $message['extra']['user_agent']);
}
}
diff --git a/tests/Monolog/Formatter/MongoDBFormatterTest.php b/tests/Monolog/Formatter/MongoDBFormatterTest.php
index 52e699e..8759c01 100644
--- a/tests/Monolog/Formatter/MongoDBFormatterTest.php
+++ b/tests/Monolog/Formatter/MongoDBFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -16,21 +16,21 @@ use Monolog\Logger;
/**
* @author Florian Plattner <me@florianplattner.de>
*/
-class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
+class MongoDBFormatterTest extends \PHPUnit\Framework\TestCase
{
public function setUp()
{
- if (!class_exists('MongoDate')) {
- $this->markTestSkipped('mongo extension not installed');
+ if (!class_exists('MongoDB\BSON\UTCDateTime')) {
+ $this->markTestSkipped('ext-mongodb not installed');
}
}
public function constructArgumentProvider()
{
- return array(
- array(1, true, 1, true),
- array(0, false, 0, false),
- );
+ return [
+ [1, true, 1, true],
+ [0, false, 0, false],
+ ];
}
/**
@@ -56,28 +56,28 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
public function testSimpleFormat()
{
- $record = array(
+ $record = [
'message' => 'some log message',
- 'context' => array(),
+ 'context' => [],
'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test',
- 'datetime' => new \DateTime('2014-02-01 00:00:00'),
- 'extra' => array(),
- );
+ 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
+ 'extra' => [],
+ ];
$formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record);
$this->assertCount(7, $formattedRecord);
$this->assertEquals('some log message', $formattedRecord['message']);
- $this->assertEquals(array(), $formattedRecord['context']);
+ $this->assertEquals([], $formattedRecord['context']);
$this->assertEquals(Logger::WARNING, $formattedRecord['level']);
$this->assertEquals(Logger::getLevelName(Logger::WARNING), $formattedRecord['level_name']);
$this->assertEquals('test', $formattedRecord['channel']);
- $this->assertInstanceOf('\MongoDate', $formattedRecord['datetime']);
- $this->assertEquals('0.00000000 1391212800', $formattedRecord['datetime']->__toString());
- $this->assertEquals(array(), $formattedRecord['extra']);
+ $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $formattedRecord['datetime']);
+ $this->assertEquals('1453410690123', $formattedRecord['datetime']->__toString());
+ $this->assertEquals([], $formattedRecord['extra']);
}
public function testRecursiveFormat()
@@ -86,34 +86,34 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
$someObject->foo = 'something';
$someObject->bar = 'stuff';
- $record = array(
+ $record = [
'message' => 'some log message',
- 'context' => array(
- 'stuff' => new \DateTime('2014-02-01 02:31:33'),
+ 'context' => [
+ 'stuff' => new \DateTimeImmutable('1969-01-21T21:11:30.213000+00:00'),
'some_object' => $someObject,
'context_string' => 'some string',
'context_int' => 123456,
'except' => new \Exception('exception message', 987),
- ),
+ ],
'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test',
- 'datetime' => new \DateTime('2014-02-01 00:00:00'),
- 'extra' => array(),
- );
+ 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.213000+00:00'),
+ 'extra' => [],
+ ];
$formatter = new MongoDBFormatter();
$formattedRecord = $formatter->format($record);
$this->assertCount(5, $formattedRecord['context']);
- $this->assertInstanceOf('\MongoDate', $formattedRecord['context']['stuff']);
- $this->assertEquals('0.00000000 1391221893', $formattedRecord['context']['stuff']->__toString());
+ $this->assertInstanceOf('MongoDB\BSON\UTCDateTime', $formattedRecord['context']['stuff']);
+ $this->assertEquals('-29731710213', $formattedRecord['context']['stuff']->__toString());
$this->assertEquals(
- array(
+ [
'foo' => 'something',
'bar' => 'stuff',
'class' => 'stdClass',
- ),
+ ],
$formattedRecord['context']['some_object']
);
$this->assertEquals('some string', $formattedRecord['context']['context_string']);
@@ -130,75 +130,75 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatDepthArray()
{
- $record = array(
+ $record = [
'message' => 'some log message',
- 'context' => array(
- 'nest2' => array(
+ 'context' => [
+ 'nest2' => [
'property' => 'anything',
- 'nest3' => array(
+ 'nest3' => [
'nest4' => 'value',
'property' => 'nothing',
- ),
- ),
- ),
+ ],
+ ],
+ ],
'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test',
- 'datetime' => new \DateTime('2014-02-01 00:00:00'),
- 'extra' => array(),
- );
+ 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
+ 'extra' => [],
+ ];
$formatter = new MongoDBFormatter(2);
$formattedResult = $formatter->format($record);
$this->assertEquals(
- array(
- 'nest2' => array(
+ [
+ 'nest2' => [
'property' => 'anything',
'nest3' => '[...]',
- ),
- ),
+ ],
+ ],
$formattedResult['context']
);
}
public function testFormatDepthArrayInfiniteNesting()
{
- $record = array(
+ $record = [
'message' => 'some log message',
- 'context' => array(
- 'nest2' => array(
+ 'context' => [
+ 'nest2' => [
'property' => 'something',
- 'nest3' => array(
+ 'nest3' => [
'property' => 'anything',
- 'nest4' => array(
+ 'nest4' => [
'property' => 'nothing',
- ),
- ),
- ),
- ),
+ ],
+ ],
+ ],
+ ],
'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test',
- 'datetime' => new \DateTime('2014-02-01 00:00:00'),
- 'extra' => array(),
- );
+ 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
+ 'extra' => [],
+ ];
$formatter = new MongoDBFormatter(0);
$formattedResult = $formatter->format($record);
$this->assertEquals(
- array(
- 'nest2' => array(
+ [
+ 'nest2' => [
'property' => 'something',
- 'nest3' => array(
+ 'nest3' => [
'property' => 'anything',
- 'nest4' => array(
+ 'nest4' => [
'property' => 'nothing',
- ),
- ),
- ),
- ),
+ ],
+ ],
+ ],
+ ],
$formattedResult['context']
);
}
@@ -211,46 +211,46 @@ class MongoDBFormatterTest extends \PHPUnit_Framework_TestCase
$someObject->nest3->property = 'nothing';
$someObject->nest3->nest4 = 'invisible';
- $record = array(
+ $record = [
'message' => 'some log message',
- 'context' => array(
+ 'context' => [
'nest2' => $someObject,
- ),
+ ],
'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test',
- 'datetime' => new \DateTime('2014-02-01 00:00:00'),
- 'extra' => array(),
- );
+ 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
+ 'extra' => [],
+ ];
$formatter = new MongoDBFormatter(2, true);
$formattedResult = $formatter->format($record);
$this->assertEquals(
- array(
- 'nest2' => array(
+ [
+ 'nest2' => [
'property' => 'anything',
'nest3' => '[...]',
'class' => 'stdClass',
- ),
- ),
+ ],
+ ],
$formattedResult['context']
);
}
public function testFormatDepthException()
{
- $record = array(
+ $record = [
'message' => 'some log message',
- 'context' => array(
+ 'context' => [
'nest2' => new \Exception('exception message', 987),
- ),
+ ],
'level' => Logger::WARNING,
'level_name' => Logger::getLevelName(Logger::WARNING),
'channel' => 'test',
- 'datetime' => new \DateTime('2014-02-01 00:00:00'),
- 'extra' => array(),
- );
+ 'datetime' => new \DateTimeImmutable('2016-01-21T21:11:30.123456+00:00'),
+ 'extra' => [],
+ ];
$formatter = new MongoDBFormatter(2, false);
$formattedRecord = $formatter->format($record);
diff --git a/tests/Monolog/Formatter/NormalizerFormatterTest.php b/tests/Monolog/Formatter/NormalizerFormatterTest.php
index 57bcdf9..68b275d 100644
--- a/tests/Monolog/Formatter/NormalizerFormatterTest.php
+++ b/tests/Monolog/Formatter/NormalizerFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -14,7 +14,7 @@ namespace Monolog\Formatter;
/**
* @covers Monolog\Formatter\NormalizerFormatter
*/
-class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
+class NormalizerFormatterTest extends \PHPUnit\Framework\TestCase
{
public function tearDown()
{
@@ -26,40 +26,40 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormat()
{
$formatter = new NormalizerFormatter('Y-m-d');
- $formatted = $formatter->format(array(
+ $formatted = $formatter->format([
'level_name' => 'ERROR',
'channel' => 'meh',
'message' => 'foo',
- 'datetime' => new \DateTime,
- 'extra' => array('foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => array(), 'res' => fopen('php://memory', 'rb')),
- 'context' => array(
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
+ 'context' => [
'foo' => 'bar',
'baz' => 'qux',
'inf' => INF,
'-inf' => -INF,
'nan' => acos(4),
- ),
- ));
+ ],
+ ]);
- $this->assertEquals(array(
+ $this->assertEquals([
'level_name' => 'ERROR',
'channel' => 'meh',
'message' => 'foo',
'datetime' => date('Y-m-d'),
- 'extra' => array(
- 'foo' => '[object] (Monolog\\Formatter\\TestFooNorm: {"foo":"foo"})',
- 'bar' => '[object] (Monolog\\Formatter\\TestBarNorm: bar)',
- 'baz' => array(),
- 'res' => '[resource] (stream)',
- ),
- 'context' => array(
+ 'extra' => [
+ 'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]],
+ 'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'],
+ 'baz' => [],
+ 'res' => '[resource(stream)]',
+ ],
+ 'context' => [
'foo' => 'bar',
'baz' => 'qux',
'inf' => 'INF',
'-inf' => '-INF',
'nan' => 'NaN',
- ),
- ), $formatted);
+ ],
+ ], $formatted);
}
public function testFormatExceptions()
@@ -67,22 +67,22 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$formatter = new NormalizerFormatter('Y-m-d');
$e = new \LogicException('bar');
$e2 = new \RuntimeException('foo', 0, $e);
- $formatted = $formatter->format(array(
+ $formatted = $formatter->format([
'exception' => $e2,
- ));
+ ]);
$this->assertGreaterThan(5, count($formatted['exception']['trace']));
$this->assertTrue(isset($formatted['exception']['previous']));
unset($formatted['exception']['trace'], $formatted['exception']['previous']);
- $this->assertEquals(array(
- 'exception' => array(
+ $this->assertEquals([
+ 'exception' => [
'class' => get_class($e2),
'message' => $e2->getMessage(),
'code' => $e2->getCode(),
'file' => $e2->getFile().':'.$e2->getLine(),
- ),
- ), $formatted);
+ ],
+ ], $formatted);
}
public function testFormatSoapFaultException()
@@ -93,14 +93,14 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$formatter = new NormalizerFormatter('Y-m-d');
$e = new \SoapFault('foo', 'bar', 'hello', 'world');
- $formatted = $formatter->format(array(
+ $formatted = $formatter->format([
'exception' => $e,
- ));
+ ]);
unset($formatted['exception']['trace']);
- $this->assertEquals(array(
- 'exception' => array(
+ $this->assertEquals([
+ 'exception' => [
'class' => 'SoapFault',
'message' => 'bar',
'code' => 0,
@@ -108,58 +108,59 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
'faultcode' => 'foo',
'faultactor' => 'hello',
'detail' => 'world',
- ),
- ), $formatted);
+ ],
+ ], $formatted);
}
public function testFormatToStringExceptionHandle()
{
$formatter = new NormalizerFormatter('Y-m-d');
- $this->setExpectedException('RuntimeException', 'Could not convert to string');
- $formatter->format(array(
+ $this->expectException('RuntimeException');
+ $this->expectExceptionMessage('Could not convert to string');
+ $formatter->format([
'myObject' => new TestToStringError(),
- ));
+ ]);
}
public function testBatchFormat()
{
$formatter = new NormalizerFormatter('Y-m-d');
- $formatted = $formatter->formatBatch(array(
- array(
+ $formatted = $formatter->formatBatch([
+ [
'level_name' => 'CRITICAL',
'channel' => 'test',
'message' => 'bar',
- 'context' => array(),
- 'datetime' => new \DateTime,
- 'extra' => array(),
- ),
- array(
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
+ ],
+ [
'level_name' => 'WARNING',
'channel' => 'log',
'message' => 'foo',
- 'context' => array(),
- 'datetime' => new \DateTime,
- 'extra' => array(),
- ),
- ));
- $this->assertEquals(array(
- array(
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable,
+ 'extra' => [],
+ ],
+ ]);
+ $this->assertEquals([
+ [
'level_name' => 'CRITICAL',
'channel' => 'test',
'message' => 'bar',
- 'context' => array(),
+ 'context' => [],
'datetime' => date('Y-m-d'),
- 'extra' => array(),
- ),
- array(
+ 'extra' => [],
+ ],
+ [
'level_name' => 'WARNING',
'channel' => 'log',
'message' => 'foo',
- 'context' => array(),
+ 'context' => [],
'datetime' => date('Y-m-d'),
- 'extra' => array(),
- ),
- ), $formatted);
+ 'extra' => [],
+ ],
+ ], $formatted);
}
/**
@@ -186,11 +187,20 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson');
$reflMethod->setAccessible(true);
- $res = $reflMethod->invoke($formatter, array($foo, $bar), true);
+ $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
restore_error_handler();
- $this->assertEquals(@json_encode(array($foo, $bar)), $res);
+ $this->assertEquals(@json_encode([$foo, $bar]), $res);
+ }
+
+ public function testCanNormalizeReferences()
+ {
+ $formatter = new NormalizerFormatter();
+ $x = ['foo' => 'bar'];
+ $y = ['x' => &$x];
+ $x['y'] = &$y;
+ $formatter->format($y);
}
public function testIgnoresInvalidTypes()
@@ -210,11 +220,11 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson');
$reflMethod->setAccessible(true);
- $res = $reflMethod->invoke($formatter, array($resource), true);
+ $res = $reflMethod->invoke($formatter, [$resource], true);
restore_error_handler();
- $this->assertEquals(@json_encode(array($resource)), $res);
+ $this->assertEquals(@json_encode([$resource]), $res);
}
public function testNormalizeHandleLargeArrays()
@@ -240,10 +250,6 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
*/
public function testThrowsOnInvalidEncoding()
{
- if (version_compare(PHP_VERSION, '5.5.0', '<')) {
- // Ignore the warning that will be emitted by PHP <5.5.0
- \PHPUnit_Framework_Error_Warning::$enabled = false;
- }
$formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson');
$reflMethod->setAccessible(true);
@@ -251,31 +257,18 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
// send an invalid unicode sequence as a object that can't be cleaned
$record = new \stdClass;
$record->message = "\xB1\x31";
- $res = $reflMethod->invoke($formatter, $record);
- if (PHP_VERSION_ID < 50500 && $res === '{"message":null}') {
- throw new \RuntimeException('PHP 5.3/5.4 throw a warning and null the value instead of returning false entirely');
- }
+ $reflMethod->invoke($formatter, $record);
}
public function testConvertsInvalidEncodingAsLatin9()
{
- if (version_compare(PHP_VERSION, '5.5.0', '<')) {
- // Ignore the warning that will be emitted by PHP <5.5.0
- \PHPUnit_Framework_Error_Warning::$enabled = false;
- }
$formatter = new NormalizerFormatter();
$reflMethod = new \ReflectionMethod($formatter, 'toJson');
$reflMethod->setAccessible(true);
- $res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"));
+ $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
- if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
- $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
- } else {
- // PHP <5.5 does not return false for an element encoding failure,
- // instead it emits a warning (possibly) and nulls the value.
- $this->assertSame('{"message":null}', $res);
- }
+ $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
}
/**
@@ -295,19 +288,19 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
{
$obj = new \stdClass;
- return array(
- 'null' => array(null, null),
- 'int' => array(123, 123),
- 'float' => array(123.45, 123.45),
- 'bool false' => array(false, false),
- 'bool true' => array(true, true),
- 'ascii string' => array('abcdef', 'abcdef'),
- 'latin9 string' => array("\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'),
- 'unicode string' => array('¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'),
- 'empty array' => array(array(), array()),
- 'array' => array(array('abcdef'), array('abcdef')),
- 'object' => array($obj, $obj),
- );
+ return [
+ 'null' => [null, null],
+ 'int' => [123, 123],
+ 'float' => [123.45, 123.45],
+ 'bool false' => [false, false],
+ 'bool true' => [true, true],
+ 'ascii string' => ['abcdef', 'abcdef'],
+ 'latin9 string' => ["\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'],
+ 'unicode string' => ['¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'],
+ 'empty array' => [[], []],
+ 'array' => [['abcdef'], ['abcdef']],
+ 'object' => [$obj, $obj],
+ ];
}
/**
@@ -321,32 +314,29 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
$reflMethod->setAccessible(true);
- $this->setExpectedException('RuntimeException', $msg);
+ $this->expectException('RuntimeException');
+ $this->expectExceptionMessage($msg);
$reflMethod->invoke($formatter, $code, 'faked');
}
public function providesHandleJsonErrorFailure()
{
- return array(
- 'depth' => array(JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'),
- 'state' => array(JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'),
- 'ctrl' => array(JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'),
- 'default' => array(-1, 'Unknown error'),
- );
+ return [
+ 'depth' => [JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'],
+ 'state' => [JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'],
+ 'ctrl' => [JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'],
+ 'default' => [-1, 'Unknown error'],
+ ];
}
+ // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
+ // and no file or line are included in the trace because it's treated as internal function
public function testExceptionTraceWithArgs()
{
if (defined('HHVM_VERSION')) {
$this->markTestSkipped('Not supported in HHVM since it detects errors differently');
}
- // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
- // and no file or line are included in the trace because it's treated as internal function
- set_error_handler(function ($errno, $errstr, $errfile, $errline) {
- throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
- });
-
try {
// This will contain $resource and $wrappedResource as arguments in the trace item
$resource = fopen('php://memory', 'rw+');
@@ -354,25 +344,24 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
$wrappedResource = new TestFooNorm;
$wrappedResource->foo = $resource;
// Just do something stupid with a resource/wrapped resource as argument
- array_keys($wrappedResource);
- } catch (\Exception $e) {
- restore_error_handler();
+ $arr = [$wrappedResource, $resource];
+ // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
+ usort($arr, function ($a, $b) {
+ throw new \ErrorException('Foo');
+ });
+ } catch (\Throwable $e) {
}
$formatter = new NormalizerFormatter();
- $record = array('context' => array('exception' => $e));
+ $record = ['context' => ['exception' => $e]];
$result = $formatter->format($record);
$this->assertRegExp(
- '%"resource":"\[resource\] \(stream\)"%',
+ '%\[resource\(stream\)\]%',
$result['context']['exception']['trace'][0]
);
- if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
- $pattern = '%"wrappedResource":"\[object\] \(Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm: \)"%';
- } else {
- $pattern = '%\\\\"foo\\\\":null%';
- }
+ $pattern = '%\[\{"Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm":"JSON_ERROR"\}%';
// Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
$this->assertRegExp(
@@ -384,7 +373,7 @@ class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
class TestFooNorm
{
- public $foo = 'foo';
+ public $foo = 'fooValue';
}
class TestBarNorm
diff --git a/tests/Monolog/Formatter/ScalarFormatterTest.php b/tests/Monolog/Formatter/ScalarFormatterTest.php
index b1c8fd4..9af4937 100644
--- a/tests/Monolog/Formatter/ScalarFormatterTest.php
+++ b/tests/Monolog/Formatter/ScalarFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,9 @@
namespace Monolog\Formatter;
-class ScalarFormatterTest extends \PHPUnit_Framework_TestCase
+use Monolog\DateTimeImmutable;
+
+class ScalarFormatterTest extends \PHPUnit\Framework\TestCase
{
private $formatter;
@@ -22,7 +24,7 @@ class ScalarFormatterTest extends \PHPUnit_Framework_TestCase
public function buildTrace(\Exception $e)
{
- $data = array();
+ $data = [];
$trace = $e->getTrace();
foreach ($trace as $frame) {
if (isset($frame['file'])) {
@@ -37,74 +39,70 @@ class ScalarFormatterTest extends \PHPUnit_Framework_TestCase
public function encodeJson($data)
{
- if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
- return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
- }
-
- return json_encode($data);
+ return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
public function testFormat()
{
$exception = new \Exception('foo');
- $formatted = $this->formatter->format(array(
+ $formatted = $this->formatter->format([
'foo' => 'string',
'bar' => 1,
'baz' => false,
- 'bam' => array(1, 2, 3),
- 'bat' => array('foo' => 'bar'),
- 'bap' => \DateTime::createFromFormat(\DateTime::ISO8601, '1970-01-01T00:00:00+0000'),
+ 'bam' => [1, 2, 3],
+ 'bat' => ['foo' => 'bar'],
+ 'bap' => $dt = new DateTimeImmutable(true),
'ban' => $exception,
- ));
+ ]);
- $this->assertSame(array(
+ $this->assertSame([
'foo' => 'string',
'bar' => 1,
'baz' => false,
- 'bam' => $this->encodeJson(array(1, 2, 3)),
- 'bat' => $this->encodeJson(array('foo' => 'bar')),
- 'bap' => '1970-01-01 00:00:00',
- 'ban' => $this->encodeJson(array(
+ 'bam' => $this->encodeJson([1, 2, 3]),
+ 'bat' => $this->encodeJson(['foo' => 'bar']),
+ 'bap' => (string) $dt,
+ 'ban' => $this->encodeJson([
'class' => get_class($exception),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(),
'trace' => $this->buildTrace($exception),
- )),
- ), $formatted);
+ ]),
+ ], $formatted);
}
public function testFormatWithErrorContext()
{
- $context = array('file' => 'foo', 'line' => 1);
- $formatted = $this->formatter->format(array(
+ $context = ['file' => 'foo', 'line' => 1];
+ $formatted = $this->formatter->format([
'context' => $context,
- ));
+ ]);
- $this->assertSame(array(
+ $this->assertSame([
'context' => $this->encodeJson($context),
- ), $formatted);
+ ], $formatted);
}
public function testFormatWithExceptionContext()
{
$exception = new \Exception('foo');
- $formatted = $this->formatter->format(array(
- 'context' => array(
+ $formatted = $this->formatter->format([
+ 'context' => [
'exception' => $exception,
- ),
- ));
+ ],
+ ]);
- $this->assertSame(array(
- 'context' => $this->encodeJson(array(
- 'exception' => array(
+ $this->assertSame([
+ 'context' => $this->encodeJson([
+ 'exception' => [
'class' => get_class($exception),
'message' => $exception->getMessage(),
'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(),
'trace' => $this->buildTrace($exception),
- ),
- )),
- ), $formatted);
+ ],
+ ]),
+ ], $formatted);
}
}
diff --git a/tests/Monolog/Formatter/WildfireFormatterTest.php b/tests/Monolog/Formatter/WildfireFormatterTest.php
index 52f15a3..1374947 100644
--- a/tests/Monolog/Formatter/WildfireFormatterTest.php
+++ b/tests/Monolog/Formatter/WildfireFormatterTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,7 @@ namespace Monolog\Formatter;
use Monolog\Logger;
-class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
+class WildfireFormatterTest extends \PHPUnit\Framework\TestCase
{
/**
* @covers Monolog\Formatter\WildfireFormatter::format
@@ -21,15 +21,15 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testDefaultFormat()
{
$wildfire = new WildfireFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('ip' => '127.0.0.1'),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['ip' => '127.0.0.1'],
'message' => 'log',
- );
+ ];
$message = $wildfire->format($record);
@@ -46,15 +46,15 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithFileAndLine()
{
$wildfire = new WildfireFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('from' => 'logger'),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array('ip' => '127.0.0.1', 'file' => 'test', 'line' => 14),
+ 'context' => ['from' => 'logger'],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => ['ip' => '127.0.0.1', 'file' => 'test', 'line' => 14],
'message' => 'log',
- );
+ ];
$message = $wildfire->format($record);
@@ -71,15 +71,15 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testFormatWithoutContext()
{
$wildfire = new WildfireFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
$message = $wildfire->format($record);
@@ -96,17 +96,17 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testBatchFormatThrowException()
{
$wildfire = new WildfireFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array(),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => [],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
- $wildfire->formatBatch(array($record));
+ $wildfire->formatBatch([$record]);
}
/**
@@ -115,22 +115,22 @@ class WildfireFormatterTest extends \PHPUnit_Framework_TestCase
public function testTableFormat()
{
$wildfire = new WildfireFormatter();
- $record = array(
+ $record = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'table-channel',
- 'context' => array(
- WildfireFormatter::TABLE => array(
- array('col1', 'col2', 'col3'),
- array('val1', 'val2', 'val3'),
- array('foo1', 'foo2', 'foo3'),
- array('bar1', 'bar2', 'bar3'),
- ),
- ),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => [
+ WildfireFormatter::TABLE => [
+ ['col1', 'col2', 'col3'],
+ ['val1', 'val2', 'val3'],
+ ['foo1', 'foo2', 'foo3'],
+ ['bar1', 'bar2', 'bar3'],
+ ],
+ ],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'table-message',
- );
+ ];
$message = $wildfire->format($record);
diff --git a/tests/Monolog/Handler/AbstractHandlerTest.php b/tests/Monolog/Handler/AbstractHandlerTest.php
index 568eb9d..b7451a7 100644
--- a/tests/Monolog/Handler/AbstractHandlerTest.php
+++ b/tests/Monolog/Handler/AbstractHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,10 +11,8 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
-use Monolog\Formatter\LineFormatter;
-use Monolog\Processor\WebProcessor;
class AbstractHandlerTest extends TestCase
{
@@ -24,21 +22,17 @@ class AbstractHandlerTest extends TestCase
* @covers Monolog\Handler\AbstractHandler::setLevel
* @covers Monolog\Handler\AbstractHandler::getBubble
* @covers Monolog\Handler\AbstractHandler::setBubble
- * @covers Monolog\Handler\AbstractHandler::getFormatter
- * @covers Monolog\Handler\AbstractHandler::setFormatter
*/
public function testConstructAndGetSet()
{
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false));
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]);
$this->assertEquals(Logger::WARNING, $handler->getLevel());
$this->assertEquals(false, $handler->getBubble());
$handler->setLevel(Logger::ERROR);
$handler->setBubble(true);
- $handler->setFormatter($formatter = new LineFormatter);
$this->assertEquals(Logger::ERROR, $handler->getLevel());
$this->assertEquals(true, $handler->getBubble());
- $this->assertSame($formatter, $handler->getFormatter());
}
/**
@@ -49,7 +43,7 @@ class AbstractHandlerTest extends TestCase
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');
$handler->expects($this->exactly(2))
->method('handle');
- $handler->handleBatch(array($this->getRecord(), $this->getRecord()));
+ $handler->handleBatch([$this->getRecord(), $this->getRecord()]);
}
/**
@@ -57,7 +51,7 @@ class AbstractHandlerTest extends TestCase
*/
public function testIsHandling()
{
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false));
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]);
$this->assertTrue($handler->isHandling($this->getRecord()));
$this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
}
@@ -67,49 +61,9 @@ class AbstractHandlerTest extends TestCase
*/
public function testHandlesPsrStyleLevels()
{
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array('warning', false));
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', ['warning', false]);
$this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG)));
$handler->setLevel('debug');
$this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG)));
}
-
- /**
- * @covers Monolog\Handler\AbstractHandler::getFormatter
- * @covers Monolog\Handler\AbstractHandler::getDefaultFormatter
- */
- public function testGetFormatterInitializesDefault()
- {
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');
- $this->assertInstanceOf('Monolog\Formatter\LineFormatter', $handler->getFormatter());
- }
-
- /**
- * @covers Monolog\Handler\AbstractHandler::pushProcessor
- * @covers Monolog\Handler\AbstractHandler::popProcessor
- * @expectedException LogicException
- */
- public function testPushPopProcessor()
- {
- $logger = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');
- $processor1 = new WebProcessor;
- $processor2 = new WebProcessor;
-
- $logger->pushProcessor($processor1);
- $logger->pushProcessor($processor2);
-
- $this->assertEquals($processor2, $logger->popProcessor());
- $this->assertEquals($processor1, $logger->popProcessor());
- $logger->popProcessor();
- }
-
- /**
- * @covers Monolog\Handler\AbstractHandler::pushProcessor
- * @expectedException InvalidArgumentException
- */
- public function testPushProcessorWithNonCallable()
- {
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler');
-
- $handler->pushProcessor(new \stdClass());
- }
}
diff --git a/tests/Monolog/Handler/AbstractProcessingHandlerTest.php b/tests/Monolog/Handler/AbstractProcessingHandlerTest.php
index 24d4f63..58d0920 100644
--- a/tests/Monolog/Handler/AbstractProcessingHandlerTest.php
+++ b/tests/Monolog/Handler/AbstractProcessingHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,18 +11,30 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Monolog\Processor\WebProcessor;
+use Monolog\Formatter\LineFormatter;
class AbstractProcessingHandlerTest extends TestCase
{
/**
+ * @covers Monolog\Handler\FormattableHandlerTrait::getFormatter
+ * @covers Monolog\Handler\FormattableHandlerTrait::setFormatter
+ */
+ public function testConstructAndGetSet()
+ {
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, false]);
+ $handler->setFormatter($formatter = new LineFormatter);
+ $this->assertSame($formatter, $handler->getFormatter());
+ }
+
+ /**
* @covers Monolog\Handler\AbstractProcessingHandler::handle
*/
public function testHandleLowerLevelMessage()
{
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, true));
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, true]);
$this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG)));
}
@@ -31,7 +43,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/
public function testHandleBubbling()
{
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, true));
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::DEBUG, true]);
$this->assertFalse($handler->handle($this->getRecord()));
}
@@ -40,7 +52,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/
public function testHandleNotBubbling()
{
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, false));
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::DEBUG, false]);
$this->assertTrue($handler->handle($this->getRecord()));
}
@@ -49,7 +61,7 @@ class AbstractProcessingHandlerTest extends TestCase
*/
public function testHandleIsFalseWhenNotHandled()
{
- $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, false));
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, false]);
$this->assertTrue($handler->handle($this->getRecord()));
$this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG)));
}
@@ -60,13 +72,13 @@ class AbstractProcessingHandlerTest extends TestCase
public function testProcessRecord()
{
$handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler');
- $handler->pushProcessor(new WebProcessor(array(
+ $handler->pushProcessor(new WebProcessor([
'REQUEST_URI' => '',
'REQUEST_METHOD' => '',
'REMOTE_ADDR' => '',
'SERVER_NAME' => '',
'UNIQUE_ID' => '',
- )));
+ ]));
$handledRecord = null;
$handler->expects($this->once())
->method('write')
@@ -77,4 +89,44 @@ class AbstractProcessingHandlerTest extends TestCase
$handler->handle($this->getRecord());
$this->assertEquals(6, count($handledRecord['extra']));
}
+
+ /**
+ * @covers Monolog\Handler\ProcessableHandlerTrait::pushProcessor
+ * @covers Monolog\Handler\ProcessableHandlerTrait::popProcessor
+ * @expectedException LogicException
+ */
+ public function testPushPopProcessor()
+ {
+ $logger = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler');
+ $processor1 = new WebProcessor;
+ $processor2 = new WebProcessor;
+
+ $logger->pushProcessor($processor1);
+ $logger->pushProcessor($processor2);
+
+ $this->assertEquals($processor2, $logger->popProcessor());
+ $this->assertEquals($processor1, $logger->popProcessor());
+ $logger->popProcessor();
+ }
+
+ /**
+ * @covers Monolog\Handler\ProcessableHandlerTrait::pushProcessor
+ * @expectedException TypeError
+ */
+ public function testPushProcessorWithNonCallable()
+ {
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler');
+
+ $handler->pushProcessor(new \stdClass());
+ }
+
+ /**
+ * @covers Monolog\Handler\FormattableHandlerTrait::getFormatter
+ * @covers Monolog\Handler\FormattableHandlerTrait::getDefaultFormatter
+ */
+ public function testGetFormatterInitializesDefault()
+ {
+ $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler');
+ $this->assertInstanceOf(LineFormatter::class, $handler->getFormatter());
+ }
}
diff --git a/tests/Monolog/Handler/AmqpHandlerTest.php b/tests/Monolog/Handler/AmqpHandlerTest.php
index 8e0e723..680de29 100644
--- a/tests/Monolog/Handler/AmqpHandlerTest.php
+++ b/tests/Monolog/Handler/AmqpHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Connection\AMQPConnection;
@@ -31,43 +31,43 @@ class AmqpHandlerTest extends TestCase
$this->markTestSkipped("Please update AMQP to version >= 1.0");
}
- $messages = array();
+ $messages = [];
+
+ $exchange = $this->getMockBuilder('AMQPExchange')
+ ->setMethods(['publish', 'setName'])
+ ->disableOriginalConstructor()
+ ->getMock();
- $exchange = $this->getMock('AMQPExchange', array('publish', 'setName'), array(), '', false);
- $exchange->expects($this->once())
- ->method('setName')
- ->with('log')
- ;
$exchange->expects($this->any())
->method('publish')
- ->will($this->returnCallback(function ($message, $routing_key, $flags = 0, $attributes = array()) use (&$messages) {
- $messages[] = array($message, $routing_key, $flags, $attributes);
+ ->will($this->returnCallback(function ($message, $routing_key, $flags = 0, $attributes = []) use (&$messages) {
+ $messages[] = [$message, $routing_key, $flags, $attributes];
}))
;
- $handler = new AmqpHandler($exchange, 'log');
+ $handler = new AmqpHandler($exchange);
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
+ $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
- $expected = array(
- array(
+ $expected = [
+ [
'message' => 'test',
- 'context' => array(
- 'data' => array(),
+ 'context' => [
+ 'data' => [],
'foo' => 34,
- ),
+ ],
'level' => 300,
'level_name' => 'WARNING',
'channel' => 'test',
- 'extra' => array(),
- ),
- 'warn.test',
+ 'extra' => [],
+ ],
+ 'warning.test',
0,
- array(
+ [
'delivery_mode' => 2,
'content_type' => 'application/json',
- ),
- );
+ ],
+ ];
$handler->handle($record);
@@ -83,43 +83,46 @@ class AmqpHandlerTest extends TestCase
$this->markTestSkipped("php-amqplib not installed");
}
- $messages = array();
+ $messages = [];
- $exchange = $this->getMock('PhpAmqpLib\Channel\AMQPChannel', array('basic_publish', '__destruct'), array(), '', false);
+ $exchange = $this->getMockBuilder('PhpAmqpLib\Channel\AMQPChannel')
+ ->setMethods(['basic_publish', '__destruct'])
+ ->disableOriginalConstructor()
+ ->getMock();
$exchange->expects($this->any())
->method('basic_publish')
->will($this->returnCallback(function (AMQPMessage $msg, $exchange = "", $routing_key = "", $mandatory = false, $immediate = false, $ticket = null) use (&$messages) {
- $messages[] = array($msg, $exchange, $routing_key, $mandatory, $immediate, $ticket);
+ $messages[] = [$msg, $exchange, $routing_key, $mandatory, $immediate, $ticket];
}))
;
$handler = new AmqpHandler($exchange, 'log');
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
+ $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
- $expected = array(
- array(
+ $expected = [
+ [
'message' => 'test',
- 'context' => array(
- 'data' => array(),
+ 'context' => [
+ 'data' => [],
'foo' => 34,
- ),
+ ],
'level' => 300,
'level_name' => 'WARNING',
'channel' => 'test',
- 'extra' => array(),
- ),
+ 'extra' => [],
+ ],
'log',
- 'warn.test',
+ 'warning.test',
false,
false,
null,
- array(
+ [
'delivery_mode' => 2,
'content_type' => 'application/json',
- ),
- );
+ ],
+ ];
$handler->handle($record);
diff --git a/tests/Monolog/Handler/BrowserConsoleHandlerTest.php b/tests/Monolog/Handler/BrowserConsoleHandlerTest.php
index ffb1d74..048ee1c 100644
--- a/tests/Monolog/Handler/BrowserConsoleHandlerTest.php
+++ b/tests/Monolog/Handler/BrowserConsoleHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -89,7 +89,7 @@ EOF;
$handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter());
- $handler->handle($this->getRecord(Logger::DEBUG, 'test', array('foo' => 'bar')));
+ $handler->handle($this->getRecord(Logger::DEBUG, 'test', ['foo' => 'bar']));
$expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
diff --git a/tests/Monolog/Handler/BufferHandlerTest.php b/tests/Monolog/Handler/BufferHandlerTest.php
index da8b3c3..f1338b4 100644
--- a/tests/Monolog/Handler/BufferHandlerTest.php
+++ b/tests/Monolog/Handler/BufferHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
class BufferHandlerTest extends TestCase
@@ -47,7 +47,7 @@ class BufferHandlerTest extends TestCase
$handler->handle($this->getRecord(Logger::WARNING));
$handler->handle($this->getRecord(Logger::DEBUG));
$this->shutdownCheckHandler = $test;
- register_shutdown_function(array($this, 'checkPropagation'));
+ register_shutdown_function([$this, 'checkPropagation']);
}
public function checkPropagation()
diff --git a/tests/Monolog/Handler/ChromePHPHandlerTest.php b/tests/Monolog/Handler/ChromePHPHandlerTest.php
index 0449f8b..e9a1f98 100644
--- a/tests/Monolog/Handler/ChromePHPHandlerTest.php
+++ b/tests/Monolog/Handler/ChromePHPHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -37,17 +37,17 @@ class ChromePHPHandlerTest extends TestCase
$handler->handle($this->getRecord(Logger::DEBUG));
$handler->handle($this->getRecord(Logger::WARNING));
- $expected = array(
- 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array(
+ $expected = [
+ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([
'version' => ChromePHPHandler::VERSION,
- 'columns' => array('label', 'log', 'backtrace', 'type'),
- 'rows' => array(
+ 'columns' => ['label', 'log', 'backtrace', 'type'],
+ 'rows' => [
'test',
'test',
- ),
+ ],
'request_uri' => '',
- )))),
- );
+ ]))),
+ ];
$this->assertEquals($expected, $handler->getHeaders());
}
@@ -71,33 +71,33 @@ class ChromePHPHandlerTest extends TestCase
// overflow chrome headers limit
$handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 100 * 1024)));
- $expected = array(
- 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array(
+ $expected = [
+ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([
'version' => ChromePHPHandler::VERSION,
- 'columns' => array('label', 'log', 'backtrace', 'type'),
- 'rows' => array(
- array(
+ 'columns' => ['label', 'log', 'backtrace', 'type'],
+ 'rows' => [
+ [
'test',
'test',
'unknown',
'log',
- ),
- array(
+ ],
+ [
'test',
str_repeat('a', 150 * 1024),
'unknown',
'warn',
- ),
- array(
+ ],
+ [
'monolog',
'Incomplete logs, chrome header size limit reached',
'unknown',
'warn',
- ),
- ),
+ ],
+ ],
'request_uri' => '',
- )))),
- );
+ ]))),
+ ];
$this->assertEquals($expected, $handler->getHeaders());
}
@@ -114,19 +114,19 @@ class ChromePHPHandlerTest extends TestCase
$handler2->handle($this->getRecord(Logger::DEBUG));
$handler2->handle($this->getRecord(Logger::WARNING));
- $expected = array(
- 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array(
+ $expected = [
+ 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([
'version' => ChromePHPHandler::VERSION,
- 'columns' => array('label', 'log', 'backtrace', 'type'),
- 'rows' => array(
+ 'columns' => ['label', 'log', 'backtrace', 'type'],
+ 'rows' => [
'test',
'test',
'test',
'test',
- ),
+ ],
'request_uri' => '',
- )))),
- );
+ ]))),
+ ];
$this->assertEquals($expected, $handler2->getHeaders());
}
@@ -134,14 +134,14 @@ class ChromePHPHandlerTest extends TestCase
class TestChromePHPHandler extends ChromePHPHandler
{
- protected $headers = array();
+ protected $headers = [];
public static function reset()
{
self::$initialized = false;
self::$overflowed = false;
self::$sendHeaders = true;
- self::$json['rows'] = array();
+ self::$json['rows'] = [];
}
protected function sendHeader($header, $content)
diff --git a/tests/Monolog/Handler/CouchDBHandlerTest.php b/tests/Monolog/Handler/CouchDBHandlerTest.php
index 9fc4b38..f89a130 100644
--- a/tests/Monolog/Handler/CouchDBHandlerTest.php
+++ b/tests/Monolog/Handler/CouchDBHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,14 +11,14 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
class CouchDBHandlerTest extends TestCase
{
public function testHandle()
{
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
+ $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new CouchDBHandler();
diff --git a/tests/Monolog/Handler/DeduplicationHandlerTest.php b/tests/Monolog/Handler/DeduplicationHandlerTest.php
index e2aff86..491fd85 100644
--- a/tests/Monolog/Handler/DeduplicationHandlerTest.php
+++ b/tests/Monolog/Handler/DeduplicationHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
class DeduplicationHandlerTest extends TestCase
@@ -88,10 +88,10 @@ class DeduplicationHandlerTest extends TestCase
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0);
$record = $this->getRecord(Logger::ERROR);
- $record['datetime']->modify('+62seconds');
+ $record['datetime'] = $record['datetime']->modify('+62seconds');
$handler->handle($record);
$record = $this->getRecord(Logger::CRITICAL);
- $record['datetime']->modify('+62seconds');
+ $record['datetime'] = $record['datetime']->modify('+62seconds');
$handler->handle($record);
$handler->flush();
@@ -115,13 +115,13 @@ class DeduplicationHandlerTest extends TestCase
// handle two records from yesterday, and one recent
$record = $this->getRecord(Logger::ERROR);
- $record['datetime']->modify('-1day -10seconds');
+ $record['datetime'] = $record['datetime']->modify('-1day -10seconds');
$handler->handle($record);
$record2 = $this->getRecord(Logger::CRITICAL);
- $record2['datetime']->modify('-1day -10seconds');
+ $record2['datetime'] = $record2['datetime']->modify('-1day -10seconds');
$handler->handle($record2);
$record3 = $this->getRecord(Logger::CRITICAL);
- $record3['datetime']->modify('-30seconds');
+ $record3['datetime'] = $record3['datetime']->modify('-30seconds');
$handler->handle($record3);
// log is written as none of them are duplicate
diff --git a/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php b/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php
index d67da90..f72f323 100644
--- a/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php
+++ b/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
class DoctrineCouchDBHandlerTest extends TestCase
@@ -26,21 +26,21 @@ class DoctrineCouchDBHandlerTest extends TestCase
public function testHandle()
{
$client = $this->getMockBuilder('Doctrine\\CouchDB\\CouchDBClient')
- ->setMethods(array('postDocument'))
+ ->setMethods(['postDocument'])
->disableOriginalConstructor()
->getMock();
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
+ $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
- $expected = array(
+ $expected = [
'message' => 'test',
- 'context' => array('data' => '[object] (stdClass: {})', 'foo' => 34),
+ 'context' => ['data' => ['stdClass' => []], 'foo' => 34],
'level' => Logger::WARNING,
'level_name' => 'WARNING',
'channel' => 'test',
- 'datetime' => $record['datetime']->format('Y-m-d H:i:s'),
- 'extra' => array(),
- );
+ 'datetime' => (string) $record['datetime'],
+ 'extra' => [],
+ ];
$client->expects($this->once())
->method('postDocument')
diff --git a/tests/Monolog/Handler/DynamoDbHandlerTest.php b/tests/Monolog/Handler/DynamoDbHandlerTest.php
index 2e6c348..9d61356 100644
--- a/tests/Monolog/Handler/DynamoDbHandlerTest.php
+++ b/tests/Monolog/Handler/DynamoDbHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class DynamoDbHandlerTest extends TestCase
{
@@ -24,8 +24,9 @@ class DynamoDbHandlerTest extends TestCase
}
$this->client = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient')
- ->setMethods(array('formatAttributes', '__call'))
- ->disableOriginalConstructor()->getMock();
+ ->setMethods(['formatAttributes', '__call'])
+ ->disableOriginalConstructor()
+ ->getMock();
}
public function testConstruct()
@@ -47,8 +48,8 @@ class DynamoDbHandlerTest extends TestCase
public function testHandle()
{
$record = $this->getRecord();
- $formatter = $this->getMock('Monolog\Formatter\FormatterInterface');
- $formatted = array('foo' => 1, 'bar' => 2);
+ $formatter = $this->createMock('Monolog\Formatter\FormatterInterface');
+ $formatted = ['foo' => 1, 'bar' => 2];
$handler = new DynamoDbHandler($this->client, 'foo');
$handler->setFormatter($formatter);
@@ -72,10 +73,10 @@ class DynamoDbHandlerTest extends TestCase
$this->client
->expects($this->once())
->method('__call')
- ->with('putItem', array(array(
+ ->with('putItem', [[
'TableName' => 'foo',
'Item' => $expFormatted,
- )));
+ ]]);
$handler->handle($record);
}
diff --git a/tests/Monolog/Handler/ElasticSearchHandlerTest.php b/tests/Monolog/Handler/ElasticSearchHandlerTest.php
index 1687074..e0e207d 100644
--- a/tests/Monolog/Handler/ElasticSearchHandlerTest.php
+++ b/tests/Monolog/Handler/ElasticSearchHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\ElasticaFormatter;
use Monolog\Formatter\NormalizerFormatter;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Elastica\Client;
use Elastica\Request;
@@ -29,10 +29,10 @@ class ElasticSearchHandlerTest extends TestCase
/**
* @var array Default handler options
*/
- protected $options = array(
+ protected $options = [
'index' => 'my_index',
'type' => 'doc_type',
- );
+ ];
public function setUp()
{
@@ -43,7 +43,7 @@ class ElasticSearchHandlerTest extends TestCase
// base mock Elastica Client object
$this->client = $this->getMockBuilder('Elastica\Client')
- ->setMethods(array('addDocuments'))
+ ->setMethods(['addDocuments'])
->disableOriginalConstructor()
->getMock();
}
@@ -57,19 +57,19 @@ class ElasticSearchHandlerTest extends TestCase
public function testHandle()
{
// log message
- $msg = array(
+ $msg = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('foo' => 7, 'bar', 'class' => new \stdClass),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
// format expected result
$formatter = new ElasticaFormatter($this->options['index'], $this->options['type']);
- $expected = array($formatter->format($msg));
+ $expected = [$formatter->format($msg)];
// setup ES client mock
$this->client->expects($this->any())
@@ -79,7 +79,7 @@ class ElasticSearchHandlerTest extends TestCase
// perform tests
$handler = new ElasticSearchHandler($this->client, $this->options);
$handler->handle($msg);
- $handler->handleBatch(array($msg));
+ $handler->handleBatch([$msg]);
}
/**
@@ -113,11 +113,11 @@ class ElasticSearchHandlerTest extends TestCase
*/
public function testOptions()
{
- $expected = array(
+ $expected = [
'index' => $this->options['index'],
'type' => $this->options['type'],
'ignore_error' => false,
- );
+ ];
$handler = new ElasticSearchHandler($this->client, $this->options);
$this->assertEquals($expected, $handler->getOptions());
}
@@ -128,13 +128,14 @@ class ElasticSearchHandlerTest extends TestCase
*/
public function testConnectionErrors($ignore, $expectedError)
{
- $clientOpts = array('host' => '127.0.0.1', 'port' => 1);
+ $clientOpts = ['host' => '127.0.0.1', 'port' => 1];
$client = new Client($clientOpts);
- $handlerOpts = array('ignore_error' => $ignore);
+ $handlerOpts = ['ignore_error' => $ignore];
$handler = new ElasticSearchHandler($client, $handlerOpts);
if ($expectedError) {
- $this->setExpectedException($expectedError[0], $expectedError[1]);
+ $this->expectException($expectedError[0]);
+ $this->expectExceptionMessage($expectedError[1]);
$handler->handle($this->getRecord());
} else {
$this->assertFalse($handler->handle($this->getRecord()));
@@ -146,10 +147,10 @@ class ElasticSearchHandlerTest extends TestCase
*/
public function providerTestConnectionErrors()
{
- return array(
- array(false, array('RuntimeException', 'Error sending messages to Elasticsearch')),
- array(true, false),
- );
+ return [
+ [false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
+ [true, false],
+ ];
}
/**
@@ -162,28 +163,28 @@ class ElasticSearchHandlerTest extends TestCase
*/
public function testHandleIntegration()
{
- $msg = array(
+ $msg = [
'level' => Logger::ERROR,
'level_name' => 'ERROR',
'channel' => 'meh',
- 'context' => array('foo' => 7, 'bar', 'class' => new \stdClass),
- 'datetime' => new \DateTime("@0"),
- 'extra' => array(),
+ 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass],
+ 'datetime' => new \DateTimeImmutable("@0"),
+ 'extra' => [],
'message' => 'log',
- );
+ ];
$expected = $msg;
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
- $expected['context'] = array(
+ $expected['context'] = [
'class' => '[object] (stdClass: {})',
'foo' => 7,
0 => 'bar',
- );
+ ];
$client = new Client();
$handler = new ElasticSearchHandler($client, $this->options);
try {
- $handler->handleBatch(array($msg));
+ $handler->handleBatch([$msg]);
} catch (\RuntimeException $e) {
$this->markTestSkipped("Cannot connect to Elastic Search server on localhost");
}
@@ -234,6 +235,6 @@ class ElasticSearchHandlerTest extends TestCase
return $data['_source'];
}
- return array();
+ return [];
}
}
diff --git a/tests/Monolog/Handler/ErrorLogHandlerTest.php b/tests/Monolog/Handler/ErrorLogHandlerTest.php
index 99785cb..d230fb1 100644
--- a/tests/Monolog/Handler/ErrorLogHandlerTest.php
+++ b/tests/Monolog/Handler/ErrorLogHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
@@ -24,7 +24,7 @@ class ErrorLogHandlerTest extends TestCase
{
protected function setUp()
{
- $GLOBALS['error_log'] = array();
+ $GLOBALS['error_log'] = [];
}
/**
diff --git a/tests/Monolog/Handler/FilterHandlerTest.php b/tests/Monolog/Handler/FilterHandlerTest.php
index 31b7686..0e64e76 100644
--- a/tests/Monolog/Handler/FilterHandlerTest.php
+++ b/tests/Monolog/Handler/FilterHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class FilterHandlerTest extends TestCase
{
@@ -63,7 +63,7 @@ class FilterHandlerTest extends TestCase
$this->assertFalse($test->hasEmergencyRecords());
$test = new TestHandler();
- $handler = new FilterHandler($test, array(Logger::INFO, Logger::ERROR));
+ $handler = new FilterHandler($test, [Logger::INFO, Logger::ERROR]);
$handler->handle($this->getRecord(Logger::DEBUG));
$this->assertFalse($test->hasDebugRecords());
@@ -86,14 +86,14 @@ class FilterHandlerTest extends TestCase
$test = new TestHandler();
$handler = new FilterHandler($test);
- $levels = array(Logger::INFO, Logger::ERROR);
+ $levels = [Logger::INFO, Logger::ERROR];
$handler->setAcceptedLevels($levels);
$this->assertSame($levels, $handler->getAcceptedLevels());
- $handler->setAcceptedLevels(array('info', 'error'));
+ $handler->setAcceptedLevels(['info', 'error']);
$this->assertSame($levels, $handler->getAcceptedLevels());
- $levels = array(Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY);
+ $levels = [Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY];
$handler->setAcceptedLevels(Logger::CRITICAL, Logger::EMERGENCY);
$this->assertSame($levels, $handler->getAcceptedLevels());
diff --git a/tests/Monolog/Handler/FingersCrossedHandlerTest.php b/tests/Monolog/Handler/FingersCrossedHandlerTest.php
index b92bf43..5b25a36 100644
--- a/tests/Monolog/Handler/FingersCrossedHandlerTest.php
+++ b/tests/Monolog/Handler/FingersCrossedHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy;
use Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy;
@@ -114,8 +114,8 @@ class FingersCrossedHandlerTest extends TestCase
{
$test = new TestHandler();
$handler = new FingersCrossedHandler(function ($record, $handler) use ($test) {
- return $test;
- });
+ return $test;
+ });
$handler->handle($this->getRecord(Logger::DEBUG));
$handler->handle($this->getRecord(Logger::INFO));
$this->assertFalse($test->hasDebugRecords());
@@ -133,8 +133,8 @@ class FingersCrossedHandlerTest extends TestCase
public function testHandleWithBadCallbackThrowsException()
{
$handler = new FingersCrossedHandler(function ($record, $handler) {
- return 'foo';
- });
+ return 'foo';
+ });
$handler->handle($this->getRecord(Logger::WARNING));
}
@@ -203,7 +203,7 @@ class FingersCrossedHandlerTest extends TestCase
public function testChannelLevelActivationStrategy()
{
$test = new TestHandler();
- $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, array('othertest' => Logger::DEBUG)));
+ $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, ['othertest' => Logger::DEBUG]));
$handler->handle($this->getRecord(Logger::WARNING));
$this->assertFalse($test->hasWarningRecords());
$record = $this->getRecord(Logger::DEBUG);
@@ -220,7 +220,7 @@ class FingersCrossedHandlerTest extends TestCase
public function testChannelLevelActivationStrategyWithPsrLevels()
{
$test = new TestHandler();
- $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', array('othertest' => 'debug')));
+ $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', ['othertest' => 'debug']));
$handler->handle($this->getRecord(Logger::WARNING));
$this->assertFalse($test->hasWarningRecords());
$record = $this->getRecord(Logger::DEBUG);
diff --git a/tests/Monolog/Handler/FirePHPHandlerTest.php b/tests/Monolog/Handler/FirePHPHandlerTest.php
index 0eb10a6..b62e7fd 100644
--- a/tests/Monolog/Handler/FirePHPHandlerTest.php
+++ b/tests/Monolog/Handler/FirePHPHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -32,13 +32,13 @@ class FirePHPHandlerTest extends TestCase
$handler->handle($this->getRecord(Logger::DEBUG));
$handler->handle($this->getRecord(Logger::WARNING));
- $expected = array(
+ $expected = [
'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2',
'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1',
'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3',
'X-Wf-1-1-1-1' => 'test',
'X-Wf-1-1-1-2' => 'test',
- );
+ ];
$this->assertEquals($expected, $handler->getHeaders());
}
@@ -55,18 +55,18 @@ class FirePHPHandlerTest extends TestCase
$handler2->handle($this->getRecord(Logger::DEBUG));
$handler2->handle($this->getRecord(Logger::WARNING));
- $expected = array(
+ $expected = [
'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2',
'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1',
'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3',
'X-Wf-1-1-1-1' => 'test',
'X-Wf-1-1-1-2' => 'test',
- );
+ ];
- $expected2 = array(
+ $expected2 = [
'X-Wf-1-1-1-3' => 'test',
'X-Wf-1-1-1-4' => 'test',
- );
+ ];
$this->assertEquals($expected, $handler->getHeaders());
$this->assertEquals($expected2, $handler2->getHeaders());
@@ -75,7 +75,7 @@ class FirePHPHandlerTest extends TestCase
class TestFirePHPHandler extends FirePHPHandler
{
- protected $headers = array();
+ protected $headers = [];
public static function reset()
{
diff --git a/tests/Monolog/Handler/FleepHookHandlerTest.php b/tests/Monolog/Handler/FleepHookHandlerTest.php
index 91cdd31..11b5a65 100644
--- a/tests/Monolog/Handler/FleepHookHandlerTest.php
+++ b/tests/Monolog/Handler/FleepHookHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
/**
* @coversDefaultClass \Monolog\Handler\FleepHookHandler
@@ -56,15 +56,15 @@ class FleepHookHandlerTest extends TestCase
*/
public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays()
{
- $record = array(
+ $record = [
'message' => 'msg',
- 'context' => array(),
+ 'context' => [],
'level' => Logger::DEBUG,
'level_name' => Logger::getLevelName(Logger::DEBUG),
'channel' => 'channel',
- 'datetime' => new \DateTime(),
- 'extra' => array(),
- );
+ 'datetime' => new \DateTimeImmutable(),
+ 'extra' => [],
+ ];
$expectedFormatter = new LineFormatter(null, null, true, true);
$expected = $expectedFormatter->format($record);
diff --git a/tests/Monolog/Handler/FlowdockHandlerTest.php b/tests/Monolog/Handler/FlowdockHandlerTest.php
index 4b120d5..23f8b06 100644
--- a/tests/Monolog/Handler/FlowdockHandlerTest.php
+++ b/tests/Monolog/Handler/FlowdockHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use Monolog\Formatter\FlowdockFormatter;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -61,15 +61,14 @@ class FlowdockHandlerTest extends TestCase
private function createHandler($token = 'myToken')
{
- $constructorArgs = array($token, Logger::DEBUG);
+ $constructorArgs = [$token, Logger::DEBUG];
$this->res = fopen('php://memory', 'a');
- $this->handler = $this->getMock(
- '\Monolog\Handler\FlowdockHandler',
- array('fsockopen', 'streamSetTimeout', 'closeSocket'),
- $constructorArgs
- );
+ $this->handler = $this->getMockBuilder('Monolog\Handler\FlowdockHandler')
+ ->setConstructorArgs($constructorArgs)
+ ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
+ ->getMock();
- $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
+ $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this->handler, 'localhost:1234');
diff --git a/tests/Monolog/Handler/GelfHandlerLegacyTest.php b/tests/Monolog/Handler/GelfHandlerLegacyTest.php
deleted file mode 100644
index 9d007b1..0000000
--- a/tests/Monolog/Handler/GelfHandlerLegacyTest.php
+++ /dev/null
@@ -1,95 +0,0 @@
-<?php
-
-/*
- * This file is part of the Monolog package.
- *
- * (c) Jordi Boggiano <j.boggiano@seld.be>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Monolog\Handler;
-
-use Gelf\Message;
-use Monolog\TestCase;
-use Monolog\Logger;
-use Monolog\Formatter\GelfMessageFormatter;
-
-class GelfHandlerLegacyTest extends TestCase
-{
- public function setUp()
- {
- if (!class_exists('Gelf\MessagePublisher') || !class_exists('Gelf\Message')) {
- $this->markTestSkipped("mlehner/gelf-php not installed");
- }
-
- require_once __DIR__ . '/GelfMockMessagePublisher.php';
- }
-
- /**
- * @covers Monolog\Handler\GelfHandler::__construct
- */
- public function testConstruct()
- {
- $handler = new GelfHandler($this->getMessagePublisher());
- $this->assertInstanceOf('Monolog\Handler\GelfHandler', $handler);
- }
-
- protected function getHandler($messagePublisher)
- {
- $handler = new GelfHandler($messagePublisher);
-
- return $handler;
- }
-
- protected function getMessagePublisher()
- {
- return new GelfMockMessagePublisher('localhost');
- }
-
- public function testDebug()
- {
- $messagePublisher = $this->getMessagePublisher();
- $handler = $this->getHandler($messagePublisher);
-
- $record = $this->getRecord(Logger::DEBUG, "A test debug message");
- $handler->handle($record);
-
- $this->assertEquals(7, $messagePublisher->lastMessage->getLevel());
- $this->assertEquals('test', $messagePublisher->lastMessage->getFacility());
- $this->assertEquals($record['message'], $messagePublisher->lastMessage->getShortMessage());
- $this->assertEquals(null, $messagePublisher->lastMessage->getFullMessage());
- }
-
- public function testWarning()
- {
- $messagePublisher = $this->getMessagePublisher();
- $handler = $this->getHandler($messagePublisher);
-
- $record = $this->getRecord(Logger::WARNING, "A test warning message");
- $handler->handle($record);
-
- $this->assertEquals(4, $messagePublisher->lastMessage->getLevel());
- $this->assertEquals('test', $messagePublisher->lastMessage->getFacility());
- $this->assertEquals($record['message'], $messagePublisher->lastMessage->getShortMessage());
- $this->assertEquals(null, $messagePublisher->lastMessage->getFullMessage());
- }
-
- public function testInjectedGelfMessageFormatter()
- {
- $messagePublisher = $this->getMessagePublisher();
- $handler = $this->getHandler($messagePublisher);
-
- $handler->setFormatter(new GelfMessageFormatter('mysystem', 'EXT', 'CTX'));
-
- $record = $this->getRecord(Logger::WARNING, "A test warning message");
- $record['extra']['blarg'] = 'yep';
- $record['context']['from'] = 'logger';
- $handler->handle($record);
-
- $this->assertEquals('mysystem', $messagePublisher->lastMessage->getHost());
- $this->assertArrayHasKey('_EXTblarg', $messagePublisher->lastMessage->toArray());
- $this->assertArrayHasKey('_CTXfrom', $messagePublisher->lastMessage->toArray());
- }
-}
diff --git a/tests/Monolog/Handler/GelfHandlerTest.php b/tests/Monolog/Handler/GelfHandlerTest.php
index 8cdd64f..12e5f8b 100644
--- a/tests/Monolog/Handler/GelfHandlerTest.php
+++ b/tests/Monolog/Handler/GelfHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use Gelf\Message;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Monolog\Formatter\GelfMessageFormatter;
@@ -43,7 +43,10 @@ class GelfHandlerTest extends TestCase
protected function getMessagePublisher()
{
- return $this->getMock('Gelf\Publisher', array('publish'), array(), '', false);
+ return $this->getMockBuilder('Gelf\Publisher')
+ ->setMethods(['publish'])
+ ->disableOriginalConstructor()
+ ->getMock();
}
public function testDebug()
diff --git a/tests/Monolog/Handler/GelfMockMessagePublisher.php b/tests/Monolog/Handler/GelfMockMessagePublisher.php
deleted file mode 100644
index 873d92f..0000000
--- a/tests/Monolog/Handler/GelfMockMessagePublisher.php
+++ /dev/null
@@ -1,25 +0,0 @@
-<?php
-
-/*
- * This file is part of the Monolog package.
- *
- * (c) Jordi Boggiano <j.boggiano@seld.be>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
-
-namespace Monolog\Handler;
-
-use Gelf\MessagePublisher;
-use Gelf\Message;
-
-class GelfMockMessagePublisher extends MessagePublisher
-{
- public function publish(Message $message)
- {
- $this->lastMessage = $message;
- }
-
- public $lastMessage = null;
-}
diff --git a/tests/Monolog/Handler/GroupHandlerTest.php b/tests/Monolog/Handler/GroupHandlerTest.php
index a1b8617..d0ffdf0 100644
--- a/tests/Monolog/Handler/GroupHandlerTest.php
+++ b/tests/Monolog/Handler/GroupHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
class GroupHandlerTest extends TestCase
@@ -22,7 +22,7 @@ class GroupHandlerTest extends TestCase
*/
public function testConstructorOnlyTakesHandler()
{
- new GroupHandler(array(new TestHandler(), "foo"));
+ new GroupHandler([new TestHandler(), "foo"]);
}
/**
@@ -31,7 +31,7 @@ class GroupHandlerTest extends TestCase
*/
public function testHandle()
{
- $testHandlers = array(new TestHandler(), new TestHandler());
+ $testHandlers = [new TestHandler(), new TestHandler()];
$handler = new GroupHandler($testHandlers);
$handler->handle($this->getRecord(Logger::DEBUG));
$handler->handle($this->getRecord(Logger::INFO));
@@ -47,9 +47,9 @@ class GroupHandlerTest extends TestCase
*/
public function testHandleBatch()
{
- $testHandlers = array(new TestHandler(), new TestHandler());
+ $testHandlers = [new TestHandler(), new TestHandler()];
$handler = new GroupHandler($testHandlers);
- $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)));
+ $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
@@ -62,7 +62,7 @@ class GroupHandlerTest extends TestCase
*/
public function testIsHandling()
{
- $testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING));
+ $testHandlers = [new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)];
$handler = new GroupHandler($testHandlers);
$this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR)));
$this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING)));
@@ -75,7 +75,7 @@ class GroupHandlerTest extends TestCase
public function testHandleUsesProcessors()
{
$test = new TestHandler();
- $handler = new GroupHandler(array($test));
+ $handler = new GroupHandler([$test]);
$handler->pushProcessor(function ($record) {
$record['extra']['foo'] = true;
@@ -92,14 +92,14 @@ class GroupHandlerTest extends TestCase
*/
public function testHandleBatchUsesProcessors()
{
- $testHandlers = array(new TestHandler(), new TestHandler());
+ $testHandlers = [new TestHandler(), new TestHandler()];
$handler = new GroupHandler($testHandlers);
$handler->pushProcessor(function ($record) {
$record['extra']['foo'] = true;
return $record;
});
- $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)));
+ $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
diff --git a/tests/Monolog/Handler/HandlerWrapperTest.php b/tests/Monolog/Handler/HandlerWrapperTest.php
index d8d0452..bedc175 100644
--- a/tests/Monolog/Handler/HandlerWrapperTest.php
+++ b/tests/Monolog/Handler/HandlerWrapperTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
/**
* @author Alexey Karapetov <alexey@karapetov.com>
@@ -28,7 +28,7 @@ class HandlerWrapperTest extends TestCase
public function setUp()
{
parent::setUp();
- $this->handler = $this->getMock('Monolog\\Handler\\HandlerInterface');
+ $this->handler = $this->createMock('Monolog\\Handler\\HandlerInterface');
$this->wrapper = new HandlerWrapper($this->handler);
}
@@ -37,10 +37,10 @@ class HandlerWrapperTest extends TestCase
*/
public function trueFalseDataProvider()
{
- return array(
- array(true),
- array(false),
- );
+ return [
+ [true],
+ [false],
+ ];
}
/**
@@ -87,44 +87,4 @@ class HandlerWrapperTest extends TestCase
$this->assertEquals($result, $this->wrapper->handleBatch($records));
}
-
- public function testPushProcessor()
- {
- $processor = function () {};
- $this->handler->expects($this->once())
- ->method('pushProcessor')
- ->with($processor);
-
- $this->assertEquals($this->wrapper, $this->wrapper->pushProcessor($processor));
- }
-
- public function testPopProcessor()
- {
- $processor = function () {};
- $this->handler->expects($this->once())
- ->method('popProcessor')
- ->willReturn($processor);
-
- $this->assertEquals($processor, $this->wrapper->popProcessor());
- }
-
- public function testSetFormatter()
- {
- $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
- $this->handler->expects($this->once())
- ->method('setFormatter')
- ->with($formatter);
-
- $this->assertEquals($this->wrapper, $this->wrapper->setFormatter($formatter));
- }
-
- public function testGetFormatter()
- {
- $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
- $this->handler->expects($this->once())
- ->method('getFormatter')
- ->willReturn($formatter);
-
- $this->assertEquals($formatter, $this->wrapper->getFormatter());
- }
}
diff --git a/tests/Monolog/Handler/HipChatHandlerTest.php b/tests/Monolog/Handler/HipChatHandlerTest.php
index 52dc9da..4df4de4 100644
--- a/tests/Monolog/Handler/HipChatHandlerTest.php
+++ b/tests/Monolog/Handler/HipChatHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -24,30 +24,6 @@ class HipChatHandlerTest extends TestCase
/** @var HipChatHandler */
private $handler;
- public function testWriteHeader()
- {
- $this->createHandler();
- $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
- fseek($this->res, 0);
- $content = fread($this->res, 1024);
-
- $this->assertRegexp('/POST \/v1\/rooms\/message\?format=json&auth_token=.* HTTP\/1.1\\r\\nHost: api.hipchat.com\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
-
- return $content;
- }
-
- public function testWriteCustomHostHeader()
- {
- $this->createHandler('myToken', 'room1', 'Monolog', true, 'hipchat.foo.bar');
- $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
- fseek($this->res, 0);
- $content = fread($this->res, 1024);
-
- $this->assertRegexp('/POST \/v1\/rooms\/message\?format=json&auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
-
- return $content;
- }
-
public function testWriteV2()
{
$this->createHandler('myToken', 'room1', 'Monolog', false, 'hipchat.foo.bar', 'v2');
@@ -55,7 +31,7 @@ class HipChatHandlerTest extends TestCase
fseek($this->res, 0);
$content = fread($this->res, 1024);
- $this->assertRegexp('/POST \/v2\/room\/room1\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
+ $this->assertRegexp('{POST /v2/room/room1/notification\?auth_token=.* HTTP/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content);
return $content;
}
@@ -67,7 +43,7 @@ class HipChatHandlerTest extends TestCase
fseek($this->res, 0);
$content = fread($this->res, 1024);
- $this->assertRegexp('/POST \/v2\/room\/room1\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
+ $this->assertRegexp('{POST /v2/room/room1/notification\?auth_token=.* HTTP/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content);
return $content;
}
@@ -79,7 +55,7 @@ class HipChatHandlerTest extends TestCase
fseek($this->res, 0);
$content = fread($this->res, 1024);
- $this->assertRegexp('/POST \/v2\/room\/room%20name\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
+ $this->assertRegexp('{POST /v2/room/room%20name/notification\?auth_token=.* HTTP/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content);
return $content;
}
@@ -92,18 +68,6 @@ class HipChatHandlerTest extends TestCase
$this->assertRegexp('/notify=0&message=test1&message_format=text&color=red&room_id=room1&from=Monolog$/', $content);
}
- public function testWriteContentV1WithoutName()
- {
- $this->createHandler('myToken', 'room1', null, false, 'hipchat.foo.bar', 'v1');
- $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1'));
- fseek($this->res, 0);
- $content = fread($this->res, 1024);
-
- $this->assertRegexp('/notify=0&message=test1&message_format=text&color=red&room_id=room1&from=$/', $content);
-
- return $content;
- }
-
/**
* @depends testWriteCustomHostHeader
*/
@@ -175,16 +139,16 @@ class HipChatHandlerTest extends TestCase
public function provideLevelColors()
{
- return array(
- array(Logger::DEBUG, 'gray'),
- array(Logger::INFO, 'green'),
- array(Logger::WARNING, 'yellow'),
- array(Logger::ERROR, 'red'),
- array(Logger::CRITICAL, 'red'),
- array(Logger::ALERT, 'red'),
- array(Logger::EMERGENCY,'red'),
- array(Logger::NOTICE, 'green'),
- );
+ return [
+ [Logger::DEBUG, 'gray'],
+ [Logger::INFO, 'green'],
+ [Logger::WARNING, 'yellow'],
+ [Logger::ERROR, 'red'],
+ [Logger::CRITICAL, 'red'],
+ [Logger::ALERT, 'red'],
+ [Logger::EMERGENCY,'red'],
+ [Logger::NOTICE, 'green'],
+ ];
}
/**
@@ -204,49 +168,48 @@ class HipChatHandlerTest extends TestCase
public function provideBatchRecords()
{
- return array(
- array(
- array(
- array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTime()),
- array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()),
- array('level' => Logger::CRITICAL, 'message' => 'Everything is broken!', 'level_name' => 'critical', 'datetime' => new \DateTime()),
- ),
+ return [
+ [
+ [
+ ['level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTimeImmutable()],
+ ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()],
+ ['level' => Logger::CRITICAL, 'message' => 'Everything is broken!', 'level_name' => 'critical', 'datetime' => new \DateTimeImmutable()],
+ ],
'red',
- ),
- array(
- array(
- array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTime()),
- array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()),
- ),
+ ],
+ [
+ [
+ ['level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTimeImmutable()],
+ ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()],
+ ],
'yellow',
- ),
- array(
- array(
- array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTime()),
- array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()),
- ),
+ ],
+ [
+ [
+ ['level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTimeImmutable()],
+ ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()],
+ ],
'green',
- ),
- array(
- array(
- array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTime()),
- ),
+ ],
+ [
+ [
+ ['level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTimeImmutable()],
+ ],
'gray',
- ),
- );
+ ],
+ ];
}
private function createHandler($token = 'myToken', $room = 'room1', $name = 'Monolog', $notify = false, $host = 'api.hipchat.com', $version = 'v1')
{
- $constructorArgs = array($token, $room, $name, $notify, Logger::DEBUG, true, true, 'text', $host, $version);
+ $constructorArgs = [$token, $room, $name, $notify, Logger::DEBUG, true, true, 'text', $host, $version];
$this->res = fopen('php://memory', 'a');
- $this->handler = $this->getMock(
- '\Monolog\Handler\HipChatHandler',
- array('fsockopen', 'streamSetTimeout', 'closeSocket'),
- $constructorArgs
- );
+ $this->handler = $this->getMockBuilder('Monolog\Handler\HipChatHandler')
+ ->setConstructorArgs($constructorArgs)
+ ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
+ ->getMock();
- $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
+ $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this->handler, 'localhost:1234');
@@ -263,14 +226,6 @@ class HipChatHandlerTest extends TestCase
$this->handler->setFormatter($this->getIdentityFormatter());
}
- /**
- * @expectedException InvalidArgumentException
- */
- public function testCreateWithTooLongName()
- {
- $hipChatHandler = new HipChatHandler('token', 'room', 'SixteenCharsHere');
- }
-
public function testCreateWithTooLongNameV2()
{
// creating a handler with too long of a name but using the v2 api doesn't matter.
diff --git a/tests/Monolog/Handler/LogEntriesHandlerTest.php b/tests/Monolog/Handler/LogEntriesHandlerTest.php
index b2deb40..92a206d 100644
--- a/tests/Monolog/Handler/LogEntriesHandlerTest.php
+++ b/tests/Monolog/Handler/LogEntriesHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -37,37 +37,36 @@ class LogEntriesHandlerTest extends TestCase
fseek($this->res, 0);
$content = fread($this->res, 1024);
- $this->assertRegexp('/testToken \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] test.CRITICAL: Critical write test/', $content);
+ $this->assertRegexp('/testToken \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}\+00:00\] test.CRITICAL: Critical write test/', $content);
}
public function testWriteBatchContent()
{
- $records = array(
+ $records = [
$this->getRecord(),
$this->getRecord(),
$this->getRecord(),
- );
+ ];
$this->createHandler();
$this->handler->handleBatch($records);
fseek($this->res, 0);
$content = fread($this->res, 1024);
- $this->assertRegexp('/(testToken \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] .* \[\] \[\]\n){3}/', $content);
+ $this->assertRegexp('/(testToken \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}\+00:00\] .* \[\] \[\]\n){3}/', $content);
}
private function createHandler()
{
$useSSL = extension_loaded('openssl');
- $args = array('testToken', $useSSL, Logger::DEBUG, true);
+ $args = ['testToken', $useSSL, Logger::DEBUG, true];
$this->res = fopen('php://memory', 'a');
- $this->handler = $this->getMock(
- '\Monolog\Handler\LogEntriesHandler',
- array('fsockopen', 'streamSetTimeout', 'closeSocket'),
- $args
- );
+ $this->handler = $this->getMockBuilder('Monolog\Handler\LogEntriesHandler')
+ ->setConstructorArgs($args)
+ ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
+ ->getMock();
- $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
+ $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this->handler, 'localhost:1234');
diff --git a/tests/Monolog/Handler/LogmaticHandlerTest.php b/tests/Monolog/Handler/LogmaticHandlerTest.php
new file mode 100644
index 0000000..bab74ac
--- /dev/null
+++ b/tests/Monolog/Handler/LogmaticHandlerTest.php
@@ -0,0 +1,83 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Monolog\Test\TestCase;
+use Monolog\Logger;
+
+/**
+ * @author Julien Breux <julien.breux@gmail.com>
+ */
+class LogmaticHandlerTest extends TestCase
+{
+ /**
+ * @var resource
+ */
+ private $res;
+
+ /**
+ * @var LogmaticHandler
+ */
+ private $handler;
+
+ public function testWriteContent()
+ {
+ $this->createHandler();
+ $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Critical write test'));
+
+ fseek($this->res, 0);
+ $content = fread($this->res, 1024);
+
+ $this->assertRegexp('/testToken {"message":"Critical write test","context":\[\],"level":500,"level_name":"CRITICAL","channel":"test","datetime":"(.*)","extra":\[\],"hostname":"testHostname","appname":"testAppname","@marker":\["sourcecode","php"\]}/', $content);
+ }
+
+ public function testWriteBatchContent()
+ {
+ $records = [
+ $this->getRecord(),
+ $this->getRecord(),
+ $this->getRecord(),
+ ];
+ $this->createHandler();
+ $this->handler->handleBatch($records);
+
+ fseek($this->res, 0);
+ $content = fread($this->res, 1024);
+
+ $this->assertRegexp('/testToken {"message":"test","context":\[\],"level":300,"level_name":"WARNING","channel":"test","datetime":"(.*)","extra":\[\],"hostname":"testHostname","appname":"testAppname","@marker":\["sourcecode","php"\]}/', $content);
+ }
+
+ private function createHandler()
+ {
+ $useSSL = extension_loaded('openssl');
+ $args = ['testToken', 'testHostname', 'testAppname', $useSSL, Logger::DEBUG, true];
+ $this->res = fopen('php://memory', 'a');
+ $this->handler = $this->getMockBuilder('Monolog\Handler\LogmaticHandler')
+ ->setConstructorArgs($args)
+ ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
+ ->getMock();
+
+ $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
+ $reflectionProperty->setAccessible(true);
+ $reflectionProperty->setValue($this->handler, 'localhost:1234');
+
+ $this->handler->expects($this->any())
+ ->method('fsockopen')
+ ->will($this->returnValue($this->res));
+ $this->handler->expects($this->any())
+ ->method('streamSetTimeout')
+ ->will($this->returnValue(true));
+ $this->handler->expects($this->any())
+ ->method('closeSocket')
+ ->will($this->returnValue(true));
+ }
+}
diff --git a/tests/Monolog/Handler/MailHandlerTest.php b/tests/Monolog/Handler/MailHandlerTest.php
index 6754f3d..5a52819 100644
--- a/tests/Monolog/Handler/MailHandlerTest.php
+++ b/tests/Monolog/Handler/MailHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class MailHandlerTest extends TestCase
{
@@ -21,11 +21,11 @@ class MailHandlerTest extends TestCase
*/
public function testHandleBatch()
{
- $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
+ $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$formatter->expects($this->once())
->method('formatBatch'); // Each record is formatted
- $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler');
+ $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler', [], '', true, true, true, ['send', 'write']);
$handler->expects($this->once())
->method('send');
$handler->expects($this->never())
@@ -41,11 +41,11 @@ class MailHandlerTest extends TestCase
*/
public function testHandleBatchNotSendsMailIfMessagesAreBelowLevel()
{
- $records = array(
+ $records = [
$this->getRecord(Logger::DEBUG, 'debug message 1'),
$this->getRecord(Logger::DEBUG, 'debug message 2'),
$this->getRecord(Logger::INFO, 'information'),
- );
+ ];
$handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler');
$handler->expects($this->never())
@@ -61,10 +61,11 @@ class MailHandlerTest extends TestCase
public function testHandle()
{
$handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler');
+ $handler->setFormatter(new \Monolog\Formatter\LineFormatter);
$record = $this->getRecord();
- $records = array($record);
- $records[0]['formatted'] = '['.$record['datetime']->format('Y-m-d H:i:s').'] test.WARNING: test [] []'."\n";
+ $records = [$record];
+ $records[0]['formatted'] = '['.$record['datetime'].'] test.WARNING: test [] []'."\n";
$handler->expects($this->once())
->method('send')
diff --git a/tests/Monolog/Handler/MockRavenClient-gte-0-16-0.php b/tests/Monolog/Handler/MockRavenClient-gte-0-16-0.php
new file mode 100644
index 0000000..07434e4
--- /dev/null
+++ b/tests/Monolog/Handler/MockRavenClient-gte-0-16-0.php
@@ -0,0 +1,27 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Raven_Client;
+
+class MockRavenClient extends Raven_Client
+{
+ public function capture($data, $stack = null, $vars = null)
+ {
+ $data = array_merge($this->get_user_data(), $data);
+ $this->lastData = $data;
+ $this->lastStack = $stack;
+ }
+
+ public $lastData;
+ public $lastStack;
+}
diff --git a/tests/Monolog/Handler/MockRavenClient.php b/tests/Monolog/Handler/MockRavenClient.php
index a083322..d344d34 100644
--- a/tests/Monolog/Handler/MockRavenClient.php
+++ b/tests/Monolog/Handler/MockRavenClient.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
diff --git a/tests/Monolog/Handler/MongoDBHandlerTest.php b/tests/Monolog/Handler/MongoDBHandlerTest.php
index 0fdef63..7333ef6 100644
--- a/tests/Monolog/Handler/MongoDBHandlerTest.php
+++ b/tests/Monolog/Handler/MongoDBHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,8 +11,9 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
-use Monolog\Logger;
+use MongoDB\Driver\Manager;
+use Monolog\Test\TestCase;
+use Monolog\Formatter\NormalizerFormatter;
class MongoDBHandlerTest extends TestCase
{
@@ -21,45 +22,57 @@ class MongoDBHandlerTest extends TestCase
*/
public function testConstructorShouldThrowExceptionForInvalidMongo()
{
- new MongoDBHandler(new \stdClass(), 'DB', 'Collection');
+ new MongoDBHandler(new \stdClass, 'db', 'collection');
}
- public function testHandle()
+ public function testHandleWithLibraryClient()
{
- $mongo = $this->getMock('Mongo', array('selectCollection'), array(), '', false);
- $collection = $this->getMock('stdClass', array('save'));
+ if (!(class_exists('MongoDB\Client'))) {
+ $this->markTestSkipped('mongodb/mongodb not installed');
+ }
+
+ $mongodb = $this->getMockBuilder('MongoDB\Client')
+ ->disableOriginalConstructor()
+ ->getMock();
- $mongo->expects($this->once())
+ $collection = $this->getMockBuilder('MongoDB\Collection')
+ ->disableOriginalConstructor()
+ ->getMock();
+
+ $mongodb->expects($this->once())
->method('selectCollection')
- ->with('DB', 'Collection')
+ ->with('db', 'collection')
->will($this->returnValue($collection));
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
-
- $expected = array(
- 'message' => 'test',
- 'context' => array('data' => '[object] (stdClass: {})', 'foo' => 34),
- 'level' => Logger::WARNING,
- 'level_name' => 'WARNING',
- 'channel' => 'test',
- 'datetime' => $record['datetime']->format('Y-m-d H:i:s'),
- 'extra' => array(),
- );
+ $record = $this->getRecord();
+ $expected = $record;
+ $expected['datetime'] = $record['datetime']->format(NormalizerFormatter::SIMPLE_DATE);
$collection->expects($this->once())
- ->method('save')
+ ->method('insertOne')
->with($expected);
- $handler = new MongoDBHandler($mongo, 'DB', 'Collection');
+ $handler = new MongoDBHandler($mongodb, 'db', 'collection');
$handler->handle($record);
}
-}
-if (!class_exists('Mongo')) {
- class Mongo
+ public function testHandleWithDriverManager()
{
- public function selectCollection()
- {
+ if (!(class_exists('MongoDB\Driver\Manager'))) {
+ $this->markTestSkipped('ext-mongodb not installed');
+ }
+
+ /* This can become a unit test once ManagerInterface can be mocked.
+ * See: https://jira.mongodb.org/browse/PHPC-378
+ */
+ $mongodb = new Manager('mongodb://localhost:27017');
+ $handler = new MongoDBHandler($mongodb, 'test', 'monolog');
+ $record = $this->getRecord();
+
+ try {
+ $handler->handle($record);
+ } catch (\RuntimeException $e) {
+ $this->markTestSkipped('Could not connect to MongoDB server on mongodb://localhost:27017');
}
}
}
diff --git a/tests/Monolog/Handler/NativeMailerHandlerTest.php b/tests/Monolog/Handler/NativeMailerHandlerTest.php
index ddf545d..d4aef95 100644
--- a/tests/Monolog/Handler/NativeMailerHandlerTest.php
+++ b/tests/Monolog/Handler/NativeMailerHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use InvalidArgumentException;
@@ -24,7 +24,7 @@ class NativeMailerHandlerTest extends TestCase
{
protected function setUp()
{
- $GLOBALS['mail'] = array();
+ $GLOBALS['mail'] = [];
}
/**
@@ -50,7 +50,7 @@ class NativeMailerHandlerTest extends TestCase
public function testSetterArrayHeaderInjection()
{
$mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org');
- $mailer->addHeader(array("Content-Type: text/html\r\nFrom: faked@attacker.org"));
+ $mailer->addHeader(["Content-Type: text/html\r\nFrom: faked@attacker.org"]);
}
/**
@@ -78,7 +78,8 @@ class NativeMailerHandlerTest extends TestCase
$from = 'receiver@example.org';
$mailer = new NativeMailerHandler($to, $subject, $from);
- $mailer->handleBatch(array());
+ $mailer->setFormatter(new \Monolog\Formatter\LineFormatter);
+ $mailer->handleBatch([]);
// batch is empty, nothing sent
$this->assertEmpty($GLOBALS['mail']);
diff --git a/tests/Monolog/Handler/NewRelicHandlerTest.php b/tests/Monolog/Handler/NewRelicHandlerTest.php
index 4d3a615..a71bbf8 100644
--- a/tests/Monolog/Handler/NewRelicHandlerTest.php
+++ b/tests/Monolog/Handler/NewRelicHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
class NewRelicHandlerTest extends TestCase
@@ -24,7 +24,7 @@ class NewRelicHandlerTest extends TestCase
public function setUp()
{
self::$appname = null;
- self::$customParameters = array();
+ self::$customParameters = [];
self::$transactionName = null;
}
@@ -46,8 +46,8 @@ class NewRelicHandlerTest extends TestCase
public function testThehandlerCanAddContextParamsToTheNewRelicTrace()
{
$handler = new StubNewRelicHandler();
- $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('a' => 'b')));
- $this->assertEquals(array('context_a' => 'b'), self::$customParameters);
+ $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['a' => 'b']));
+ $this->assertEquals(['context_a' => 'b'], self::$customParameters);
}
public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace()
@@ -56,10 +56,10 @@ class NewRelicHandlerTest extends TestCase
$handler->handle($this->getRecord(
Logger::ERROR,
'log message',
- array('a' => array('key1' => 'value1', 'key2' => 'value2'))
+ ['a' => ['key1' => 'value1', 'key2' => 'value2']]
));
$this->assertEquals(
- array('context_a_key1' => 'value1', 'context_a_key2' => 'value2'),
+ ['context_a_key1' => 'value1', 'context_a_key2' => 'value2'],
self::$customParameters
);
}
@@ -67,40 +67,40 @@ class NewRelicHandlerTest extends TestCase
public function testThehandlerCanAddExtraParamsToTheNewRelicTrace()
{
$record = $this->getRecord(Logger::ERROR, 'log message');
- $record['extra'] = array('c' => 'd');
+ $record['extra'] = ['c' => 'd'];
$handler = new StubNewRelicHandler();
$handler->handle($record);
- $this->assertEquals(array('extra_c' => 'd'), self::$customParameters);
+ $this->assertEquals(['extra_c' => 'd'], self::$customParameters);
}
public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace()
{
$record = $this->getRecord(Logger::ERROR, 'log message');
- $record['extra'] = array('c' => array('key1' => 'value1', 'key2' => 'value2'));
+ $record['extra'] = ['c' => ['key1' => 'value1', 'key2' => 'value2']];
$handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true);
$handler->handle($record);
$this->assertEquals(
- array('extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'),
+ ['extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'],
self::$customParameters
);
}
public function testThehandlerCanAddExtraContextAndParamsToTheNewRelicTrace()
{
- $record = $this->getRecord(Logger::ERROR, 'log message', array('a' => 'b'));
- $record['extra'] = array('c' => 'd');
+ $record = $this->getRecord(Logger::ERROR, 'log message', ['a' => 'b']);
+ $record['extra'] = ['c' => 'd'];
$handler = new StubNewRelicHandler();
$handler->handle($record);
- $expected = array(
+ $expected = [
'context_a' => 'b',
'extra_c' => 'd',
- );
+ ];
$this->assertEquals($expected, self::$customParameters);
}
@@ -131,7 +131,7 @@ class NewRelicHandlerTest extends TestCase
public function testTheAppNameCanBeOverriddenFromEachLog()
{
$handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName');
- $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('appname' => 'logAppName')));
+ $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['appname' => 'logAppName']));
$this->assertEquals('logAppName', self::$appname);
}
@@ -155,7 +155,7 @@ class NewRelicHandlerTest extends TestCase
public function testTheTransactionNameCanBeOverriddenFromEachLog()
{
$handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction');
- $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('transaction_name' => 'logTransactName')));
+ $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['transaction_name' => 'logTransactName']));
$this->assertEquals('logTransactName', self::$transactionName);
}
diff --git a/tests/Monolog/Handler/NoopHandlerTest.php b/tests/Monolog/Handler/NoopHandlerTest.php
new file mode 100644
index 0000000..768f5e3
--- /dev/null
+++ b/tests/Monolog/Handler/NoopHandlerTest.php
@@ -0,0 +1,49 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Monolog\Test\TestCase;
+use Monolog\Logger;
+
+/**
+ * @covers Monolog\Handler\NoopHandler::handle
+ */
+class NoopHandlerTest extends TestCase
+{
+ /**
+ * @dataProvider logLevelsProvider
+ */
+ public function testIsHandling($level)
+ {
+ $handler = new NoopHandler();
+ $this->assertTrue($handler->isHandling($this->getRecord($level)));
+ }
+
+ /**
+ * @dataProvider logLevelsProvider
+ */
+ public function testHandle($level)
+ {
+ $handler = new NoopHandler();
+ $this->assertFalse($handler->handle($this->getRecord($level)));
+ }
+
+ public function logLevelsProvider()
+ {
+ return array_map(
+ function ($level) {
+ return [$level];
+ },
+ array_values(Logger::getLevels())
+ );
+ }
+}
diff --git a/tests/Monolog/Handler/NullHandlerTest.php b/tests/Monolog/Handler/NullHandlerTest.php
index 292df78..b7e482b 100644
--- a/tests/Monolog/Handler/NullHandlerTest.php
+++ b/tests/Monolog/Handler/NullHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
diff --git a/tests/Monolog/Handler/PHPConsoleHandlerTest.php b/tests/Monolog/Handler/PHPConsoleHandlerTest.php
index 152573e..0836b99 100644
--- a/tests/Monolog/Handler/PHPConsoleHandlerTest.php
+++ b/tests/Monolog/Handler/PHPConsoleHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -14,11 +14,11 @@ namespace Monolog\Handler;
use Exception;
use Monolog\ErrorHandler;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use PhpConsole\Connector;
use PhpConsole\Dispatcher\Debug as DebugDispatcher;
use PhpConsole\Dispatcher\Errors as ErrorDispatcher;
-use PhpConsole\Handler;
+use PhpConsole\Handler as VendorPhpConsoleHandler;
use PHPUnit_Framework_MockObject_MockObject;
/**
@@ -52,8 +52,8 @@ class PHPConsoleHandlerTest extends TestCase
{
return $this->getMockBuilder('PhpConsole\Dispatcher\Debug')
->disableOriginalConstructor()
- ->setMethods(array('dispatchDebug'))
- ->setConstructorArgs(array($connector, $connector->getDumper()))
+ ->setMethods(['dispatchDebug'])
+ ->setConstructorArgs([$connector, $connector->getDumper()])
->getMock();
}
@@ -61,8 +61,8 @@ class PHPConsoleHandlerTest extends TestCase
{
return $this->getMockBuilder('PhpConsole\Dispatcher\Errors')
->disableOriginalConstructor()
- ->setMethods(array('dispatchError', 'dispatchException'))
- ->setConstructorArgs(array($connector, $connector->getDumper()))
+ ->setMethods(['dispatchError', 'dispatchException'])
+ ->setConstructorArgs([$connector, $connector->getDumper()])
->getMock();
}
@@ -70,7 +70,7 @@ class PHPConsoleHandlerTest extends TestCase
{
$connector = $this->getMockBuilder('PhpConsole\Connector')
->disableOriginalConstructor()
- ->setMethods(array(
+ ->setMethods([
'sendMessage',
'onShutDown',
'isActiveClient',
@@ -81,7 +81,7 @@ class PHPConsoleHandlerTest extends TestCase
'setAllowedIpMasks',
'setHeadersLimit',
'startEvalRequestsListener',
- ))
+ ])
->getMock();
$connector->expects($this->any())
@@ -93,17 +93,17 @@ class PHPConsoleHandlerTest extends TestCase
protected function getHandlerDefaultOption($name)
{
- $handler = new PHPConsoleHandler(array(), $this->connector);
+ $handler = new PHPConsoleHandler([], $this->connector);
$options = $handler->getOptions();
return $options[$name];
}
- protected function initLogger($handlerOptions = array(), $level = Logger::DEBUG)
+ protected function initLogger($handlerOptions = [], $level = Logger::DEBUG)
{
- return new Logger('test', array(
+ return new Logger('test', [
new PHPConsoleHandler($handlerOptions, $this->connector, $level),
- ));
+ ]);
}
public function testInitWithDefaultConnector()
@@ -114,33 +114,33 @@ class PHPConsoleHandlerTest extends TestCase
public function testInitWithCustomConnector()
{
- $handler = new PHPConsoleHandler(array(), $this->connector);
+ $handler = new PHPConsoleHandler([], $this->connector);
$this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector()));
}
public function testDebug()
{
$this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with($this->equalTo('test'));
- $this->initLogger()->addDebug('test');
+ $this->initLogger()->debug('test');
}
public function testDebugContextInMessage()
{
$message = 'test';
$tag = 'tag';
- $context = array($tag, 'custom' => mt_rand());
+ $context = [$tag, 'custom' => mt_rand()];
$expectedMessage = $message . ' ' . json_encode(array_slice($context, 1));
$this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with(
$this->equalTo($expectedMessage),
$this->equalTo($tag)
);
- $this->initLogger()->addDebug($message, $context);
+ $this->initLogger()->debug($message, $context);
}
public function testDebugTags($tagsContextKeys = null)
{
$expectedTags = mt_rand();
- $logger = $this->initLogger($tagsContextKeys ? array('debugTagsKeysInContext' => $tagsContextKeys) : array());
+ $logger = $this->initLogger($tagsContextKeys ? ['debugTagsKeysInContext' => $tagsContextKeys] : []);
if (!$tagsContextKeys) {
$tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext');
}
@@ -151,7 +151,7 @@ class PHPConsoleHandlerTest extends TestCase
$this->equalTo($expectedTags)
);
$this->connector->setDebugDispatcher($debugDispatcher);
- $logger->addDebug('test', array($key => $expectedTags));
+ $logger->debug('test', [$key => $expectedTags]);
}
}
@@ -168,8 +168,8 @@ class PHPConsoleHandlerTest extends TestCase
$this->equalTo($line),
$classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore'))
);
- $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? array('classesPartialsTraceIgnore' => $classesPartialsTraceIgnore) : array()), false);
- $errorHandler->registerErrorHandler(array(), false, E_USER_WARNING);
+ $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false);
+ $errorHandler->registerErrorHandler([], false, E_USER_WARNING);
$errorHandler->handleError($code, $message, $file, $line);
}
@@ -183,7 +183,7 @@ class PHPConsoleHandlerTest extends TestCase
$handler->log(
\Psr\Log\LogLevel::ERROR,
sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()),
- array('exception' => $e)
+ ['exception' => $e]
);
}
@@ -192,45 +192,45 @@ class PHPConsoleHandlerTest extends TestCase
*/
public function testWrongOptionsThrowsException()
{
- new PHPConsoleHandler(array('xxx' => 1));
+ new PHPConsoleHandler(['xxx' => 1]);
}
public function testOptionEnabled()
{
$this->debugDispatcher->expects($this->never())->method('dispatchDebug');
- $this->initLogger(array('enabled' => false))->addDebug('test');
+ $this->initLogger(['enabled' => false])->debug('test');
}
public function testOptionClassesPartialsTraceIgnore()
{
- $this->testError(array('Class', 'Namespace\\'));
+ $this->testError(['Class', 'Namespace\\']);
}
public function testOptionDebugTagsKeysInContext()
{
- $this->testDebugTags(array('key1', 'key2'));
+ $this->testDebugTags(['key1', 'key2']);
}
public function testOptionUseOwnErrorsAndExceptionsHandler()
{
- $this->initLogger(array('useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true));
- $this->assertEquals(array(Handler::getInstance(), 'handleError'), set_error_handler(function () {
+ $this->initLogger(['useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true]);
+ $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleError'], set_error_handler(function () {
}));
- $this->assertEquals(array(Handler::getInstance(), 'handleException'), set_exception_handler(function () {
+ $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleException'], set_exception_handler(function () {
}));
}
public static function provideConnectorMethodsOptionsSets()
{
- return array(
- array('sourcesBasePath', 'setSourcesBasePath', __DIR__),
- array('serverEncoding', 'setServerEncoding', 'cp1251'),
- array('password', 'setPassword', '******'),
- array('enableSslOnlyMode', 'enableSslOnlyMode', true, false),
- array('ipMasks', 'setAllowedIpMasks', array('127.0.0.*')),
- array('headersLimit', 'setHeadersLimit', 2500),
- array('enableEvalListener', 'startEvalRequestsListener', true, false),
- );
+ return [
+ ['sourcesBasePath', 'setSourcesBasePath', __DIR__],
+ ['serverEncoding', 'setServerEncoding', 'cp1251'],
+ ['password', 'setPassword', '******'],
+ ['enableSslOnlyMode', 'enableSslOnlyMode', true, false],
+ ['ipMasks', 'setAllowedIpMasks', ['127.0.0.*']],
+ ['headersLimit', 'setHeadersLimit', 2500],
+ ['enableEvalListener', 'startEvalRequestsListener', true, false],
+ ];
}
/**
@@ -242,24 +242,24 @@ class PHPConsoleHandlerTest extends TestCase
if ($isArgument) {
$expectCall->with($value);
}
- new PHPConsoleHandler(array($option => $value), $this->connector);
+ new PHPConsoleHandler([$option => $value], $this->connector);
}
public function testOptionDetectDumpTraceAndSource()
{
- new PHPConsoleHandler(array('detectDumpTraceAndSource' => true), $this->connector);
+ new PHPConsoleHandler(['detectDumpTraceAndSource' => true], $this->connector);
$this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource);
}
public static function provideDumperOptionsValues()
{
- return array(
- array('dumperLevelLimit', 'levelLimit', 1001),
- array('dumperItemsCountLimit', 'itemsCountLimit', 1002),
- array('dumperItemSizeLimit', 'itemSizeLimit', 1003),
- array('dumperDumpSizeLimit', 'dumpSizeLimit', 1004),
- array('dumperDetectCallbacks', 'detectCallbacks', true),
- );
+ return [
+ ['dumperLevelLimit', 'levelLimit', 1001],
+ ['dumperItemsCountLimit', 'itemsCountLimit', 1002],
+ ['dumperItemSizeLimit', 'itemSizeLimit', 1003],
+ ['dumperDumpSizeLimit', 'dumpSizeLimit', 1004],
+ ['dumperDetectCallbacks', 'detectCallbacks', true],
+ ];
}
/**
@@ -267,7 +267,7 @@ class PHPConsoleHandlerTest extends TestCase
*/
public function testDumperOptions($option, $dumperProperty, $value)
{
- new PHPConsoleHandler(array($option => $value), $this->connector);
+ new PHPConsoleHandler([$option => $value], $this->connector);
$this->assertEquals($value, $this->connector->getDumper()->$dumperProperty);
}
}
diff --git a/tests/Monolog/Handler/ProcessHandlerTest.php b/tests/Monolog/Handler/ProcessHandlerTest.php
new file mode 100644
index 0000000..dc2a427
--- /dev/null
+++ b/tests/Monolog/Handler/ProcessHandlerTest.php
@@ -0,0 +1,195 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+namespace Monolog\Handler;
+
+use Monolog\Test\TestCase;
+use Monolog\Logger;
+
+class ProcessHandlerTest extends TestCase
+{
+ /**
+ * Dummy command to be used by tests that should not fail due to the command.
+ *
+ * @var string
+ */
+ const DUMMY_COMMAND = 'echo';
+
+ /**
+ * @covers Monolog\Handler\ProcessHandler::__construct
+ * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand
+ * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
+ * @covers Monolog\Handler\ProcessHandler::write
+ * @covers Monolog\Handler\ProcessHandler::ensureProcessIsStarted
+ * @covers Monolog\Handler\ProcessHandler::startProcess
+ * @covers Monolog\Handler\ProcessHandler::handleStartupErrors
+ */
+ public function testWriteOpensProcessAndWritesToStdInOfProcess()
+ {
+ $fixtures = [
+ 'chuck norris',
+ 'foobar1337',
+ ];
+
+ $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
+ $mockBuilder->setMethods(['writeProcessInput']);
+ // using echo as command, as it is most probably available
+ $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
+
+ $handler = $mockBuilder->getMock();
+
+ $handler->expects($this->exactly(2))
+ ->method('writeProcessInput')
+ ->withConsecutive($this->stringContains($fixtures[0]), $this->stringContains($fixtures[1]));
+
+ /** @var ProcessHandler $handler */
+ $handler->handle($this->getRecord(Logger::WARNING, $fixtures[0]));
+ $handler->handle($this->getRecord(Logger::ERROR, $fixtures[1]));
+ }
+
+ /**
+ * Data provider for invalid commands.
+ *
+ * @return array
+ */
+ public function invalidCommandProvider()
+ {
+ return [
+ [1337, 'TypeError'],
+ ['', 'InvalidArgumentException'],
+ [null, 'TypeError'],
+ [fopen('php://input', 'r'), 'TypeError'],
+ ];
+ }
+
+ /**
+ * @dataProvider invalidCommandProvider
+ * @param mixed $invalidCommand
+ * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand
+ */
+ public function testConstructWithInvalidCommandThrowsInvalidArgumentException($invalidCommand, $expectedExcep)
+ {
+ $this->setExpectedException($expectedExcep);
+ new ProcessHandler($invalidCommand, Logger::DEBUG);
+ }
+
+ /**
+ * Data provider for invalid CWDs.
+ *
+ * @return array
+ */
+ public function invalidCwdProvider()
+ {
+ return [
+ [1337, 'TypeError'],
+ ['', 'InvalidArgumentException'],
+ [fopen('php://input', 'r'), 'TypeError'],
+ ];
+ }
+
+ /**
+ * @dataProvider invalidCwdProvider
+ * @param mixed $invalidCwd
+ * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
+ */
+ public function testConstructWithInvalidCwdThrowsInvalidArgumentException($invalidCwd, $expectedExcep)
+ {
+ $this->setExpectedException($expectedExcep);
+ new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, $invalidCwd);
+ }
+
+ /**
+ * @covers Monolog\Handler\ProcessHandler::__construct
+ * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd
+ */
+ public function testConstructWithValidCwdWorks()
+ {
+ $handler = new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, sys_get_temp_dir());
+ $this->assertInstanceOf(
+ 'Monolog\Handler\ProcessHandler',
+ $handler,
+ 'Constructed handler is not a ProcessHandler.'
+ );
+ }
+
+ /**
+ * @covers Monolog\Handler\ProcessHandler::handleStartupErrors
+ */
+ public function testStartupWithFailingToSelectErrorStreamThrowsUnexpectedValueException()
+ {
+ $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
+ $mockBuilder->setMethods(['selectErrorStream']);
+ $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
+
+ $handler = $mockBuilder->getMock();
+
+ $handler->expects($this->once())
+ ->method('selectErrorStream')
+ ->will($this->returnValue(false));
+
+ $this->setExpectedException('\UnexpectedValueException');
+ /** @var ProcessHandler $handler */
+ $handler->handle($this->getRecord(Logger::WARNING, 'stream failing, whoops'));
+ }
+
+ /**
+ * @covers Monolog\Handler\ProcessHandler::handleStartupErrors
+ * @covers Monolog\Handler\ProcessHandler::selectErrorStream
+ */
+ public function testStartupWithErrorsThrowsUnexpectedValueException()
+ {
+ $handler = new ProcessHandler('>&2 echo "some fake error message"');
+ $this->setExpectedException('\UnexpectedValueException');
+ $handler->handle($this->getRecord(Logger::WARNING, 'some warning in the house'));
+ }
+
+ /**
+ * @covers Monolog\Handler\ProcessHandler::write
+ */
+ public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentException()
+ {
+ $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler');
+ $mockBuilder->setMethods(['readProcessErrors']);
+ // using echo as command, as it is most probably available
+ $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]);
+
+ $handler = $mockBuilder->getMock();
+
+ $handler->expects($this->exactly(2))
+ ->method('readProcessErrors')
+ ->willReturnOnConsecutiveCalls('', $this->returnValue('some fake error message here'));
+
+ $this->setExpectedException('\UnexpectedValueException');
+ /** @var ProcessHandler $handler */
+ $handler->handle($this->getRecord(Logger::WARNING, 'some test stuff'));
+ }
+
+ /**
+ * @covers Monolog\Handler\ProcessHandler::close
+ */
+ public function testCloseClosesProcess()
+ {
+ $class = new \ReflectionClass('Monolog\Handler\ProcessHandler');
+ $property = $class->getProperty('process');
+ $property->setAccessible(true);
+
+ $handler = new ProcessHandler(self::DUMMY_COMMAND);
+ $handler->handle($this->getRecord(Logger::WARNING, '21 is only the half truth'));
+
+ $process = $property->getValue($handler);
+ $this->assertTrue(is_resource($process), 'Process is not running although it should.');
+
+ $handler->close();
+
+ $process = $property->getValue($handler);
+ $this->assertFalse(is_resource($process), 'Process is still running although it should not.');
+ }
+}
diff --git a/tests/Monolog/Handler/PsrHandlerTest.php b/tests/Monolog/Handler/PsrHandlerTest.php
index 64eaab1..e371512 100644
--- a/tests/Monolog/Handler/PsrHandlerTest.php
+++ b/tests/Monolog/Handler/PsrHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -21,11 +21,11 @@ class PsrHandlerTest extends TestCase
{
public function logLevelProvider()
{
- $levels = array();
+ $levels = [];
$monologLogger = new Logger('');
foreach ($monologLogger->getLevels() as $levelName => $level) {
- $levels[] = array($levelName, $level);
+ $levels[] = [$levelName, $level];
}
return $levels;
@@ -37,14 +37,14 @@ class PsrHandlerTest extends TestCase
public function testHandlesAllLevels($levelName, $level)
{
$message = 'Hello, world! ' . $level;
- $context = array('foo' => 'bar', 'level' => $level);
+ $context = ['foo' => 'bar', 'level' => $level];
- $psrLogger = $this->getMock('Psr\Log\NullLogger');
+ $psrLogger = $this->createMock('Psr\Log\NullLogger');
$psrLogger->expects($this->once())
->method('log')
->with(strtolower($levelName), $message, $context);
$handler = new PsrHandler($psrLogger);
- $handler->handle(array('level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context));
+ $handler->handle(['level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context]);
}
}
diff --git a/tests/Monolog/Handler/PushoverHandlerTest.php b/tests/Monolog/Handler/PushoverHandlerTest.php
index 56df474..6a295c9 100644
--- a/tests/Monolog/Handler/PushoverHandlerTest.php
+++ b/tests/Monolog/Handler/PushoverHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -103,7 +103,7 @@ class PushoverHandlerTest extends TestCase
public function testWriteToMultipleUsers()
{
- $this->createHandler('myToken', array('userA', 'userB'));
+ $this->createHandler('myToken', ['userA', 'userB']);
$this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
@@ -114,15 +114,14 @@ class PushoverHandlerTest extends TestCase
private function createHandler($token = 'myToken', $user = 'myUser', $title = 'Monolog')
{
- $constructorArgs = array($token, $user, $title);
+ $constructorArgs = [$token, $user, $title];
$this->res = fopen('php://memory', 'a');
- $this->handler = $this->getMock(
- '\Monolog\Handler\PushoverHandler',
- array('fsockopen', 'streamSetTimeout', 'closeSocket'),
- $constructorArgs
- );
+ $this->handler = $this->getMockBuilder('Monolog\Handler\PushoverHandler')
+ ->setConstructorArgs($constructorArgs)
+ ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
+ ->getMock();
- $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
+ $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this->handler, 'localhost:1234');
diff --git a/tests/Monolog/Handler/RavenHandlerTest.php b/tests/Monolog/Handler/RavenHandlerTest.php
index 26d212b..082042f 100644
--- a/tests/Monolog/Handler/RavenHandlerTest.php
+++ b/tests/Monolog/Handler/RavenHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,19 +11,24 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
+use Raven_Client;
class RavenHandlerTest extends TestCase
{
public function setUp()
{
if (!class_exists('Raven_Client')) {
- $this->markTestSkipped('raven/raven not installed');
+ $this->markTestSkipped('sentry/sentry not installed');
}
- require_once __DIR__ . '/MockRavenClient.php';
+ if (version_compare(Raven_Client::VERSION, '0.16.0', '>=')) {
+ require_once __DIR__ . '/MockRavenClient-gte-0-16-0.php';
+ } else {
+ require_once __DIR__ . '/MockRavenClient.php';
+ }
}
/**
@@ -78,8 +83,8 @@ class RavenHandlerTest extends TestCase
$ravenClient = $this->getRavenClient();
$handler = $this->getHandler($ravenClient);
- $tags = array(1, 2, 'foo');
- $record = $this->getRecord(Logger::INFO, 'test', array('tags' => $tags));
+ $tags = [1, 2, 'foo'];
+ $record = $this->getRecord(Logger::INFO, 'test', ['tags' => $tags]);
$handler->handle($record);
$this->assertEquals($tags, $ravenClient->lastData['tags']);
@@ -93,7 +98,7 @@ class RavenHandlerTest extends TestCase
$checksum = '098f6bcd4621d373cade4e832627b4f6';
$release = '05a671c66aefea124cc08b76ea6d30bb';
$eventId = '31423';
- $record = $this->getRecord(Logger::INFO, 'test', array('checksum' => $checksum, 'release' => $release, 'event_id' => $eventId));
+ $record = $this->getRecord(Logger::INFO, 'test', ['checksum' => $checksum, 'release' => $release, 'event_id' => $eventId]);
$handler->handle($record);
$this->assertEquals($checksum, $ravenClient->lastData['checksum']);
@@ -106,8 +111,8 @@ class RavenHandlerTest extends TestCase
$ravenClient = $this->getRavenClient();
$handler = $this->getHandler($ravenClient);
- $fingerprint = array('{{ default }}', 'other value');
- $record = $this->getRecord(Logger::INFO, 'test', array('fingerprint' => $fingerprint));
+ $fingerprint = ['{{ default }}', 'other value'];
+ $record = $this->getRecord(Logger::INFO, 'test', ['fingerprint' => $fingerprint]);
$handler->handle($record);
$this->assertEquals($fingerprint, $ravenClient->lastData['fingerprint']);
@@ -121,14 +126,14 @@ class RavenHandlerTest extends TestCase
$recordWithNoContext = $this->getRecord(Logger::INFO, 'test with default user context');
// set user context 'externally'
- $user = array(
+ $user = [
'id' => '123',
'email' => 'test@test.com',
- );
+ ];
- $recordWithContext = $this->getRecord(Logger::INFO, 'test', array('user' => $user));
+ $recordWithContext = $this->getRecord(Logger::INFO, 'test', ['user' => $user]);
- $ravenClient->user_context(array('id' => 'test_user_id'));
+ $ravenClient->user_context(['id' => 'test_user_id']);
// handle context
$handler->handle($recordWithContext);
$this->assertEquals($user, $ravenClient->lastData['user']);
@@ -156,7 +161,7 @@ class RavenHandlerTest extends TestCase
try {
$this->methodThatThrowsAnException();
} catch (\Exception $e) {
- $record = $this->getRecord(Logger::ERROR, $e->getMessage(), array('exception' => $e));
+ $record = $this->getRecord(Logger::ERROR, $e->getMessage(), ['exception' => $e]);
$handler->handle($record);
}
@@ -169,10 +174,10 @@ class RavenHandlerTest extends TestCase
$records[] = $this->getRecord(Logger::WARNING, 'warning');
$records[] = $this->getRecord(Logger::WARNING, 'warning');
- $logFormatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
+ $logFormatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$logFormatter->expects($this->once())->method('formatBatch');
- $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
+ $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$formatter->expects($this->once())->method('format')->with($this->callback(function ($record) {
return $record['level'] == 400;
}));
@@ -185,13 +190,16 @@ class RavenHandlerTest extends TestCase
public function testHandleBatchDoNothingIfRecordsAreBelowLevel()
{
- $records = array(
+ $records = [
$this->getRecord(Logger::DEBUG, 'debug message 1'),
$this->getRecord(Logger::DEBUG, 'debug message 2'),
$this->getRecord(Logger::INFO, 'information'),
- );
+ ];
- $handler = $this->getMock('Monolog\Handler\RavenHandler', null, array($this->getRavenClient()));
+ $handler = $this->getMockBuilder('Monolog\Handler\RavenHandler')
+ ->setMethods(['handle'])
+ ->setConstructorArgs([$this->getRavenClient()])
+ ->getMock();
$handler->expects($this->never())->method('handle');
$handler->setLevel(Logger::ERROR);
$handler->handleBatch($records);
@@ -209,10 +217,10 @@ class RavenHandlerTest extends TestCase
$this->getRecord(Logger::INFO, 'information 2'),
);
- $logFormatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
+ $logFormatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$logFormatter->expects($this->once())->method('formatBatch');
- $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
+ $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$formatter->expects($this->once())->method('format')->with($this->callback(function ($record) use ($records) {
return $record['message'] == 'error 1';
}));
@@ -243,7 +251,7 @@ class RavenHandlerTest extends TestCase
$this->assertEquals($release, $ravenClient->lastData['release']);
$localRelease = 'v41.41.41';
- $record = $this->getRecord(Logger::INFO, 'test', array('release' => $localRelease));
+ $record = $this->getRecord(Logger::INFO, 'test', ['release' => $localRelease]);
$handler->handle($record);
$this->assertEquals($localRelease, $ravenClient->lastData['release']);
}
diff --git a/tests/Monolog/Handler/RedisHandlerTest.php b/tests/Monolog/Handler/RedisHandlerTest.php
index 689d527..a0260e1 100644
--- a/tests/Monolog/Handler/RedisHandlerTest.php
+++ b/tests/Monolog/Handler/RedisHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
@@ -27,26 +27,30 @@ class RedisHandlerTest extends TestCase
public function testConstructorShouldWorkWithPredis()
{
- $redis = $this->getMock('Predis\Client');
+ $redis = $this->createMock('Predis\Client');
$this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key'));
}
public function testConstructorShouldWorkWithRedis()
{
- $redis = $this->getMock('Redis');
+ if (!class_exists('Redis')) {
+ $this->markTestSkipped('The redis ext is required to run this test');
+ }
+
+ $redis = $this->createMock('Redis');
$this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key'));
}
public function testPredisHandle()
{
- $redis = $this->getMock('Predis\Client', array('rpush'));
+ $redis = $this->createPartialMock('Predis\Client', ['rpush']);
// Predis\Client uses rpush
$redis->expects($this->once())
->method('rpush')
->with('key', 'test');
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
+ $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key');
$handler->setFormatter(new LineFormatter("%message%"));
@@ -55,14 +59,18 @@ class RedisHandlerTest extends TestCase
public function testRedisHandle()
{
- $redis = $this->getMock('Redis', array('rpush'));
+ if (!class_exists('Redis')) {
+ $this->markTestSkipped('The redis ext is required to run this test');
+ }
+
+ $redis = $this->createPartialMock('Redis', ['rpush']);
// Redis uses rPush
$redis->expects($this->once())
- ->method('rPush')
+ ->method('rpush')
->with('key', 'test');
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
+ $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key');
$handler->setFormatter(new LineFormatter("%message%"));
@@ -71,7 +79,11 @@ class RedisHandlerTest extends TestCase
public function testRedisHandleCapped()
{
- $redis = $this->getMock('Redis', array('multi', 'rpush', 'ltrim', 'exec'));
+ if (!class_exists('Redis')) {
+ $this->markTestSkipped('The redis ext is required to run this test');
+ }
+
+ $redis = $this->createPartialMock('Redis', ['multi', 'rpush', 'ltrim', 'exec']);
// Redis uses multi
$redis->expects($this->once())
@@ -90,7 +102,7 @@ class RedisHandlerTest extends TestCase
->method('exec')
->will($this->returnSelf());
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
+ $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10);
$handler->setFormatter(new LineFormatter("%message%"));
@@ -99,9 +111,9 @@ class RedisHandlerTest extends TestCase
public function testPredisHandleCapped()
{
- $redis = $this->getMock('Predis\Client', array('transaction'));
+ $redis = $this->createPartialMock('Predis\Client', ['transaction']);
- $redisTransaction = $this->getMock('Predis\Client', array('rpush', 'ltrim'));
+ $redisTransaction = $this->createPartialMock('Predis\Client', ['rpush', 'ltrim']);
$redisTransaction->expects($this->once())
->method('rpush')
@@ -118,7 +130,7 @@ class RedisHandlerTest extends TestCase
$cb($redisTransaction);
}));
- $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34));
+ $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10);
$handler->setFormatter(new LineFormatter("%message%"));
diff --git a/tests/Monolog/Handler/RollbarHandlerTest.php b/tests/Monolog/Handler/RollbarHandlerTest.php
index f302e91..89fc9cb 100644
--- a/tests/Monolog/Handler/RollbarHandlerTest.php
+++ b/tests/Monolog/Handler/RollbarHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use Exception;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use PHPUnit_Framework_MockObject_MockObject as MockObject;
@@ -32,7 +32,7 @@ class RollbarHandlerTest extends TestCase
/**
* @var array
*/
- public $reportedExceptionArguments = null;
+ private $reportedExceptionArguments = null;
protected function setUp()
{
@@ -60,25 +60,23 @@ class RollbarHandlerTest extends TestCase
->setMethods(array('report_message', 'report_exception', 'flush'))
->getMock();
- $that = $this;
-
$this->rollbarNotifier
->expects($this->any())
->method('report_exception')
- ->willReturnCallback(function ($exception, $context, $payload) use ($that) {
- $that->reportedExceptionArguments = compact('exception', 'context', 'payload');
+ ->willReturnCallback(function ($exception, $context, $payload) {
+ $this->reportedExceptionArguments = compact('exception', 'context', 'payload');
});
}
- private function createHandler()
+ private function createHandler(): RollbarHandler
{
return new RollbarHandler($this->rollbarNotifier, Logger::DEBUG);
}
- private function createExceptionRecord($level = Logger::DEBUG, $message = 'test', $exception = null)
+ private function createExceptionRecord($level = Logger::DEBUG, $message = 'test', $exception = null): array
{
- return $this->getRecord($level, $message, array(
- 'exception' => $exception ?: new Exception()
- ));
+ return $this->getRecord($level, $message, [
+ 'exception' => $exception ?: new Exception(),
+ ]);
}
}
diff --git a/tests/Monolog/Handler/RotatingFileHandlerTest.php b/tests/Monolog/Handler/RotatingFileHandlerTest.php
index f1feb22..f2d61db 100644
--- a/tests/Monolog/Handler/RotatingFileHandlerTest.php
+++ b/tests/Monolog/Handler/RotatingFileHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,21 +11,15 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
-use PHPUnit_Framework_Error_Deprecated;
+use InvalidArgumentException;
+use Monolog\Test\TestCase;
/**
* @covers Monolog\Handler\RotatingFileHandler
*/
class RotatingFileHandlerTest extends TestCase
{
- /**
- * This var should be private but then the anonymous function
- * in the `setUp` method won't be able to set it. `$this` cant't
- * be used in the anonymous function in `setUp` because PHP 5.3
- * does not support it.
- */
- public $lastError;
+ private $lastError;
public function setUp()
{
@@ -35,13 +29,11 @@ class RotatingFileHandlerTest extends TestCase
$this->markTestSkipped($dir.' must be writable to test the RotatingFileHandler.');
}
$this->lastError = null;
- $self = $this;
- // workaround with &$self used for PHP 5.3
- set_error_handler(function($code, $message) use (&$self) {
- $self->lastError = array(
+ set_error_handler(function ($code, $message) {
+ $this->lastError = [
'code' => $code,
'message' => $message,
- );
+ ];
});
}
@@ -107,32 +99,32 @@ class RotatingFileHandlerTest extends TestCase
public function rotationTests()
{
$now = time();
- $dayCallback = function($ago) use ($now) {
+ $dayCallback = function ($ago) use ($now) {
return $now + 86400 * $ago;
};
$monthCallback = function($ago) {
- return gmmktime(0, 0, 0, date('n') + $ago, 1, date('Y'));
+ return gmmktime(0, 0, 0, (int) (date('n') + $ago), 1, (int) date('Y'));
};
$yearCallback = function($ago) {
- return gmmktime(0, 0, 0, 1, 1, date('Y') + $ago);
+ return gmmktime(0, 0, 0, 1, 1, (int) (date('Y') + $ago));
};
- return array(
+ return [
'Rotation is triggered when the file of the current day is not present'
- => array(true, RotatingFileHandler::FILE_PER_DAY, $dayCallback),
+ => [true, RotatingFileHandler::FILE_PER_DAY, $dayCallback],
'Rotation is not triggered when the file of the current day is already present'
- => array(false, RotatingFileHandler::FILE_PER_DAY, $dayCallback),
+ => [false, RotatingFileHandler::FILE_PER_DAY, $dayCallback],
'Rotation is triggered when the file of the current month is not present'
- => array(true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback),
+ => [true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback],
'Rotation is not triggered when the file of the current month is already present'
- => array(false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback),
+ => [false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback],
'Rotation is triggered when the file of the current year is not present'
- => array(true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback),
+ => [true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback],
'Rotation is not triggered when the file of the current year is already present'
- => array(false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback),
- );
+ => [false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback],
+ ];
}
/**
@@ -141,26 +133,38 @@ class RotatingFileHandlerTest extends TestCase
public function testAllowOnlyFixedDefinedDateFormats($dateFormat, $valid)
{
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
- $handler->setFilenameFormat('{filename}-{date}', $dateFormat);
if (!$valid) {
- $this->assertErrorWasTriggered(
- E_USER_DEPRECATED,
- 'Invalid date format - format must be one of RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), '.
- 'RotatingFileHandler::FILE_PER_MONTH ("Y-m") or RotatingFileHandler::FILE_PER_YEAR ("Y"), '.
- 'or you can set one of the date formats using slashes, underscores and/or dots instead of dashes.'
- );
+ $this->setExpectedExceptionRegExp(InvalidArgumentException::class, '~^Invalid date format~');
}
+ $handler->setFilenameFormat('{filename}-{date}', $dateFormat);
+ $this->assertTrue(true);
}
public function dateFormatProvider()
{
- return array(
- array(RotatingFileHandler::FILE_PER_DAY, true),
- array(RotatingFileHandler::FILE_PER_MONTH, true),
- array(RotatingFileHandler::FILE_PER_YEAR, true),
- array('m-d-Y', false),
- array('Y-m-d-h-i', false)
- );
+ return [
+ [RotatingFileHandler::FILE_PER_DAY, true],
+ [RotatingFileHandler::FILE_PER_MONTH, true],
+ [RotatingFileHandler::FILE_PER_YEAR, true],
+ ['Y/m/d', true],
+ ['Y.m.d', true],
+ ['Y_m_d', true],
+ ['Ymd', true],
+ ['Ym/d', true],
+ ['Y/m', true],
+ ['Ym', true],
+ ['Y.m', true],
+ ['Y_m', true],
+ ['Y/md', true],
+ ['', false],
+ ['m-d-Y', false],
+ ['Y-m-d-h-i', false],
+ ['Y-', false],
+ ['Y-m-', false],
+ ['Y--', false],
+ ['m-d', false],
+ ['Y-d', false],
+ ];
}
/**
@@ -169,26 +173,24 @@ class RotatingFileHandlerTest extends TestCase
public function testDisallowFilenameFormatsWithoutDate($filenameFormat, $valid)
{
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
- $handler->setFilenameFormat($filenameFormat, RotatingFileHandler::FILE_PER_DAY);
if (!$valid) {
- $this->assertErrorWasTriggered(
- E_USER_DEPRECATED,
- 'Invalid filename format - format should contain at least `{date}`, because otherwise rotating is impossible.'
- );
+ $this->setExpectedExceptionRegExp(InvalidArgumentException::class, '~^Invalid filename format~');
}
+
+ $handler->setFilenameFormat($filenameFormat, RotatingFileHandler::FILE_PER_DAY);
}
public function filenameFormatProvider()
{
- return array(
- array('{filename}', false),
- array('{filename}-{date}', true),
- array('{date}', true),
- array('foobar-{date}', true),
- array('foo-{date}-bar', true),
- array('{date}-foobar', true),
- array('foobar', false),
- );
+ return [
+ ['{filename}', false],
+ ['{filename}-{date}', true],
+ ['{date}', true],
+ ['foobar-{date}', true],
+ ['foo-{date}-bar', true],
+ ['{date}-foobar', true],
+ ['foobar', false],
+ ];
}
public function testReuseCurrentFile()
diff --git a/tests/Monolog/Handler/SamplingHandlerTest.php b/tests/Monolog/Handler/SamplingHandlerTest.php
index b354cee..90f5c9b 100644
--- a/tests/Monolog/Handler/SamplingHandlerTest.php
+++ b/tests/Monolog/Handler/SamplingHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
/**
* @covers Monolog\Handler\SamplingHandler::handle
diff --git a/tests/Monolog/Handler/Slack/SlackRecordTest.php b/tests/Monolog/Handler/Slack/SlackRecordTest.php
index e1aa96d..aa5787f 100644
--- a/tests/Monolog/Handler/Slack/SlackRecordTest.php
+++ b/tests/Monolog/Handler/Slack/SlackRecordTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler\Slack;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
/**
* @coversDefaultClass Monolog\Handler\Slack\SlackRecord
@@ -42,8 +42,8 @@ class SlackRecordTest extends TestCase
/**
* @dataProvider dataGetAttachmentColor
- * @param int $logLevel
- * @param string $expectedColour RGB hex color or name of Slack color
+ * @param int $logLevel
+ * @param string $expectedColour RGB hex color or name of Slack color
* @covers ::getAttachmentColor
*/
public function testGetAttachmentColor($logLevel, $expectedColour)
@@ -88,7 +88,7 @@ class SlackRecordTest extends TestCase
array(array(), '[]'),
array($multipleDimensions, json_encode($multipleDimensions, $jsonPrettyPrintFlag)),
array($numericKeys, json_encode($numericKeys, $jsonPrettyPrintFlag)),
- array($singleDimension, json_encode($singleDimension))
+ array($singleDimension, json_encode($singleDimension)),
);
}
@@ -172,17 +172,21 @@ class SlackRecordTest extends TestCase
public function testTextEqualsFormatterOutput()
{
- $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface');
+ $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$formatter
->expects($this->any())
->method('format')
- ->will($this->returnCallback(function ($record) { return $record['message'] . 'test'; }));
+ ->will($this->returnCallback(function ($record) {
+ return $record['message'] . 'test';
+ }));
- $formatter2 = $this->getMock('Monolog\\Formatter\\FormatterInterface');
+ $formatter2 = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$formatter2
->expects($this->any())
->method('format')
- ->will($this->returnCallback(function ($record) { return $record['message'] . 'test1'; }));
+ ->will($this->returnCallback(function ($record) {
+ return $record['message'] . 'test1';
+ }));
$message = 'Test message';
$record = new SlackRecord(null, null, false, null, false, false, array(), $formatter);
@@ -268,13 +272,13 @@ class SlackRecordTest extends TestCase
array(
'title' => 'Extra',
'value' => sprintf('```%s```', json_encode($extra, $this->jsonPrettyPrintFlag)),
- 'short' => false
+ 'short' => false,
),
array(
'title' => 'Context',
'value' => sprintf('```%s```', json_encode($context, $this->jsonPrettyPrintFlag)),
- 'short' => false
- )
+ 'short' => false,
+ ),
),
$attachment['fields']
);
@@ -296,7 +300,7 @@ class SlackRecordTest extends TestCase
array(array(
'title' => 'Level',
'value' => $levelName,
- 'short' => false
+ 'short' => false,
)),
$attachment['fields']
);
@@ -322,13 +326,13 @@ class SlackRecordTest extends TestCase
array(
'title' => 'tags',
'value' => sprintf('```%s```', json_encode($extra['tags'])),
- 'short' => false
+ 'short' => false,
),
array(
'title' => 'test',
'value' => $context['test'],
- 'short' => false
- )
+ 'short' => false,
+ ),
);
$attachment = $data['attachments'][0];
@@ -370,12 +374,12 @@ class SlackRecordTest extends TestCase
array(
'title' => 'info',
'value' => sprintf('```%s```', json_encode(array('author' => 'Jordi'), $this->jsonPrettyPrintFlag)),
- 'short' => false
+ 'short' => false,
),
array(
'title' => 'tags',
'value' => sprintf('```%s```', json_encode(array('web'))),
- 'short' => false
+ 'short' => false,
),
);
diff --git a/tests/Monolog/Handler/SlackHandlerTest.php b/tests/Monolog/Handler/SlackHandlerTest.php
index b12b01f..e8abd15 100644
--- a/tests/Monolog/Handler/SlackHandlerTest.php
+++ b/tests/Monolog/Handler/SlackHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\Slack\SlackRecord;
@@ -46,7 +46,7 @@ class SlackHandlerTest extends TestCase
fseek($this->res, 0);
$content = fread($this->res, 1024);
- $this->assertRegexp('/POST \/api\/chat.postMessage HTTP\/1.1\\r\\nHost: slack.com\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content);
+ $this->assertRegexp('{POST /api/chat.postMessage HTTP/1.1\\r\\nHost: slack.com\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content);
}
public function testWriteContent()
@@ -128,15 +128,14 @@ class SlackHandlerTest extends TestCase
private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false)
{
- $constructorArgs = array($token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra);
+ $constructorArgs = [$token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra];
$this->res = fopen('php://memory', 'a');
- $this->handler = $this->getMock(
- '\Monolog\Handler\SlackHandler',
- array('fsockopen', 'streamSetTimeout', 'closeSocket'),
- $constructorArgs
- );
+ $this->handler = $this->getMockBuilder('Monolog\Handler\SlackHandler')
+ ->setConstructorArgs($constructorArgs)
+ ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
+ ->getMock();
- $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString');
+ $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($this->handler, 'localhost:1234');
diff --git a/tests/Monolog/Handler/SlackWebhookHandlerTest.php b/tests/Monolog/Handler/SlackWebhookHandlerTest.php
index c9229e2..8ce7210 100644
--- a/tests/Monolog/Handler/SlackWebhookHandlerTest.php
+++ b/tests/Monolog/Handler/SlackWebhookHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\Slack\SlackRecord;
diff --git a/tests/Monolog/Handler/SlackbotHandlerTest.php b/tests/Monolog/Handler/SlackbotHandlerTest.php
index b1b02bd..340c4c6 100644
--- a/tests/Monolog/Handler/SlackbotHandlerTest.php
+++ b/tests/Monolog/Handler/SlackbotHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
diff --git a/tests/Monolog/Handler/SocketHandlerTest.php b/tests/Monolog/Handler/SocketHandlerTest.php
index 1f9c1f2..c0080e8 100644
--- a/tests/Monolog/Handler/SocketHandlerTest.php
+++ b/tests/Monolog/Handler/SocketHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -88,7 +88,7 @@ class SocketHandlerTest extends TestCase
*/
public function testExceptionIsThrownOnFsockopenError()
{
- $this->setMockHandler(array('fsockopen'));
+ $this->setMockHandler(['fsockopen']);
$this->handler->expects($this->once())
->method('fsockopen')
->will($this->returnValue(false));
@@ -100,7 +100,7 @@ class SocketHandlerTest extends TestCase
*/
public function testExceptionIsThrownOnPfsockopenError()
{
- $this->setMockHandler(array('pfsockopen'));
+ $this->setMockHandler(['pfsockopen']);
$this->handler->expects($this->once())
->method('pfsockopen')
->will($this->returnValue(false));
@@ -113,7 +113,7 @@ class SocketHandlerTest extends TestCase
*/
public function testExceptionIsThrownIfCannotSetTimeout()
{
- $this->setMockHandler(array('streamSetTimeout'));
+ $this->setMockHandler(['streamSetTimeout']);
$this->handler->expects($this->once())
->method('streamSetTimeout')
->will($this->returnValue(false));
@@ -125,13 +125,13 @@ class SocketHandlerTest extends TestCase
*/
public function testWriteFailsOnIfFwriteReturnsFalse()
{
- $this->setMockHandler(array('fwrite'));
+ $this->setMockHandler(['fwrite']);
$callback = function ($arg) {
- $map = array(
+ $map = [
'Hello world' => 6,
'world' => false,
- );
+ ];
return $map[$arg];
};
@@ -148,13 +148,13 @@ class SocketHandlerTest extends TestCase
*/
public function testWriteFailsIfStreamTimesOut()
{
- $this->setMockHandler(array('fwrite', 'streamGetMetadata'));
+ $this->setMockHandler(['fwrite', 'streamGetMetadata']);
$callback = function ($arg) {
- $map = array(
+ $map = [
'Hello world' => 6,
'world' => 5,
- );
+ ];
return $map[$arg];
};
@@ -164,7 +164,7 @@ class SocketHandlerTest extends TestCase
->will($this->returnCallback($callback));
$this->handler->expects($this->exactly(1))
->method('streamGetMetadata')
- ->will($this->returnValue(array('timed_out' => true)));
+ ->will($this->returnValue(['timed_out' => true]));
$this->writeRecord('Hello world');
}
@@ -174,7 +174,7 @@ class SocketHandlerTest extends TestCase
*/
public function testWriteFailsOnIncompleteWrite()
{
- $this->setMockHandler(array('fwrite', 'streamGetMetadata'));
+ $this->setMockHandler(['fwrite', 'streamGetMetadata']);
$res = $this->res;
$callback = function ($string) use ($res) {
@@ -188,7 +188,7 @@ class SocketHandlerTest extends TestCase
->will($this->returnCallback($callback));
$this->handler->expects($this->exactly(1))
->method('streamGetMetadata')
- ->will($this->returnValue(array('timed_out' => false)));
+ ->will($this->returnValue(['timed_out' => false]));
$this->writeRecord('Hello world');
}
@@ -205,13 +205,13 @@ class SocketHandlerTest extends TestCase
public function testWriteWithMock()
{
- $this->setMockHandler(array('fwrite'));
+ $this->setMockHandler(['fwrite']);
$callback = function ($arg) {
- $map = array(
+ $map = [
'Hello world' => 6,
'world' => 5,
- );
+ ];
return $map[$arg];
};
@@ -247,7 +247,7 @@ class SocketHandlerTest extends TestCase
*/
public function testAvoidInfiniteLoopWhenNoDataIsWrittenForAWritingTimeoutSeconds()
{
- $this->setMockHandler(array('fwrite', 'streamGetMetadata'));
+ $this->setMockHandler(['fwrite', 'streamGetMetadata']);
$this->handler->expects($this->any())
->method('fwrite')
@@ -255,7 +255,7 @@ class SocketHandlerTest extends TestCase
$this->handler->expects($this->any())
->method('streamGetMetadata')
- ->will($this->returnValue(array('timed_out' => false)));
+ ->will($this->returnValue(['timed_out' => false]));
$this->handler->setWritingTimeout(1);
@@ -273,18 +273,19 @@ class SocketHandlerTest extends TestCase
$this->handler->handle($this->getRecord(Logger::WARNING, $string));
}
- private function setMockHandler(array $methods = array())
+ private function setMockHandler(array $methods = [])
{
$this->res = fopen('php://memory', 'a');
- $defaultMethods = array('fsockopen', 'pfsockopen', 'streamSetTimeout');
+ $defaultMethods = ['fsockopen', 'pfsockopen', 'streamSetTimeout'];
$newMethods = array_diff($methods, $defaultMethods);
$finalMethods = array_merge($defaultMethods, $newMethods);
- $this->handler = $this->getMock(
- '\Monolog\Handler\SocketHandler', $finalMethods, array('localhost:1234')
- );
+ $this->handler = $this->getMockBuilder('Monolog\Handler\SocketHandler')
+ ->setMethods($finalMethods)
+ ->setConstructorArgs(['localhost:1234'])
+ ->getMock();
if (!in_array('fsockopen', $methods)) {
$this->handler->expects($this->any())
diff --git a/tests/Monolog/Handler/StreamHandlerTest.php b/tests/Monolog/Handler/StreamHandlerTest.php
index 487030f..377e296 100644
--- a/tests/Monolog/Handler/StreamHandlerTest.php
+++ b/tests/Monolog/Handler/StreamHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
class StreamHandlerTest extends TestCase
@@ -51,13 +51,38 @@ class StreamHandlerTest extends TestCase
{
$handler = new StreamHandler('php://memory');
$handler->handle($this->getRecord(Logger::WARNING, 'test'));
- $streamProp = new \ReflectionProperty('Monolog\Handler\StreamHandler', 'stream');
- $streamProp->setAccessible(true);
- $handle = $streamProp->getValue($handler);
+ $stream = $handler->getStream();
- $this->assertTrue(is_resource($handle));
+ $this->assertTrue(is_resource($stream));
$handler->close();
- $this->assertFalse(is_resource($handle));
+ $this->assertFalse(is_resource($stream));
+ }
+
+ /**
+ * @covers Monolog\Handler\StreamHandler::close
+ * @covers Monolog\Handler\Handler::__sleep
+ */
+ public function testSerialization()
+ {
+ $handler = new StreamHandler('php://memory');
+ $handler->handle($this->getRecord(Logger::WARNING, 'testfoo'));
+ $stream = $handler->getStream();
+
+ $this->assertTrue(is_resource($stream));
+ fseek($stream, 0);
+ $this->assertContains('testfoo', stream_get_contents($stream));
+ $serialized = serialize($handler);
+ $this->assertFalse(is_resource($stream));
+
+ $handler = unserialize($serialized);
+ $handler->handle($this->getRecord(Logger::WARNING, 'testbar'));
+ $stream = $handler->getStream();
+
+ $this->assertTrue(is_resource($stream));
+ fseek($stream, 0);
+ $contents = stream_get_contents($stream);
+ $this->assertNotContains('testfoo', $contents);
+ $this->assertContains('testbar', $contents);
}
/**
@@ -93,11 +118,11 @@ class StreamHandlerTest extends TestCase
public function invalidArgumentProvider()
{
- return array(
- array(1),
- array(array()),
- array(array('bogus://url')),
- );
+ return [
+ [1],
+ [[]],
+ [['bogus://url']],
+ ];
}
/**
diff --git a/tests/Monolog/Handler/SwiftMailerHandlerTest.php b/tests/Monolog/Handler/SwiftMailerHandlerTest.php
index 1d62940..3c77127 100644
--- a/tests/Monolog/Handler/SwiftMailerHandlerTest.php
+++ b/tests/Monolog/Handler/SwiftMailerHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -12,7 +12,7 @@
namespace Monolog\Handler;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class SwiftMailerHandlerTest extends TestCase
{
@@ -37,10 +37,10 @@ class SwiftMailerHandlerTest extends TestCase
};
$handler = new SwiftMailerHandler($this->mailer, $callback);
- $records = array(
+ $records = [
$this->getRecord(Logger::DEBUG),
$this->getRecord(Logger::INFO),
- );
+ ];
$handler->handleBatch($records);
}
@@ -66,9 +66,9 @@ class SwiftMailerHandlerTest extends TestCase
$handler = new SwiftMailerHandler($this->mailer, $callback);
// Logging 1 record makes this an Emergency
- $records = array(
+ $records = [
$this->getRecord(Logger::EMERGENCY),
- );
+ ];
$handler->handleBatch($records);
}
@@ -83,14 +83,15 @@ class SwiftMailerHandlerTest extends TestCase
->method('send')
->with($this->callback(function ($value) use (&$receivedMessage) {
$receivedMessage = $value;
+
return true;
}));
$handler = new SwiftMailerHandler($this->mailer, $messageTemplate);
- $records = array(
+ $records = [
$this->getRecord(Logger::EMERGENCY),
- );
+ ];
$handler->handleBatch($records);
$this->assertEquals('Alert: EMERGENCY test', $receivedMessage->getSubject());
@@ -103,10 +104,10 @@ class SwiftMailerHandlerTest extends TestCase
$method = new \ReflectionMethod('Monolog\Handler\SwiftMailerHandler', 'buildMessage');
$method->setAccessible(true);
- $method->invokeArgs($handler, array($messageTemplate, array()));
+ $method->invokeArgs($handler, [$messageTemplate, []]);
- $builtMessage1 = $method->invoke($handler, $messageTemplate, array());
- $builtMessage2 = $method->invoke($handler, $messageTemplate, array());
+ $builtMessage1 = $method->invoke($handler, $messageTemplate, []);
+ $builtMessage2 = $method->invoke($handler, $messageTemplate, []);
$this->assertFalse($builtMessage1->getId() === $builtMessage2->getId(), 'Two different messages have the same id');
}
diff --git a/tests/Monolog/Handler/SyslogHandlerTest.php b/tests/Monolog/Handler/SyslogHandlerTest.php
index 8f9e46b..550e210 100644
--- a/tests/Monolog/Handler/SyslogHandlerTest.php
+++ b/tests/Monolog/Handler/SyslogHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -13,7 +13,7 @@ namespace Monolog\Handler;
use Monolog\Logger;
-class SyslogHandlerTest extends \PHPUnit_Framework_TestCase
+class SyslogHandlerTest extends \PHPUnit\Framework\TestCase
{
/**
* @covers Monolog\Handler\SyslogHandler::__construct
@@ -38,7 +38,7 @@ class SyslogHandlerTest extends \PHPUnit_Framework_TestCase
*/
public function testConstructInvalidFacility()
{
- $this->setExpectedException('UnexpectedValueException');
+ $this->expectException('UnexpectedValueException');
$handler = new SyslogHandler('test', 'unknown');
}
}
diff --git a/tests/Monolog/Handler/SyslogUdpHandlerTest.php b/tests/Monolog/Handler/SyslogUdpHandlerTest.php
index 7ee8a98..9f32d91 100644
--- a/tests/Monolog/Handler/SyslogUdpHandlerTest.php
+++ b/tests/Monolog/Handler/SyslogUdpHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
/**
* @requires extension sockets
@@ -42,7 +42,10 @@ class SyslogUdpHandlerTest extends TestCase
$handler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter());
- $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('write'), array('lol', 'lol'));
+ $socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
+ ->setMethods(['write'])
+ ->setConstructorArgs(['lol', 'lol'])
+ ->getMock();
$socket->expects($this->at(0))
->method('write')
->with("lol", "<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - ");
@@ -60,7 +63,10 @@ class SyslogUdpHandlerTest extends TestCase
$handler = new SyslogUdpHandler("127.0.0.1", 514, "authpriv");
$handler->setFormatter($this->getIdentityFormatter());
- $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('write'), array('lol', 'lol'));
+ $socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
+ ->setMethods(['write'])
+ ->setConstructorArgs(['lol', 'lol'])
+ ->getMock();
$socket->expects($this->never())
->method('write');
@@ -71,6 +77,6 @@ class SyslogUdpHandlerTest extends TestCase
protected function getRecordWithMessage($msg)
{
- return array('message' => $msg, 'level' => \Monolog\Logger::WARNING, 'context' => null, 'extra' => array(), 'channel' => 'lol');
+ return ['message' => $msg, 'level' => \Monolog\Logger::WARNING, 'context' => null, 'extra' => [], 'channel' => 'lol'];
}
}
diff --git a/tests/Monolog/Handler/TestHandlerTest.php b/tests/Monolog/Handler/TestHandlerTest.php
index bfb8d3d..db3f01f 100644
--- a/tests/Monolog/Handler/TestHandlerTest.php
+++ b/tests/Monolog/Handler/TestHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
/**
@@ -51,20 +51,20 @@ class TestHandlerTest extends TestCase
$records = $handler->getRecords();
unset($records[0]['formatted']);
- $this->assertEquals(array($record), $records);
+ $this->assertEquals([$record], $records);
}
public function methodProvider()
{
- return array(
- array('Emergency', Logger::EMERGENCY),
- array('Alert' , Logger::ALERT),
- array('Critical' , Logger::CRITICAL),
- array('Error' , Logger::ERROR),
- array('Warning' , Logger::WARNING),
- array('Info' , Logger::INFO),
- array('Notice' , Logger::NOTICE),
- array('Debug' , Logger::DEBUG),
- );
+ return [
+ ['Emergency', Logger::EMERGENCY],
+ ['Alert' , Logger::ALERT],
+ ['Critical' , Logger::CRITICAL],
+ ['Error' , Logger::ERROR],
+ ['Warning' , Logger::WARNING],
+ ['Info' , Logger::INFO],
+ ['Notice' , Logger::NOTICE],
+ ['Debug' , Logger::DEBUG],
+ ];
}
}
diff --git a/tests/Monolog/Handler/UdpSocketTest.php b/tests/Monolog/Handler/UdpSocketTest.php
index fa524d0..1adf79a 100644
--- a/tests/Monolog/Handler/UdpSocketTest.php
+++ b/tests/Monolog/Handler/UdpSocketTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Handler\SyslogUdp\UdpSocket;
/**
@@ -21,7 +21,10 @@ class UdpSocketTest extends TestCase
{
public function testWeDoNotTruncateShortMessages()
{
- $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('send'), array('lol', 'lol'));
+ $socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
+ ->setMethods(['send'])
+ ->setConstructorArgs(['lol', 'lol'])
+ ->getMock();
$socket->expects($this->at(0))
->method('send')
@@ -32,7 +35,10 @@ class UdpSocketTest extends TestCase
public function testLongMessagesAreTruncated()
{
- $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('send'), array('lol', 'lol'));
+ $socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
+ ->setMethods(['send'])
+ ->setConstructorArgs(['lol', 'lol'])
+ ->getMock();
$truncatedString = str_repeat("derp", 16254).'d';
@@ -53,7 +59,7 @@ class UdpSocketTest extends TestCase
}
/**
- * @expectedException LogicException
+ * @expectedException RuntimeException
*/
public function testWriteAfterCloseErrors()
{
diff --git a/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php b/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php
index 8d37a1f..60f5175 100644
--- a/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php
+++ b/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Logger;
class WhatFailureGroupHandlerTest extends TestCase
@@ -22,7 +22,7 @@ class WhatFailureGroupHandlerTest extends TestCase
*/
public function testConstructorOnlyTakesHandler()
{
- new WhatFailureGroupHandler(array(new TestHandler(), "foo"));
+ new WhatFailureGroupHandler([new TestHandler(), "foo"]);
}
/**
@@ -31,7 +31,7 @@ class WhatFailureGroupHandlerTest extends TestCase
*/
public function testHandle()
{
- $testHandlers = array(new TestHandler(), new TestHandler());
+ $testHandlers = [new TestHandler(), new TestHandler()];
$handler = new WhatFailureGroupHandler($testHandlers);
$handler->handle($this->getRecord(Logger::DEBUG));
$handler->handle($this->getRecord(Logger::INFO));
@@ -47,9 +47,9 @@ class WhatFailureGroupHandlerTest extends TestCase
*/
public function testHandleBatch()
{
- $testHandlers = array(new TestHandler(), new TestHandler());
+ $testHandlers = [new TestHandler(), new TestHandler()];
$handler = new WhatFailureGroupHandler($testHandlers);
- $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)));
+ $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
@@ -62,7 +62,7 @@ class WhatFailureGroupHandlerTest extends TestCase
*/
public function testIsHandling()
{
- $testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING));
+ $testHandlers = [new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)];
$handler = new WhatFailureGroupHandler($testHandlers);
$this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR)));
$this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING)));
@@ -75,7 +75,7 @@ class WhatFailureGroupHandlerTest extends TestCase
public function testHandleUsesProcessors()
{
$test = new TestHandler();
- $handler = new WhatFailureGroupHandler(array($test));
+ $handler = new WhatFailureGroupHandler([$test]);
$handler->pushProcessor(function ($record) {
$record['extra']['foo'] = true;
@@ -94,7 +94,7 @@ class WhatFailureGroupHandlerTest extends TestCase
{
$test = new TestHandler();
$exception = new ExceptionTestHandler();
- $handler = new WhatFailureGroupHandler(array($exception, $test, $exception));
+ $handler = new WhatFailureGroupHandler([$exception, $test, $exception]);
$handler->pushProcessor(function ($record) {
$record['extra']['foo'] = true;
@@ -112,7 +112,7 @@ class ExceptionTestHandler extends TestHandler
/**
* {@inheritdoc}
*/
- public function handle(array $record)
+ public function handle(array $record): bool
{
parent::handle($record);
diff --git a/tests/Monolog/Handler/ZendMonitorHandlerTest.php b/tests/Monolog/Handler/ZendMonitorHandlerTest.php
index 69b001e..4879ebe 100644
--- a/tests/Monolog/Handler/ZendMonitorHandlerTest.php
+++ b/tests/Monolog/Handler/ZendMonitorHandlerTest.php
@@ -1,4 +1,5 @@
-<?php
+<?php declare(strict_types=1);
+
/*
* This file is part of the Monolog package.
*
@@ -10,7 +11,7 @@
namespace Monolog\Handler;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class ZendMonitorHandlerTest extends TestCase
{
@@ -29,12 +30,12 @@ class ZendMonitorHandlerTest extends TestCase
public function testWrite()
{
$record = $this->getRecord();
- $formatterResult = array(
+ $formatterResult = [
'message' => $record['message'],
- );
+ ];
$zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler')
- ->setMethods(array('writeZendMonitorCustomEvent', 'getDefaultFormatter'))
+ ->setMethods(['writeZendMonitorCustomEvent', 'getDefaultFormatter'])
->getMock();
$formatterMock = $this->getMockBuilder('Monolog\Formatter\NormalizerFormatter')
diff --git a/tests/Monolog/LoggerTest.php b/tests/Monolog/LoggerTest.php
index 1ecc34a..428daa0 100644
--- a/tests/Monolog/LoggerTest.php
+++ b/tests/Monolog/LoggerTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -14,7 +14,7 @@ namespace Monolog;
use Monolog\Processor\WebProcessor;
use Monolog\Handler\TestHandler;
-class LoggerTest extends \PHPUnit_Framework_TestCase
+class LoggerTest extends \PHPUnit\Framework\TestCase
{
/**
* @covers Monolog\Logger::getName
@@ -38,7 +38,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
*/
public function testWithName()
{
- $first = new Logger('first', array($handler = new TestHandler()));
+ $first = new Logger('first', [$handler = new TestHandler()]);
$second = $first->withName('second');
$this->assertSame('first', $first->getName());
@@ -78,7 +78,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
$logger = new Logger('foo');
$handler = new TestHandler;
$logger->pushHandler($handler);
- $logger->addWarning('test');
+ $logger->warning('test');
list($record) = $handler->getRecords();
$this->assertEquals('foo', $record['channel']);
}
@@ -90,12 +90,13 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
{
$logger = new Logger(__METHOD__);
- $handler = $this->getMock('Monolog\Handler\NullHandler', array('handle'));
- $handler->expects($this->once())
- ->method('handle');
- $logger->pushHandler($handler);
+ $handler = $this->prophesize('Monolog\Handler\NullHandler');
+ $handler->handle(\Prophecy\Argument::any())->shouldBeCalled();
+ $handler->isHandling(['level' => 300])->willReturn(true);
- $this->assertTrue($logger->addWarning('test'));
+ $logger->pushHandler($handler->reveal());
+
+ $this->assertTrue($logger->addRecord(Logger::WARNING, 'test'));
}
/**
@@ -105,19 +106,20 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
{
$logger = new Logger(__METHOD__);
- $handler = $this->getMock('Monolog\Handler\NullHandler', array('handle'), array(Logger::ERROR));
- $handler->expects($this->never())
- ->method('handle');
- $logger->pushHandler($handler);
+ $handler = $this->prophesize('Monolog\Handler\NullHandler');
+ $handler->handle()->shouldNotBeCalled();
+ $handler->isHandling(['level' => 300])->willReturn(false);
- $this->assertFalse($logger->addWarning('test'));
+ $logger->pushHandler($handler->reveal());
+
+ $this->assertFalse($logger->addRecord(Logger::WARNING, 'test'));
}
public function testHandlersInCtor()
{
$handler1 = new TestHandler;
$handler2 = new TestHandler;
- $logger = new Logger(__METHOD__, array($handler1, $handler2));
+ $logger = new Logger(__METHOD__, [$handler1, $handler2]);
$this->assertEquals($handler1, $logger->popHandler());
$this->assertEquals($handler2, $logger->popHandler());
@@ -127,7 +129,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
{
$processor1 = new WebProcessor;
$processor2 = new WebProcessor;
- $logger = new Logger(__METHOD__, array(), array($processor1, $processor2));
+ $logger = new Logger(__METHOD__, [], [$processor1, $processor2]);
$this->assertEquals($processor1, $logger->popProcessor());
$this->assertEquals($processor2, $logger->popProcessor());
@@ -162,18 +164,18 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
$handler2 = new TestHandler;
$logger->pushHandler($handler1);
- $logger->setHandlers(array($handler2));
+ $logger->setHandlers([$handler2]);
// handler1 has been removed
- $this->assertEquals(array($handler2), $logger->getHandlers());
+ $this->assertEquals([$handler2], $logger->getHandlers());
- $logger->setHandlers(array(
+ $logger->setHandlers([
"AMapKey" => $handler1,
"Woop" => $handler2,
- ));
+ ]);
// Keys have been scrubbed
- $this->assertEquals(array($handler1, $handler2), $logger->getHandlers());
+ $this->assertEquals([$handler1, $handler2], $logger->getHandlers());
}
/**
@@ -196,17 +198,6 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
}
/**
- * @covers Monolog\Logger::pushProcessor
- * @expectedException InvalidArgumentException
- */
- public function testPushProcessorWithNonCallable()
- {
- $logger = new Logger(__METHOD__);
-
- $logger->pushProcessor(new \stdClass());
- }
-
- /**
* @covers Monolog\Logger::addRecord
*/
public function testProcessorsAreExecuted()
@@ -219,7 +210,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
return $record;
});
- $logger->addError('test');
+ $logger->error('test');
list($record) = $handler->getRecords();
$this->assertTrue($record['extra']['win']);
}
@@ -230,7 +221,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
public function testProcessorsAreCalledOnlyOnce()
{
$logger = new Logger(__METHOD__);
- $handler = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler = $this->createMock('Monolog\Handler\HandlerInterface');
$handler->expects($this->any())
->method('isHandling')
->will($this->returnValue(true))
@@ -243,7 +234,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
$processor = $this->getMockBuilder('Monolog\Processor\WebProcessor')
->disableOriginalConstructor()
- ->setMethods(array('__invoke'))
+ ->setMethods(['__invoke'])
->getMock()
;
$processor->expects($this->once())
@@ -252,7 +243,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
;
$logger->pushProcessor($processor);
- $logger->addError('test');
+ $logger->error('test');
}
/**
@@ -261,7 +252,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
public function testProcessorsNotCalledWhenNotHandled()
{
$logger = new Logger(__METHOD__);
- $handler = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler = $this->createMock('Monolog\Handler\HandlerInterface');
$handler->expects($this->once())
->method('isHandling')
->will($this->returnValue(false))
@@ -271,7 +262,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
$logger->pushProcessor(function ($record) use ($that) {
$that->fail('The processor should not be called');
});
- $logger->addAlert('test');
+ $logger->alert('test');
}
/**
@@ -281,7 +272,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
{
$logger = new Logger(__METHOD__);
- $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->never())
->method('isHandling')
->will($this->returnValue(false))
@@ -292,7 +283,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
;
$logger->pushHandler($handler1);
- $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->once())
->method('isHandling')
->will($this->returnValue(true))
@@ -303,7 +294,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
;
$logger->pushHandler($handler2);
- $handler3 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler3 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler3->expects($this->once())
->method('isHandling')
->will($this->returnValue(false))
@@ -321,7 +312,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
*/
public function testHandlersNotCalledBeforeFirstHandlingWithAssocArray()
{
- $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->never())
->method('isHandling')
->will($this->returnValue(false))
@@ -331,7 +322,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue(false))
;
- $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->once())
->method('isHandling')
->will($this->returnValue(true))
@@ -341,7 +332,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue(false))
;
- $handler3 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler3 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler3->expects($this->once())
->method('isHandling')
->will($this->returnValue(false))
@@ -350,7 +341,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
->method('handle')
;
- $logger = new Logger(__METHOD__, array('last' => $handler3, 'second' => $handler2, 'first' => $handler1));
+ $logger = new Logger(__METHOD__, ['last' => $handler3, 'second' => $handler2, 'first' => $handler1]);
$logger->debug('test');
}
@@ -362,7 +353,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
{
$logger = new Logger(__METHOD__);
- $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->any())
->method('isHandling')
->will($this->returnValue(true))
@@ -373,7 +364,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
;
$logger->pushHandler($handler1);
- $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->any())
->method('isHandling')
->will($this->returnValue(true))
@@ -394,7 +385,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
{
$logger = new Logger(__METHOD__);
- $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->any())
->method('isHandling')
->will($this->returnValue(true))
@@ -404,7 +395,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
;
$logger->pushHandler($handler1);
- $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->any())
->method('isHandling')
->will($this->returnValue(true))
@@ -425,7 +416,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
{
$logger = new Logger(__METHOD__);
- $handler1 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->any())
->method('isHandling')
->will($this->returnValue(false))
@@ -434,7 +425,7 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
$logger->pushHandler($handler1);
$this->assertFalse($logger->isHandling(Logger::DEBUG));
- $handler2 = $this->getMock('Monolog\Handler\HandlerInterface');
+ $handler2 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler2->expects($this->any())
->method('isHandling')
->will($this->returnValue(true))
@@ -446,22 +437,14 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider logMethodProvider
- * @covers Monolog\Logger::addDebug
- * @covers Monolog\Logger::addInfo
- * @covers Monolog\Logger::addNotice
- * @covers Monolog\Logger::addWarning
- * @covers Monolog\Logger::addError
- * @covers Monolog\Logger::addCritical
- * @covers Monolog\Logger::addAlert
- * @covers Monolog\Logger::addEmergency
* @covers Monolog\Logger::debug
* @covers Monolog\Logger::info
* @covers Monolog\Logger::notice
- * @covers Monolog\Logger::warn
- * @covers Monolog\Logger::err
- * @covers Monolog\Logger::crit
+ * @covers Monolog\Logger::warning
+ * @covers Monolog\Logger::error
+ * @covers Monolog\Logger::critical
* @covers Monolog\Logger::alert
- * @covers Monolog\Logger::emerg
+ * @covers Monolog\Logger::emergency
*/
public function testLogMethods($method, $expectedLevel)
{
@@ -475,27 +458,17 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
public function logMethodProvider()
{
- return array(
- // monolog methods
- array('addDebug', Logger::DEBUG),
- array('addInfo', Logger::INFO),
- array('addNotice', Logger::NOTICE),
- array('addWarning', Logger::WARNING),
- array('addError', Logger::ERROR),
- array('addCritical', Logger::CRITICAL),
- array('addAlert', Logger::ALERT),
- array('addEmergency', Logger::EMERGENCY),
-
- // ZF/Sf2 compat methods
- array('debug', Logger::DEBUG),
- array('info', Logger::INFO),
- array('notice', Logger::NOTICE),
- array('warn', Logger::WARNING),
- array('err', Logger::ERROR),
- array('crit', Logger::CRITICAL),
- array('alert', Logger::ALERT),
- array('emerg', Logger::EMERGENCY),
- );
+ return [
+ // PSR-3 methods
+ ['debug', Logger::DEBUG],
+ ['info', Logger::INFO],
+ ['notice', Logger::NOTICE],
+ ['warning', Logger::WARNING],
+ ['error', Logger::ERROR],
+ ['critical', Logger::CRITICAL],
+ ['alert', Logger::ALERT],
+ ['emergency', Logger::EMERGENCY],
+ ];
}
/**
@@ -504,8 +477,8 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
*/
public function testSetTimezone($tz)
{
- Logger::setTimezone($tz);
$logger = new Logger('foo');
+ $logger->setTimezone($tz);
$handler = new TestHandler;
$logger->pushHandler($handler);
$logger->info('test');
@@ -516,18 +489,74 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
public function setTimezoneProvider()
{
return array_map(
- function ($tz) { return array(new \DateTimeZone($tz)); },
+ function ($tz) {
+ return [new \DateTimeZone($tz)];
+ },
\DateTimeZone::listIdentifiers()
);
}
/**
+ * @covers Monolog\Logger::setTimezone
+ * @covers Monolog\DateTimeImmutable::__construct
+ */
+ public function testTimezoneIsRespectedInUTC()
+ {
+ foreach ([true, false] as $microseconds) {
+ $logger = new Logger('foo');
+ $logger->useMicrosecondTimestamps($microseconds);
+ $tz = new \DateTimeZone('America/New_York');
+ $logger->setTimezone($tz);
+ $handler = new TestHandler;
+ $logger->pushHandler($handler);
+ $dt = new \DateTime('now', $tz);
+ $logger->info('test');
+ list($record) = $handler->getRecords();
+
+ $this->assertEquals($tz, $record['datetime']->getTimezone());
+ $this->assertEquals($dt->format('Y/m/d H:i'), $record['datetime']->format('Y/m/d H:i'), 'Time should match timezone with microseconds set to: '.var_export($microseconds, true));
+ }
+ }
+
+ /**
+ * @covers Monolog\Logger::setTimezone
+ * @covers Monolog\DateTimeImmutable::__construct
+ */
+ public function testTimezoneIsRespectedInOtherTimezone()
+ {
+ date_default_timezone_set('CET');
+ foreach ([true, false] as $microseconds) {
+ $logger = new Logger('foo');
+ $logger->useMicrosecondTimestamps($microseconds);
+ $tz = new \DateTimeZone('America/New_York');
+ $logger->setTimezone($tz);
+ $handler = new TestHandler;
+ $logger->pushHandler($handler);
+ $dt = new \DateTime('now', $tz);
+ $logger->info('test');
+ list($record) = $handler->getRecords();
+
+ $this->assertEquals($tz, $record['datetime']->getTimezone());
+ $this->assertEquals($dt->format('Y/m/d H:i'), $record['datetime']->format('Y/m/d H:i'), 'Time should match timezone with microseconds set to: '.var_export($microseconds, true));
+ }
+ }
+
+ public function tearDown()
+ {
+ date_default_timezone_set('UTC');
+ }
+
+ /**
* @dataProvider useMicrosecondTimestampsProvider
* @covers Monolog\Logger::useMicrosecondTimestamps
* @covers Monolog\Logger::addRecord
*/
- public function testUseMicrosecondTimestamps($micro, $assert)
+ public function testUseMicrosecondTimestamps($micro, $assert, $assertFormat)
{
+ if (PHP_VERSION_ID === 70103) {
+ $this->markTestSkipped();
+ }
+
$logger = new Logger('foo');
$logger->useMicrosecondTimestamps($micro);
$handler = new TestHandler;
@@ -535,14 +564,16 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
$logger->info('test');
list($record) = $handler->getRecords();
$this->{$assert}('000000', $record['datetime']->format('u'));
+ $this->assertSame($record['datetime']->format($assertFormat), (string) $record['datetime']);
}
public function useMicrosecondTimestampsProvider()
{
- return array(
+ return [
// this has a very small chance of a false negative (1/10^6)
- 'with microseconds' => array(true, 'assertNotSame'),
- 'without microseconds' => array(false, PHP_VERSION_ID >= 70100 ? 'assertNotSame' : 'assertSame'),
- );
+ 'with microseconds' => [true, 'assertNotSame', 'Y-m-d\TH:i:s.uP'],
+ // php 7.1 always includes microseconds, so we keep them in, but we format the datetime without
+ 'without microseconds' => [false, PHP_VERSION_ID >= 70100 ? 'assertNotSame' : 'assertSame', 'Y-m-d\TH:i:sP'],
+ ];
}
}
diff --git a/tests/Monolog/Processor/GitProcessorTest.php b/tests/Monolog/Processor/GitProcessorTest.php
index 5adb505..0059e6d 100644
--- a/tests/Monolog/Processor/GitProcessorTest.php
+++ b/tests/Monolog/Processor/GitProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Processor;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class GitProcessorTest extends TestCase
{
diff --git a/tests/Monolog/Processor/IntrospectionProcessorTest.php b/tests/Monolog/Processor/IntrospectionProcessorTest.php
index 0dd411d..5f5d9ae 100644
--- a/tests/Monolog/Processor/IntrospectionProcessorTest.php
+++ b/tests/Monolog/Processor/IntrospectionProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -27,7 +27,7 @@ function tester($handler, $record)
namespace Monolog\Processor;
use Monolog\Logger;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
use Monolog\Handler\TestHandler;
class IntrospectionProcessorTest extends TestCase
@@ -66,10 +66,10 @@ class IntrospectionProcessorTest extends TestCase
public function testLevelTooLow()
{
- $input = array(
+ $input = [
'level' => Logger::DEBUG,
- 'extra' => array(),
- );
+ 'extra' => [],
+ ];
$expected = $input;
@@ -81,18 +81,18 @@ class IntrospectionProcessorTest extends TestCase
public function testLevelEqual()
{
- $input = array(
+ $input = [
'level' => Logger::CRITICAL,
- 'extra' => array(),
- );
+ 'extra' => [],
+ ];
$expected = $input;
- $expected['extra'] = array(
+ $expected['extra'] = [
'file' => null,
'line' => null,
'class' => 'ReflectionMethod',
'function' => 'invokeArgs',
- );
+ ];
$processor = new IntrospectionProcessor(Logger::CRITICAL);
$actual = $processor($input);
@@ -102,18 +102,18 @@ class IntrospectionProcessorTest extends TestCase
public function testLevelHigher()
{
- $input = array(
+ $input = [
'level' => Logger::EMERGENCY,
- 'extra' => array(),
- );
+ 'extra' => [],
+ ];
$expected = $input;
- $expected['extra'] = array(
+ $expected['extra'] = [
'file' => null,
'line' => null,
'class' => 'ReflectionMethod',
'function' => 'invokeArgs',
- );
+ ];
$processor = new IntrospectionProcessor(Logger::CRITICAL);
$actual = $processor($input);
diff --git a/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php b/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php
index eb66614..cd80527 100644
--- a/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php
+++ b/tests/Monolog/Processor/MemoryPeakUsageProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Processor;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class MemoryPeakUsageProcessorTest extends TestCase
{
diff --git a/tests/Monolog/Processor/MemoryUsageProcessorTest.php b/tests/Monolog/Processor/MemoryUsageProcessorTest.php
index 4692dbf..a4809cb 100644
--- a/tests/Monolog/Processor/MemoryUsageProcessorTest.php
+++ b/tests/Monolog/Processor/MemoryUsageProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Processor;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class MemoryUsageProcessorTest extends TestCase
{
diff --git a/tests/Monolog/Processor/MercurialProcessorTest.php b/tests/Monolog/Processor/MercurialProcessorTest.php
index 11f2b35..9028e41 100644
--- a/tests/Monolog/Processor/MercurialProcessorTest.php
+++ b/tests/Monolog/Processor/MercurialProcessorTest.php
@@ -1,9 +1,9 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
- * (c) Jonathan A. Schweder <jonathanschweder@gmail.com>
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -11,7 +11,7 @@
namespace Monolog\Processor;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class MercurialProcessorTest extends TestCase
{
@@ -27,6 +27,7 @@ class MercurialProcessorTest extends TestCase
}
if ($result != 0) {
$this->markTestSkipped('hg is missing');
+
return;
}
diff --git a/tests/Monolog/Processor/ProcessIdProcessorTest.php b/tests/Monolog/Processor/ProcessIdProcessorTest.php
index 458d2a3..ec39e8e 100644
--- a/tests/Monolog/Processor/ProcessIdProcessorTest.php
+++ b/tests/Monolog/Processor/ProcessIdProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Processor;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class ProcessIdProcessorTest extends TestCase
{
diff --git a/tests/Monolog/Processor/PsrLogMessageProcessorTest.php b/tests/Monolog/Processor/PsrLogMessageProcessorTest.php
index 029a0c0..5071d89 100644
--- a/tests/Monolog/Processor/PsrLogMessageProcessorTest.php
+++ b/tests/Monolog/Processor/PsrLogMessageProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Processor;
-class PsrLogMessageProcessorTest extends \PHPUnit_Framework_TestCase
+class PsrLogMessageProcessorTest extends \PHPUnit\Framework\TestCase
{
/**
* @dataProvider getPairs
@@ -20,24 +20,41 @@ class PsrLogMessageProcessorTest extends \PHPUnit_Framework_TestCase
{
$proc = new PsrLogMessageProcessor;
- $message = $proc(array(
+ $message = $proc([
'message' => '{foo}',
- 'context' => array('foo' => $val),
- ));
+ 'context' => ['foo' => $val],
+ ]);
$this->assertEquals($expected, $message['message']);
}
+ public function testCustomDateFormat()
+ {
+ $format = "Y-m-d";
+ $date = new \DateTime();
+
+ $proc = new PsrLogMessageProcessor($format);
+
+ $message = $proc([
+ 'message' => '{foo}',
+ 'context' => ['foo' => $date],
+ ]);
+ $this->assertEquals($date->format($format), $message['message']);
+ }
+
public function getPairs()
{
- return array(
- array('foo', 'foo'),
- array('3', '3'),
- array(3, '3'),
- array(null, ''),
- array(true, '1'),
- array(false, ''),
- array(new \stdClass, '[object stdClass]'),
- array(array(), '[array]'),
- );
+ $date = new \DateTime();
+
+ return [
+ ['foo', 'foo'],
+ ['3', '3'],
+ [3, '3'],
+ [null, ''],
+ [true, '1'],
+ [false, ''],
+ [$date, $date->format(PsrLogMessageProcessor::SIMPLE_DATE)],
+ [new \stdClass, '[object stdClass]'],
+ [[], '[array]'],
+ ];
}
}
diff --git a/tests/Monolog/Processor/TagProcessorTest.php b/tests/Monolog/Processor/TagProcessorTest.php
index 0d860c6..da84378 100644
--- a/tests/Monolog/Processor/TagProcessorTest.php
+++ b/tests/Monolog/Processor/TagProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Processor;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class TagProcessorTest extends TestCase
{
@@ -20,7 +20,7 @@ class TagProcessorTest extends TestCase
*/
public function testProcessor()
{
- $tags = array(1, 2, 3);
+ $tags = [1, 2, 3];
$processor = new TagProcessor($tags);
$record = $processor($this->getRecord());
@@ -32,18 +32,18 @@ class TagProcessorTest extends TestCase
*/
public function testProcessorTagModification()
{
- $tags = array(1, 2, 3);
+ $tags = [1, 2, 3];
$processor = new TagProcessor($tags);
$record = $processor($this->getRecord());
$this->assertEquals($tags, $record['extra']['tags']);
- $processor->setTags(array('a', 'b'));
+ $processor->setTags(['a', 'b']);
$record = $processor($this->getRecord());
- $this->assertEquals(array('a', 'b'), $record['extra']['tags']);
+ $this->assertEquals(['a', 'b'], $record['extra']['tags']);
- $processor->addTags(array('a', 'c', 'foo' => 'bar'));
+ $processor->addTags(['a', 'c', 'foo' => 'bar']);
$record = $processor($this->getRecord());
- $this->assertEquals(array('a', 'b', 'a', 'c', 'foo' => 'bar'), $record['extra']['tags']);
+ $this->assertEquals(['a', 'b', 'a', 'c', 'foo' => 'bar'], $record['extra']['tags']);
}
}
diff --git a/tests/Monolog/Processor/UidProcessorTest.php b/tests/Monolog/Processor/UidProcessorTest.php
index 5d13058..927d564 100644
--- a/tests/Monolog/Processor/UidProcessorTest.php
+++ b/tests/Monolog/Processor/UidProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog\Processor;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class UidProcessorTest extends TestCase
{
diff --git a/tests/Monolog/Processor/WebProcessorTest.php b/tests/Monolog/Processor/WebProcessorTest.php
index 4105baf..6da6ab8 100644
--- a/tests/Monolog/Processor/WebProcessorTest.php
+++ b/tests/Monolog/Processor/WebProcessorTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,20 +11,20 @@
namespace Monolog\Processor;
-use Monolog\TestCase;
+use Monolog\Test\TestCase;
class WebProcessorTest extends TestCase
{
public function testProcessor()
{
- $server = array(
+ $server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'HTTP_REFERER' => 'D',
'SERVER_NAME' => 'F',
'UNIQUE_ID' => 'G',
- );
+ ];
$processor = new WebProcessor($server);
$record = $processor($this->getRecord());
@@ -38,10 +38,10 @@ class WebProcessorTest extends TestCase
public function testProcessorDoNothingIfNoRequestUri()
{
- $server = array(
+ $server = [
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
- );
+ ];
$processor = new WebProcessor($server);
$record = $processor($this->getRecord());
$this->assertEmpty($record['extra']);
@@ -49,12 +49,12 @@ class WebProcessorTest extends TestCase
public function testProcessorReturnNullIfNoHttpReferer()
{
- $server = array(
+ $server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'SERVER_NAME' => 'F',
- );
+ ];
$processor = new WebProcessor($server);
$record = $processor($this->getRecord());
$this->assertNull($record['extra']['referrer']);
@@ -62,12 +62,12 @@ class WebProcessorTest extends TestCase
public function testProcessorDoesNotAddUniqueIdIfNotPresent()
{
- $server = array(
+ $server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'SERVER_NAME' => 'F',
- );
+ ];
$processor = new WebProcessor($server);
$record = $processor($this->getRecord());
$this->assertFalse(isset($record['extra']['unique_id']));
@@ -75,32 +75,32 @@ class WebProcessorTest extends TestCase
public function testProcessorAddsOnlyRequestedExtraFields()
{
- $server = array(
+ $server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'SERVER_NAME' => 'F',
- );
+ ];
- $processor = new WebProcessor($server, array('url', 'http_method'));
+ $processor = new WebProcessor($server, ['url', 'http_method']);
$record = $processor($this->getRecord());
- $this->assertSame(array('url' => 'A', 'http_method' => 'C'), $record['extra']);
+ $this->assertSame(['url' => 'A', 'http_method' => 'C'], $record['extra']);
}
public function testProcessorConfiguringOfExtraFields()
{
- $server = array(
+ $server = [
'REQUEST_URI' => 'A',
'REMOTE_ADDR' => 'B',
'REQUEST_METHOD' => 'C',
'SERVER_NAME' => 'F',
- );
+ ];
- $processor = new WebProcessor($server, array('url' => 'REMOTE_ADDR'));
+ $processor = new WebProcessor($server, ['url' => 'REMOTE_ADDR']);
$record = $processor($this->getRecord());
- $this->assertSame(array('url' => 'B'), $record['extra']);
+ $this->assertSame(['url' => 'B'], $record['extra']);
}
/**
diff --git a/tests/Monolog/PsrLogCompatTest.php b/tests/Monolog/PsrLogCompatTest.php
index ab89944..a4bbcd0 100644
--- a/tests/Monolog/PsrLogCompatTest.php
+++ b/tests/Monolog/PsrLogCompatTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
diff --git a/tests/Monolog/RegistryTest.php b/tests/Monolog/RegistryTest.php
index 15fdfbd..7ee2cbd 100644
--- a/tests/Monolog/RegistryTest.php
+++ b/tests/Monolog/RegistryTest.php
@@ -1,4 +1,4 @@
-<?php
+<?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
@@ -11,7 +11,7 @@
namespace Monolog;
-class RegistryTest extends \PHPUnit_Framework_TestCase
+class RegistryTest extends \PHPUnit\Framework\TestCase
{
protected function setUp()
{
@@ -38,26 +38,26 @@ class RegistryTest extends \PHPUnit_Framework_TestCase
$logger2 = new Logger('test2');
$logger3 = new Logger('test3');
- return array(
+ return [
// only instances
- array(
- array($logger1),
- array($logger1, $logger2),
- array(true, false),
- ),
+ [
+ [$logger1],
+ [$logger1, $logger2],
+ [true, false],
+ ],
// only names
- array(
- array($logger1),
- array('test1', 'test2'),
- array(true, false),
- ),
+ [
+ [$logger1],
+ ['test1', 'test2'],
+ [true, false],
+ ],
// mixed case
- array(
- array($logger1, $logger2),
- array('test1', $logger2, 'test3', $logger3),
- array(true, true, false, false),
- ),
- );
+ [
+ [$logger1, $logger2],
+ ['test1', $logger2, 'test3', $logger3],
+ [true, true, false, false],
+ ],
+ ];
}
/**
@@ -68,7 +68,7 @@ class RegistryTest extends \PHPUnit_Framework_TestCase
Registry::addLogger(new Logger('test1'), 'log');
Registry::clear();
- $this->setExpectedException('\InvalidArgumentException');
+ $this->expectException('\InvalidArgumentException');
Registry::getInstance('log');
}
@@ -82,7 +82,7 @@ class RegistryTest extends \PHPUnit_Framework_TestCase
Registry::addLogger($loggerToAdd);
Registry::removeLogger($remove);
- $this->setExpectedException('\InvalidArgumentException');
+ $this->expectException('\InvalidArgumentException');
Registry::getInstance($loggerToAdd->getName());
}
@@ -90,10 +90,10 @@ class RegistryTest extends \PHPUnit_Framework_TestCase
{
$logger1 = new Logger('test1');
- return array(
- array($logger1, $logger1),
- array($logger1, 'test1'),
- );
+ return [
+ [$logger1, $logger1],
+ [$logger1, 'test1'],
+ ];
}
/**
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
new file mode 100644
index 0000000..d475dd3
--- /dev/null
+++ b/tests/bootstrap.php
@@ -0,0 +1,14 @@
+<?php declare(strict_types=1);
+
+/*
+ * This file is part of the Monolog package.
+ *
+ * (c) Jordi Boggiano <j.boggiano@seld.be>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+date_default_timezone_set('UTC');
+
+require __DIR__.'/../vendor/autoload.php';