From 230eb731be7a01cf0ed244ea2ed5867b40482937 Mon Sep 17 00:00:00 2001 From: bidi Date: Mon, 16 Nov 2026 14:47:32 +0200 Subject: [PATCH] code refactor, updated composer, docs, workflow, tests Signed-off-by: bidi --- .github/workflows/codecov.yml | 8 +- .github/workflows/static-analysis.yml | 12 +- .gitignore | 1 + .laminas-ci.json | 3 + CHANGELOG.md | 796 +++++++++++++++++- README.md | 254 +----- SECURITY.md | 9 +- composer.json | 16 +- docs/book/v5/upgrading.md | 18 + docs/book/v6/adding-config-provider.md | 81 ++ docs/book/v6/configuring-writer.md | 62 ++ docs/book/v6/example-with-formatter.md | 48 ++ docs/book/v6/filtering-log-messages.md | 111 +++ docs/book/v6/formatting-messages.md | 55 ++ docs/book/v6/grouping-log-files-by-date.md | 22 + docs/book/v6/overview.md | 31 + docs/book/v6/registering-custom-plugins.md | 92 ++ docs/book/v6/upgrading.md | 89 ++ docs/book/v6/usage.md | 98 +++ log.global.php.dist | 52 +- mkdocs.yml | 29 +- phpstan.neon | 6 +- phpunit.xml | 13 +- src/ConfigProvider.php | 50 +- src/Exception/ServiceNotFoundException.php | 11 + src/Factory/FilterPluginManagerFactory.php | 27 +- src/Factory/FormatterPluginManagerFactory.php | 27 +- src/Factory/LoggerAbstractServiceFactory.php | 130 --- src/Factory/LoggerFactory.php | 101 +++ src/Factory/ProcessorPluginManagerFactory.php | 27 +- src/Factory/WriterFactory.php | 42 +- src/Factory/WriterPluginManagerFactory.php | 27 +- src/Filter/Callback.php | 52 ++ src/Filter/FilterInterface.php | 4 +- src/Filter/Level.php | 38 +- src/Filter/Regex.php | 26 +- src/Filter/SuppressFilter.php | 4 + src/Filter/Validator.php | 54 +- src/Formatter/AbstractFormatter.php | 129 +++ src/Formatter/Base.php | 127 --- src/Formatter/FormatterInterface.php | 11 +- src/Formatter/Json.php | 42 +- src/Formatter/Simple.php | 27 +- src/Logger.php | 331 +++++--- src/LoggerServiceFactory.php | 158 +++- src/Manager/AbstractPluginManager.php | 195 +++++ src/Manager/FilterPluginManager.php | 45 +- src/Manager/FormatterPluginManager.php | 42 +- src/Manager/ProcessorPluginManager.php | 43 +- src/Manager/WriterPluginManager.php | 49 +- src/Processor/Backtrace.php | 35 +- src/Processor/ProcessorInterface.php | 3 + src/Processor/PsrPlaceholder.php | 31 +- src/Processor/ReferenceId.php | 7 +- src/Processor/RequestId.php | 21 +- src/Writer/AbstractWriter.php | 193 ++--- src/Writer/Noop.php | 2 + src/Writer/Stream.php | 110 ++- src/Writer/WriterInterface.php | 2 + test/ConfigProviderTest.php | 54 +- .../FilterPluginManagerFactoryTest.php | 101 --- .../FormatterPluginManagerFactoryTest.php | 101 --- .../LoggerAbstractServiceFactoryTest.php | 77 -- test/Factory/LoggerFactoryTest.php | 232 +++++ test/Factory/PluginManagerFactoryTest.php | 122 +++ .../ProcessorPluginManagerFactoryTest.php | 101 --- test/Factory/WriterFactoryTest.php | 66 +- .../WriterPluginManagerFactoryTest.php | 101 --- test/Filter/CallbackTest.php | 36 + test/Filter/LevelTest.php | 89 +- test/Filter/RegexTest.php | 76 +- test/Filter/SuppressFilterTest.php | 35 +- test/Filter/ValidatorTest.php | 74 +- test/Fixture/ContainerException.php | 12 + test/Fixture/InMemoryContainer.php | 60 ++ test/{Mock.php => Fixture/MemoryWriter.php} | 19 +- test/Fixture/NotEmptyValidator.php | 21 + test/Fixture/NotFoundException.php | 12 + .../RecordingFilter.php} | 13 +- test/Formatter/AbstractFormatterTest.php | 83 ++ test/Formatter/BaseTest.php | 43 - test/Formatter/JsonTest.php | 50 +- test/Formatter/SimpleTest.php | 61 +- test/LoggerServiceFactoryTest.php | 236 ++---- test/LoggerTest.php | 603 +++++++------ test/Manager/FilterPluginManagerTest.php | 43 - test/Manager/FormatterPluginManagerTest.php | 43 - test/Manager/PluginManagerTest.php | 243 ++++++ test/Manager/ProcessorPluginManagerTest.php | 43 - test/Manager/WriterPluginManagerTest.php | 43 - test/Processor/BackTraceTest.php | 38 +- test/Processor/PsrPlaceholderTest.php | 40 +- test/Processor/ReferenceIdTest.php | 38 +- test/Processor/RequestIdTest.php | 31 +- test/Writer/AbstractWriterTest.php | 189 +++++ test/Writer/StreamTest.php | 251 ++++-- 96 files changed, 5014 insertions(+), 2595 deletions(-) create mode 100644 docs/book/v5/upgrading.md create mode 100644 docs/book/v6/adding-config-provider.md create mode 100644 docs/book/v6/configuring-writer.md create mode 100644 docs/book/v6/example-with-formatter.md create mode 100644 docs/book/v6/filtering-log-messages.md create mode 100644 docs/book/v6/formatting-messages.md create mode 100644 docs/book/v6/grouping-log-files-by-date.md create mode 100644 docs/book/v6/overview.md create mode 100644 docs/book/v6/registering-custom-plugins.md create mode 100644 docs/book/v6/upgrading.md create mode 100644 docs/book/v6/usage.md create mode 100644 src/Exception/ServiceNotFoundException.php delete mode 100644 src/Factory/LoggerAbstractServiceFactory.php create mode 100644 src/Factory/LoggerFactory.php create mode 100644 src/Filter/Callback.php create mode 100644 src/Formatter/AbstractFormatter.php delete mode 100644 src/Formatter/Base.php create mode 100644 src/Manager/AbstractPluginManager.php delete mode 100644 test/Factory/FilterPluginManagerFactoryTest.php delete mode 100644 test/Factory/FormatterPluginManagerFactoryTest.php delete mode 100644 test/Factory/LoggerAbstractServiceFactoryTest.php create mode 100644 test/Factory/LoggerFactoryTest.php create mode 100644 test/Factory/PluginManagerFactoryTest.php delete mode 100644 test/Factory/ProcessorPluginManagerFactoryTest.php delete mode 100644 test/Factory/WriterPluginManagerFactoryTest.php create mode 100644 test/Filter/CallbackTest.php create mode 100644 test/Fixture/ContainerException.php create mode 100644 test/Fixture/InMemoryContainer.php rename test/{Mock.php => Fixture/MemoryWriter.php} (60%) create mode 100644 test/Fixture/NotEmptyValidator.php create mode 100644 test/Fixture/NotFoundException.php rename test/{MockFilter.php => Fixture/RecordingFilter.php} (52%) create mode 100644 test/Formatter/AbstractFormatterTest.php delete mode 100644 test/Formatter/BaseTest.php delete mode 100644 test/Manager/FilterPluginManagerTest.php delete mode 100644 test/Manager/FormatterPluginManagerTest.php create mode 100644 test/Manager/PluginManagerTest.php delete mode 100644 test/Manager/ProcessorPluginManagerTest.php delete mode 100644 test/Manager/WriterPluginManagerTest.php create mode 100644 test/Writer/AbstractWriterTest.php diff --git a/.github/workflows/codecov.yml b/.github/workflows/codecov.yml index c0fbc53..9652006 100644 --- a/.github/workflows/codecov.yml +++ b/.github/workflows/codecov.yml @@ -15,14 +15,14 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v3 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -50,6 +50,6 @@ jobs: run: vendor/bin/phpunit --colors=always --coverage-clover clover.xml - name: Send code coverage report to Codecov.io - uses: codecov/codecov-action@v3 + uses: codecov/codecov-action@v7 with: token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index 9976515..19ccd72 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -4,7 +4,7 @@ on: name: Run PHPStan checks jobs: - mutation: + static-analysis: name: PHPStan ${{ matrix.php }}-${{ matrix.os }} runs-on: ${{ matrix.os }} @@ -15,20 +15,20 @@ jobs: - ubuntu-latest php: - - "8.2" - "8.3" - "8.4" - "8.5" + - "8.6" steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install PHP uses: shivammathur/setup-php@v2 with: php-version: "${{ matrix.php }}" - coverage: pcov + coverage: none ini-values: assert.exception=1, zend.assertions=1, error_reporting=-1, log_errors_max_len=0, display_errors=On tools: composer:v2, cs2pr @@ -36,7 +36,7 @@ jobs: run: echo "COMPOSER_CACHE_DIR=$(composer config cache-dir)" >> $GITHUB_ENV - name: Cache dependencies installed with composer - uses: actions/cache@v4 + uses: actions/cache@v6 with: path: ${{ env.COMPOSER_CACHE_DIR }} key: php${{ matrix.php }}-composer-${{ hashFiles('**/composer.json') }} @@ -47,4 +47,4 @@ jobs: run: composer install --prefer-dist --no-interaction --no-progress --optimize-autoloader --ansi - name: Run static analysis with PHPStan - run: vendor/bin/phpstan analyse + run: composer static-analysis diff --git a/.gitignore b/.gitignore index 4d3fdcb..3e62087 100644 --- a/.gitignore +++ b/.gitignore @@ -38,3 +38,4 @@ composer.phar # Commit your application's lock file http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file # You may choose to ignore a library lock file http://getcomposer.org/doc/02-libraries.md#lock-file composer.lock +.phpunit.cache diff --git a/.laminas-ci.json b/.laminas-ci.json index 29216fa..e827682 100644 --- a/.laminas-ci.json +++ b/.laminas-ci.json @@ -1,3 +1,6 @@ { + "ignore_php_platform_requirements": { + "8.6": true + }, "backwardCompatibilityCheck": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index a7cef86..5b8d826 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,166 +1,952 @@ +# Changelog + +All notable changes to `dotkernel/dot-log` are documented in this file. + +## 6.0.0 - TBD + +### Changed + +* PHPUnit 12 and PHPStan level 8, with no ignored errors +* The plugin managers no longer extend `Laminas\ServiceManager\AbstractPluginManager`; they extend `Dot\Log\Manager\AbstractPluginManager` and work with any PSR-11 container +* `Dot\Log\ConfigProvider` returns an empty array: register `Dot\Log\Factory\LoggerFactory` for each `dot-log.` logger +* The factories are plain classes with `Psr\Container` imports only +* `laminas/laminas-validator` is no longer required, not even for development; it is listed under `suggest`. `laminas/laminas-stdlib` and `psr/container` are declared +* The `Validator` filter accepts any object with an `isValid()` method instead of only `Laminas\Validator\ValidatorInterface` +* `FormatterInterface::format()` takes `array` and returns `string`; `FilterInterface::filter()` returns `bool` +* `Dot\Log\Formatter\Base` renamed to `AbstractFormatter`; `normalizeEvent()` replaces its array-returning `format()` +* The event `timestamp` is a `DateTimeImmutable` +* Placeholders: `Stringable` values are cast to string, dates use RFC 3339, booleans become `true`/`false`, other values become `[object Class]` or `[type]` +* The `Json` formatter no longer converts numeric strings to numbers (`JSON_NUMERIC_CHECK` removed) and substitutes invalid UTF-8 +* The `Level` filter compares integers and validates its operator; the `Regex` filter validates its pattern before use +* Plugin managers throw `Dot\Log\Exception\InvalidArgumentException` and `Dot\Log\Exception\ServiceNotFoundException` + +### Added + +* PHP 8.6 support +* `Dot\Log\Factory\LoggerFactory` +* `json` formatter alias and `callback` filter +* `priority` as an alias of the writer and processor `level` key +* `Logger::createErrorHandler()`, `Logger::createExceptionHandler()` and `Logger::placeholderValue()` +* `Stream::getOldLogsPattern()` +* `provide: psr/log-implementation` +* Upgrade guides for 4.x to 5.x and 5.x to 6.x, and a page on registering custom plugins + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.2 support +* The `laminas/laminas-servicemanager` requirement, including the development requirement +* `Dot\Log\Factory\LoggerAbstractServiceFactory` +* `Dot\Log\Formatter\Base` + +### Fixed + +* Custom plugins configured under `dot_log.*_manager` were ignored +* Omitting the documented-as-optional writer or processor `level` threw a `TypeError` +* A `Stream` writer without a formatter crashed on the first write +* Formatter options were ignored when the formatter was given by class name +* The `simple` formatter wrote a literal `%extra%` for events from the logger +* The error handler logged the log level as `errno` instead of the PHP error number +* The `Backtrace` processor reported `Dot\Log\Logger::log` instead of the caller +* `DateTimeImmutable` values were not formatted +* The `Regex` filter and `AbstractWriter::write()` could leave an error handler active +* Logger options given as a generator were ignored +* Destroying a logger emptied the queue returned by `getWriters()` +* The log clean-up pattern could match, and delete, unrelated files in the log directory +* The documented writer configuration (`'name' => 'FileWriter'`) and `log.global.php.dist` did not work + +## 5.3.1 - 2026-07-31 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* File permission issues (#94) + +## 4.1.4 - 2026-07-31 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* File permission issues (#93) + +## 4.0.6 - 2026-07-31 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* File permission issues (#92) + +## 5.3.0 - 2025-10-29 + +### Changed + +* Nothing + +### Added + +* PHP 8.4 and 8.5 support (#84) + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.1 support (#84) + +### Fixed + +* Nothing + +## 4.1.3 - 2025-10-29 + +### Changed + +* Nothing + +### Added + +* PHP 8.4 and 8.5 support (#83) + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.1 support (#83) + +### Fixed + +* Nothing + +## 4.0.5 - 2025-10-29 + +### Changed + +* Nothing + +### Added + +* PHP 8.4 and 8.5 support (#82) + +### Deprecated + +* Nothing + +### Removed + +* PHP 8.1 support (#82) + +### Fixed + +* Nothing + +## 5.2.0 - 2025-10-14 + +### Changed + +* Nothing + +### Added + +* Automatic deletion of log files with the `log_lifetime` writer option (#80) + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 5.1.0 - 2025-02-24 + +### Changed + +* Replaced Psalm with PHPStan (#75) +* Replaced `Dot\Log\Exception\InvalidArgumentException` (#77) + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 5.0.0 - 2025-02-14 + +### Changed + +* Implemented PSR-3 (#68) + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.1.2 - 2025-02-14 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Wrong link in README.md (#70) +* Wrong text in the documentation (#71) +* Updated SECURITY.md (#72) + +## 3.5.4 - 2025-02-14 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Wrong link in README.md (#70) +* Updated SECURITY.md (#72) + +## 4.1.1 - 2025-01-28 + +### Changed + +* Psalm 6 (#65) + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.1.0 - 2025-01-17 + +### Changed + +* Nothing + +### Added + +* `laminas/laminas-servicemanager` 4 support (#44) + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.0.4 - 2024-09-13 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* `docs/book/index.md` symlink (#60) + +## 4.0.3 - 2024-09-13 + +### Changed + +* Nothing + +### Added + +* Unit tests + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.0.2 - 2024-08-30 + +### Changed + +* Updated README.md + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Accessing resources before initialization + +## 4.0.1 - 2024-08-29 + +### Changed + +* Updated `log.global.php.dist` + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 4.0.0 - 2024-08-29 + +### Changed + +* Updated README.md + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* The `laminas/laminas-log` dependency + +### Fixed + +* Nothing + +## 3.5.3 - 2024-06-30 + +### Changed + +* Marked the package as a wrapper in the documentation + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.2 - 2024-06-28 + +### Changed + +* Marked the package as a wrapper + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.1 - 2024-05-22 + +### Changed + +* Updated the documentation + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.5.0 - 2024-05-03 + +### Changed + +* Updated README.md + +### Added + +* Documentation (#40) + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + ## 3.4.7 - 2024-02-28 ### Changed + * laminas/laminas-servicemanager dependency update from 3.10.0 to 3.22 ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ## 3.4.6 - 2024-02-28 ### Changed + * laminas/laminas-log dependency update from 2.16 to 2.17 (introduced PHP 8.3 support) ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ## 3.4.5 - 2024-02-27 ### Changed + * dot-mail dependency update from 4.0 to 4.1 (introduced PHP 8.3 support) ### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +## 3.4.4 - 2023-12-06 + +### Changed + +* Updated README.md + +### Added + +* PHP 8.3 support + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.3 - 2023-08-29 + +### Changed + +* Nothing + +### Added + +* Codecov workflow and badge + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.2 - 2023-08-11 + +### Changed + +* Renamed `static-analisys.yml` to `static-analysis.yml` + +### Added + +* Static analysis badge (#24) + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.4.1 - 2023-07-25 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Compatibility with newer `laminas/laminas-log` versions + +## 3.4.0 - 2023-07-19 + +### Changed + +* Code quality improvements (#20) + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.3.0 - 2023-03-29 + +### Changed + +* Nothing + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* `laminas/laminas-dependency-plugin` + +### Fixed + +* Nothing + +## 3.2.1 - 2022-10-27 + +### Changed + +* Set `laminas/laminas-log` to the fixed version 2.15.2 + +### Added + +* Nothing + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.2.0 - 2022-03-22 + +### Changed + +* Updated the PHP version constraint to allow 8.0 and 8.1 + +### Added + +* PHP 8.0 and 8.1 compatibility + +### Deprecated + +* Nothing + +### Removed + +* Nothing + +### Fixed + +* Nothing + +## 3.1.1 - 2021-04-26 + +### Changed + * Nothing +### Added + +* Date-based variables in the stream writer's `stream` option + ### Deprecated + * Nothing ### Removed + +* Nothing + +### Fixed + * Nothing ## 3.1.0 - 2020-11-03 ### Changed + * Composer 2 compatibility. * Update composer.json to require version 2 of laminas/laminas-dependency-plugin to be Composer 2 compatible. ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed + * bump min version of laminas/laminas-dependency-plugin ## 2.0.0 - 2020-01-30 ### Changed + * Laminas and Mezzio migration. ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Support ### Fixed -* Nothing +* Nothing ## 1.1.2 - 2018-11-13 ### Changed + * nothing ### Added + * usage documentation ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 1.1.1 - 2018-05-04 ### Changed + * dependencies updates * using `dotkernel/dot-mail:^1.0` ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 1.1.0 - 2017-03-16 ### Changed + * updates to PSR11 container where possible * dependencies updates ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 1.0.1 - 2017-03-11 Updated php file headers doc blocks ### Added + * Nothing ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed -* Nothing +* Nothing ## 1.0.0 - 2017-03-09 Initial tagged release ### Added + * Everything ### Deprecated + * Nothing ### Removed + * Nothing ### Fixed + * Nothing diff --git a/README.md b/README.md index a35fbca..6dbe7b2 100644 --- a/README.md +++ b/README.md @@ -1,241 +1,68 @@ # dot-log -Robust, composite PSR-3 compliant logger with filtering and formatting. +Robust, composite PSR-3 compliant logger with filtering and formatting, usable with any PSR-11 container. ## Version History -| Branch | Service Manager | Log style implementation | PHP Version | -|--------|-------------------|--------------------------|---------------------------------------------------------------------------------------------------------| -| 5.0 | Service Manager 4 | PSR-Log | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/5.3.0) | -| 4.1 | Service Manager 4 | Laminas Log style | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/4.1.3) | -| 4.0 | Service Manager 3 | Laminas Log style | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/4.0.5) | -| 3.0 | Service Manager 3 | Laminas Log | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/3.5.4) | +| Branch | Container | Log style implementation | PHP Version | +|--------|----------------------|--------------------------|---------------------------------------------------------------------------------------------------------| +| 6.0 | Any PSR-11 container | PSR-Log | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/6.0.0) | +| 5.0 | Service Manager 4 | PSR-Log | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/5.3.1) | +| 4.1 | Service Manager 4 | Laminas Log style | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/4.1.4) | +| 4.0 | Service Manager 3 | Laminas Log style | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/4.0.6) | +| 3.0 | Service Manager 3 | Laminas Log | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/3.5.4) | ## Documentation Documentation is available at: https://docs.dotkernel.org/dot-log/. +Upgrading from 5.x? Read the [6.x upgrade guide](https://docs.dotkernel.org/dot-log/v6/upgrading/). + ## Badges ![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-log) -![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/5.3.0) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/6.0.0) [![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/issues) [![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/network) [![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/stargazers) -[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/blob/5.0/LICENSE.md) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/blob/6.0/LICENSE.md) -[![Build Static](https://github.com/dotkernel/dot-log/actions/workflows/continuous-integration.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-log/actions/workflows/continuous-integration.yml) +[![Build Static](https://github.com/dotkernel/dot-log/actions/workflows/continuous-integration.yml/badge.svg?branch=6.0)](https://github.com/dotkernel/dot-log/actions/workflows/continuous-integration.yml) [![codecov](https://codecov.io/gh/dotkernel/dot-log/graph/badge.svg?token=JX19KTBRCZ)](https://codecov.io/gh/dotkernel/dot-log) -[![PHPStan](https://github.com/dotkernel/dot-log/actions/workflows/static-analysis.yml/badge.svg?branch=5.0)](https://github.com/dotkernel/dot-log/actions/workflows/static-analysis.yml) - -## Adding The Config Provider - -* Enter config/config.php -* If there is no entry for the config provider below, add it: -`\Dot\Log\ConfigProvider::class` -* Make sure it is added before with the Application-Specific components, e.g.: `\Frontend\App\ConfigProvider.php`, `\Admin\App\ConfigProvider::class`, `MyProject\ConfigProvider::class` , etc. -* Open the `Dot\Log\ConfigProvider` -* In the dependencies section you will see an abstract factory (`LoggerAbstractServiceFactory::class`) -* This class responds to "selectors" instead of class names - Instead of requesting the `Dot\Log\Logger::class` from the container, `dot-log.my_logger` should be requested - -## Configuring the writer(s) - -Loggers must have at least one writer. +[![PHPStan](https://github.com/dotkernel/dot-log/actions/workflows/static-analysis.yml/badge.svg?branch=6.0)](https://github.com/dotkernel/dot-log/actions/workflows/static-analysis.yml) -A writer is an object that inherits from `Dot\Log\Writer\AbstractWriter`. A writer's responsibility is to record log data to a storage backend. +## Installation -### Writing to a file (stream) - -It is possible to separate logs into multiple files using writers and filters. -For example, *warnings.log*, *errors.log*, *all_messages.log*. - -The following is the simplest example to write all log messages to `/log/dk.log` - -```php -return [ - 'dot_log' => [ - 'loggers' => [ - 'my_logger' => [ - 'writers' => [ - 'FileWriter' => [ - 'name' => 'FileWriter', - 'level' => \Dot\Log\Logger::ALERT, // this is equal to 1 - 'options' => [ - 'stream' => __DIR__ . '/../../log/dk.log', - ], - ], - ], - ] - ], - ], -]; +```shell +composer require dotkernel/dot-log ``` -* The `FileWriter` key is optional, otherwise the writers array would be enumerative instead of associative. -* The writer name key is a developer-provided name for that writer, the writer name key is **mandatory**. - -The writer level key is not affecting the errors that are written; it is a way to organize writers. - -The writer level key is optional. - -To write into a file, the key stream must be present in the writer options array. This is required only if writing into streams/files. - -## Grouping log files by date - -By default, logs will be written to the same file: `log/dk.log`. -Optionally, you can use date format specifiers wrapped between curly braces in your FileWriter's `stream` option, automatically grouping your logs by day, week, month, year, etc. -Examples: - -* `log/dk-{Y}-{m}-{d}.log` will write every day to a different file (eg: `log/dk-2021-01-01.log`) -* `log/dk-{Y}-{W}.log` will write every week to a different file (eg: `log/dk-2021-10.log`) - -The full list of format specifiers is available in the [official documentation](https://www.php.net/manual/en/datetime.format.php). - -## Filtering log messages - -As per PSR-3 document. +## Quick start -The log levels are: emergency (0), alert (1), critical (2), error (3), warn (4), notice (5), info (6), debug (7) (in order of level/importance) - -The following example has three file writers using filters: - -* First Example: `FileWriter` - All messages are logged in `/log/dk.log` -* Second Example: `OnlyWarningsWriter` - Only warnings are logged in `/log/warnings.log` -* Third Example: `WarningOrHigherWriter` - All important messages (`warnings` or more critical) are logged in `/log/important_messages.log` +Register a factory for each logger, and configure it under `dot_log.loggers`, for example in `config/autoload/logger.global.php`: ```php [ - 'loggers' => [ - 'my_logger' => [ - 'writers' => [ - 'FileWriter' => [ - 'name' => 'FileWriter', - 'level' => \Dot\Log\Logger::ALERT, - 'options' => [ - 'stream' => __DIR__ . '/../../log/dk.log', - 'filters' => [ - 'allMessages' => [ - 'name' => 'level', - 'options' => [ - 'operator' => '>=', - 'level' => \Dot\Log\Logger::EMERG, - ] - ], - ], - ], - ], - // Only warnings - 'OnlyWarningsWriter' => [ - 'name' => 'stream', - 'level' => \Dot\Log\Logger::ALERT, - 'options' => [ - 'stream' => __DIR__ . '/../../log/warnings_only.log', - 'filters' => [ - 'warningOnly' => [ - 'name' => 'level', - 'options' => [ - 'operator' => '==', - 'level' => \Dot\Log\Logger::WARN, - ], - ], - ], - ], - ], - // Warnings and more important messages - 'WarningOrHigherWriter' => [ - 'name' => 'stream', - 'level' => \Dot\Log\Logger::ALERT, - 'options' => [ - 'stream' => __DIR__ . '/../../log/important_messages.log', - 'filters' => [ - 'importantMessages' => [ - 'name' => 'level', - 'options' => [ - // note, the smaller the level, the more important the message - // 0 - emergency, 1 - alert, 2- error, 3 - warn. .etc - 'operator' => '<=', - 'level' => \Dot\Log\Logger::WARN, - ], - ], - ], - ], - ], - ], - ], + 'dependencies' => [ + 'factories' => [ + 'dot-log.my_logger' => \Dot\Log\Factory\LoggerFactory::class, ], ], -]; -``` - -As in the writer configuration, the developer can optionally use keys for associating the filters with a name. - -IMPORTANT NOTE: the operator for more important messages is `<=`, this is because the number representation is smaller for a more important message type. - -The filter added on the first writer is equal to not setting a filter, but it has been added to illustrate how to explicitly allow all messages. - -It was added opposite to the others just to demonstrate the other operator is also an option. - -## Formatting Messages - -When using `dot-log`, the logged value is not limited to a string. Arrays can be logged as well. - -For better readability, these arrays can be serialized. - -Dot Log provides String formatting and JSON formatting. - -The formatter accepts the following parameters: - -* `name`: the formatter class (it must implement `Dot\Log\Formatter\FormatterInterface`) -* `options`: options to pass to the formatter constructor if required - -The following formats the message as JSON data: - -```php -'formatter' => [ - 'name' => \Dot\Log\Formatter\Json::class, -], -``` - -### Example with formatter - -* The log is used through dot-log -* The logger name is my_logger -* Writes to file: log/dk.log -* Explicitly allows all the messages to be written -* Formats the messages as JSON - -```php - [ + 'dot_log' => [ 'loggers' => [ 'my_logger' => [ 'writers' => [ 'FileWriter' => [ - 'name' => 'FileWriter', - 'level' => \Dot\Log\Logger::ALERT, + // the writer plugin: "stream", "noop" or a class name + 'name' => 'stream', 'options' => [ - 'stream' => __DIR__ . '/../../log/dk.log', - // explicitly log all messages - 'filters' => [ - 'allMessages' => [ - 'name' => 'level', - 'options' => [ - 'operator' => '>=', - 'level' => \Dot\Log\Logger::EMERG, - ], - ], - ], - 'formatter' => [ - 'name' => \Dot\Log\Formatter\Json::class, - ], + 'stream' => __DIR__ . '/../../log/dk-{Y}-{m}-{d}.log', + 'formatter' => ['name' => 'json'], ], ], ], @@ -245,23 +72,16 @@ return [ ]; ``` -## Usage - -Basic usage of the logger is illustrated below. - -The messages are written to see which logs are written and which are not written. +Then fetch the logger from the container and use it as any PSR-3 logger: ```php -/** @var \Dot\Log\Logger $logger */ +/** @var \Psr\Log\LoggerInterface $logger */ $logger = $container->get('dot-log.my_logger'); -$logger->emergency('0 EMERG'); -$logger->alert('1 ALERT'); -$logger->critical('2 CRITICAL'); -$logger->error('3 ERR'); -$logger->warning('4 WARN'); -$logger->notice('5 NOTICE'); -$logger->info('6 INF'); -$logger->debug('7 debug'); -$logger->log(Logger::NOTICE, 'NOTICE from log()'); +$logger->warning('User {id} failed to log in', ['id' => 7]); ``` + +The factories work with any PSR-11 container that passes the requested service name to the factory, for example Laminas Service Manager. +The `dot-log` package does not require `laminas/laminas-servicemanager`. + +See the documentation for writers, filters, formatters, processors and custom plugins. diff --git a/SECURITY.md b/SECURITY.md index d176f87..acb824c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,14 +2,13 @@ ## Supported Versions - | Version | Supported | PHP Version | |---------|--------------------|---------------------------------------------------------------------------------------------------------| -| 5.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/5.3.0) | -| 4.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/4.1.3) | +| 6.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/6.0.0) | +| 5.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/5.3.1) | +| 4.x | :white_check_mark: | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/4.1.4) | | <= 3.x | :x: | | - ## Reporting Potential Security Issues If you have encountered a potential security vulnerability in this project, @@ -28,7 +27,6 @@ release prior to any public exposure; this helps protect the project's users, and provides them with a chance to upgrade and/or update in order to protect their applications. - ## Policy If we verify a reported security vulnerability, our policy is: @@ -38,4 +36,3 @@ If we verify a reported security vulnerability, our policy is: - After patching the release branches, we will immediately issue new security fix releases for each patched release branch. - diff --git a/composer.json b/composer.json index 402ecf5..ebf7347 100644 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "dotkernel/dot-log", "type": "library", - "description": "Dotkernel log component implementing PSR-3", + "description": "Dotkernel PSR-3 logger with writers, filters, formatters and processors, usable with any PSR-11 container", "license": "MIT", "homepage": "https://github.com/dotkernel/dot-log", "keywords": [ @@ -17,9 +17,9 @@ } ], "require": { - "php": "~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0", - "laminas/laminas-servicemanager": "^4.0", - "laminas/laminas-validator": "^3.0", + "php": "~8.3.0 || ~8.4.0 || ~8.5.0 || ~8.6.0", + "laminas/laminas-stdlib": "^3.19", + "psr/container": "^1.1 || ^2.0", "psr/log": "^3.0.2" }, "require-dev": { @@ -27,7 +27,13 @@ "laminas/laminas-coding-standard": "^3.0", "phpstan/phpstan": "^2.1", "phpstan/phpstan-phpunit": "^2.0", - "phpunit/phpunit": "^10.2" + "phpunit/phpunit": "^12.5" + }, + "provide": { + "psr/log-implementation": "3.0.0" + }, + "suggest": { + "laminas/laminas-validator": "To use Laminas validators with the Dot\\Log\\Filter\\Validator filter" }, "autoload": { "psr-4": { diff --git a/docs/book/v5/upgrading.md b/docs/book/v5/upgrading.md new file mode 100644 index 0000000..17e605c --- /dev/null +++ b/docs/book/v5/upgrading.md @@ -0,0 +1,18 @@ +# Upgrading from 4.x to 5.x + +Version 5 replaced the Laminas-Log-style API of version 4 with PSR-3. +The configuration format and the `dot-log.` services stay the same, apart from the renamed keys below. + +## Changes that can break code + +| Change | Symptom | Fix | +| --- | --- | --- | +| `Logger` implements `Psr\Log\LoggerInterface` instead of `Dot\Log\LoggerInterface` | Type errors where `Dot\Log\LoggerInterface` is expected | Type-hint `Psr\Log\LoggerInterface` | +| `emerg()`, `crit()`, `err()` and `warn()` removed | Call to undefined method | Use `emergency()`, `critical()`, `error()` and `warning()` | +| `log(int $priority, mixed $message, iterable $extra)` became `log($level, string\|Stringable $message, iterable $context)` and returns `void` | Chained calls such as `$logger->info('a')->info('b')` fail | Call the methods separately. Pass extra data as `$context` | +| Writer config key `priority` renamed to `level` | The key is ignored | Rename `priority` to `level` | +| Event keys `priority`, `priorityName` and `extra` renamed to `level`, `levelName` and `context` | Custom formatters, filters or processors read missing keys; a custom `Simple` format prints `%priority%` literally | Use the new keys, for example `%timestamp% %levelName% (%level%): %message%` | +| The `priority` filter (`Dot\Log\Filter\Priority`) replaced by `level` (`Dot\Log\Filter\Level`) | Plugin `priority` not found | Use `'name' => 'level'` with the options `level` and `operator` | +| Placeholders such as `{user}` are interpolated from the context | Messages containing braces change | Escape or rename the placeholders | + +Version 6 makes further changes, see the [6.x upgrade guide](../v6/upgrading.md). diff --git a/docs/book/v6/adding-config-provider.md b/docs/book/v6/adding-config-provider.md new file mode 100644 index 0000000..014b823 --- /dev/null +++ b/docs/book/v6/adding-config-provider.md @@ -0,0 +1,81 @@ +# Registering Loggers + +Each logger is a container service named `dot-log.`, created by `Dot\Log\Factory\LoggerFactory` from the configuration under `dot_log.loggers.`. + +Register one factory entry per logger, for example in `config/autoload/logger.global.php`: + +```php + [ + 'factories' => [ + 'dot-log.my_logger' => \Dot\Log\Factory\LoggerFactory::class, + ], + ], + 'dot_log' => [ + 'loggers' => [ + 'my_logger' => [ + 'writers' => [ + 'FileWriter' => [ + 'name' => 'stream', + 'options' => [ + 'stream' => __DIR__ . '/../../log/dk.log', + ], + ], + ], + ], + ], + ], +]; +``` + +Then request the logger by that name: + +```php +/** @var \Psr\Log\LoggerInterface $logger */ +$logger = $container->get('dot-log.my_logger'); +``` + +Follow the [Configuring the writer(s)](configuring-writer.md) chapter for the writer options. + +## Supported containers + +The factories are plain classes with `__invoke(ContainerInterface $container, string $requestedName)`. +They work with any PSR-11 container that accepts a factory per service and passes the requested service name to it as the second argument, for example Laminas Service Manager. + +`dot-log` does not require `laminas/laminas-servicemanager`. +Applications that use it as their container require it themselves. + +## The config provider + +`Dot\Log\ConfigProvider` is kept so that applications listing it in `config/config.php` keep working, but it registers nothing. +You can remove it from `config/config.php`. + +> Version 5 registered an abstract factory that answered every `dot-log.*` name. +> Version 6 needs an explicit entry for each logger: see [Upgrading](upgrading.md). + +## The default logger service + +`Dot\Log\LoggerServiceFactory` creates a logger from the `log` config key, for applications that want to type-hint a single default logger: + +```php + [ + 'factories' => [ + \Dot\Log\Logger::class => \Dot\Log\LoggerServiceFactory::class, + ], + ], + 'log' => [ + 'writers' => [ + ['name' => 'stream', 'options' => ['stream' => __DIR__ . '/../../log/app.log']], + ], + ], +]; +``` diff --git a/docs/book/v6/configuring-writer.md b/docs/book/v6/configuring-writer.md new file mode 100644 index 0000000..dca5e99 --- /dev/null +++ b/docs/book/v6/configuring-writer.md @@ -0,0 +1,62 @@ +# Configuring the writer(s) + +Loggers must have at least one writer. + +A writer is an object that implements `Dot\Log\Writer\WriterInterface`, usually by extending `Dot\Log\Writer\AbstractWriter`. +A writer's responsibility is to record log data to a storage backend. + +## Writing to a file (stream) + +You can separate logs into multiple files using writers and filters. +For example, *warnings.log*, *errors.log*, *all_messages.log*. + +The following is the simplest example to write all log messages to `/log/dk.log`: + +```php +return [ + 'dot_log' => [ + 'loggers' => [ + 'my_logger' => [ + 'writers' => [ + 'FileWriter' => [ + 'name' => 'stream', + 'level' => \Dot\Log\Logger::ALERT, // this is equal to 1 + 'options' => [ + 'stream' => __DIR__ . '/../../log/dk.log', + 'log_lifetime' => null, // OPTIONAL + ], + ], + ], + ], + ], + ], +]; +``` + +- The `FileWriter` key is a free-form name for readability. It is optional: the writers array can also be a list. +- The `name` key is **mandatory** and selects the writer plugin: `stream`, `noop`, a class name, or a name registered under `dot_log.writer_manager` (see [Registering custom plugins](registering-custom-plugins.md)). +- The `level` key is optional and defaults to `1`. It does not filter messages: it orders the writers of a logger, and writers with a higher value write first. The key `priority` is accepted as an alias. +- The `options` key is passed to the writer. + +## Stream writer options + +| Option | Required | Description | +| --- | --- | --- | +| `stream` | yes | A file path, a stream URL such as `php://stderr`, or an open stream resource | +| `mode` | no | The `fopen()` mode, default `a`. Must be `a` for an open resource | +| `log_separator` | no | Written after each line, default `PHP_EOL` | +| `chmod` | no | Permissions of a new log file, default `0666` | +| `formatter` | no | The formatter, default `simple`. See [Formatting messages](formatting-messages.md) | +| `filters` | no | The filters. See [Filtering log messages](filtering-log-messages.md) | +| `log_lifetime` | no | Number of days after which the writer's log files are deleted. See below | + +## Automatic Log File Deletion + +The `options.log_lifetime` key specifies a number of days after which the specific `writer`'s log files will be **deleted even if not empty**. + +The key can be omitted completely or set to `null` in order to skip this feature. + +The deletion runs when the logger is destroyed, and only for streams named with date placeholders (see [Grouping log files by date](grouping-log-files-by-date.md)). +Only files in the stream's directory whose name matches the stream's name pattern are deleted. + +> This feature will delete all relevant log files for the configured `writer`, take care not to misconfigure it in a production environment! diff --git a/docs/book/v6/example-with-formatter.md b/docs/book/v6/example-with-formatter.md new file mode 100644 index 0000000..8d3d9c0 --- /dev/null +++ b/docs/book/v6/example-with-formatter.md @@ -0,0 +1,48 @@ +# Example with formatter + +- The log is used through `dot-log` +- The logger name is `my_logger` +- It writes to file: `log/dk.log` +- It is configured to explicitly write all messages +- The messages are formatted as JSON + +```php + [ + 'loggers' => [ + 'my_logger' => [ + 'writers' => [ + 'FileWriter' => [ + 'name' => 'stream', + 'level' => \Dot\Log\Logger::ALERT, + 'options' => [ + 'stream' => __DIR__ . '/../../log/dk.log', + // explicitly log all messages + 'filters' => [ + 'allMessages' => [ + 'name' => 'level', + 'options' => [ + 'operator' => '>=', + 'level' => \Dot\Log\Logger::EMERG, + ], + ], + ], + 'formatter' => [ + 'name' => 'json', + ], + ], + ], + ], + ], + ], + ], +]; +``` + +A call to `$logger->warning('user {id} logged in', ['id' => 7])` writes: + +```json +{"timestamp":"2026-11-13T16:15:11+00:00","level":4,"levelName":"warning","message":"user 7 logged in","context":{"id":7}} +``` diff --git a/docs/book/v6/filtering-log-messages.md b/docs/book/v6/filtering-log-messages.md new file mode 100644 index 0000000..6b8c36c --- /dev/null +++ b/docs/book/v6/filtering-log-messages.md @@ -0,0 +1,111 @@ +# Filtering log messages + +The following conforms to the `PSR-3: Logger Interface` document. + +The log levels are in order of level/importance: + +- emergency (0) +- alert (1) +- critical (2) +- error (3) +- warning (4) +- notice (5) +- info (6) +- debug (7) + +Because the plain Logger in `dot-log` is fully compatible with PSR-3, it provides a way to log all of these message types. + +## Built-in filters + +| Name | Options | Accepts an event when | +| --- | --- | --- | +| `level` | `level` (int), `operator` (default `<=`) | The event level compares true to `level` with `operator`. Operators: `<`, `lt`, `<=`, `le`, `>`, `gt`, `>=`, `ge`, `==`, `=`, `eq`, `!=`, `<>`, `ne` | +| `regex` | `regex` (string) | The message matches the regular expression | +| `suppress` | `suppress` (bool, default `false`) | `suppress` is `false` | +| `callback` | `callback` (callable) | The callable returns `true` for the event array | +| `validator` | `validator` (any object with an `isValid($value): bool` method, such as a `Laminas\Validator\ValidatorInterface`) | The validator accepts the message. `dot-log` does not install `laminas/laminas-validator`: require it to use Laminas validators | + +An integer in the `filters` list is a shortcut for a `level` filter with the `<=` operator. + +## Example + +The following example has three file writers using filters: + +- First Example: `FileWriter` - All messages are logged in `/log/dk.log` +- Second Example: `OnlyWarningsWriter` - Only warnings are logged in `/log/warnings_only.log` +- Third Example: `WarningOrHigherWriter` - All important messages (`warnings` or critical) are logged in `/log/important_messages.log` + +```php + [ + 'loggers' => [ + 'my_logger' => [ + 'writers' => [ + 'FileWriter' => [ + 'name' => 'stream', + 'level' => \Dot\Log\Logger::ALERT, + 'options' => [ + 'stream' => __DIR__ . '/../../log/dk.log', + 'filters' => [ + 'allMessages' => [ + 'name' => 'level', + 'options' => [ + 'operator' => '>=', + 'level' => \Dot\Log\Logger::EMERG, + ], + ], + ], + ], + ], + // Only warnings + 'OnlyWarningsWriter' => [ + 'name' => 'stream', + 'level' => \Dot\Log\Logger::ALERT, + 'options' => [ + 'stream' => __DIR__ . '/../../log/warnings_only.log', + 'filters' => [ + 'warningOnly' => [ + 'name' => 'level', + 'options' => [ + 'operator' => '==', + 'level' => \Dot\Log\Logger::WARN, + ], + ], + ], + ], + ], + // Warnings and more important messages + 'WarningOrHigherWriter' => [ + 'name' => 'stream', + 'level' => \Dot\Log\Logger::ALERT, + 'options' => [ + 'stream' => __DIR__ . '/../../log/important_messages.log', + 'filters' => [ + 'importantMessages' => [ + 'name' => 'level', + 'options' => [ + // note, the smaller the level, the more important the message + // 0 - emergency, 1 - alert, 2 - critical, 3 - error, 4 - warning, etc. + 'operator' => '<=', + 'level' => \Dot\Log\Logger::WARN, + ], + ], + ], + ], + ], + ], + ], + ], + ], +]; +``` + +As in the writer configuration, the developer can optionally use keys for associating the filters with a name. + +> The operator for more important messages is `<=`, this is because the number representation is smaller for a more important message type. + +The filter added on the first writer is equivalent to not setting a filter, but it was added to illustrate the usage of the operator to explicitly allow all messages. + +To add your own filters, see [Registering custom plugins](registering-custom-plugins.md). diff --git a/docs/book/v6/formatting-messages.md b/docs/book/v6/formatting-messages.md new file mode 100644 index 0000000..86fa738 --- /dev/null +++ b/docs/book/v6/formatting-messages.md @@ -0,0 +1,55 @@ +# Formatting Messages + +When using `dot-log`, the logged value is not limited to a string. +Arrays and objects can be logged in the context as well. +For better readability, these values are serialized by the formatter. + +`dot-log` provides two formatters: + +| Name | Class | Output | +| --- | --- | --- | +| `simple` | `Dot\Log\Formatter\Simple` | One line of text. The default for the stream writer | +| `json` | `Dot\Log\Formatter\Json` | One JSON object per line | + +The formatter accepts the following parameters: + +- `name`: the formatter plugin name, or a class implementing `Dot\Log\Formatter\FormatterInterface` +- `options`: passed to the formatter constructor + +The following snippet formats the message as JSON data: + +```php +'formatter' => [ + 'name' => 'json', +], +``` + +## Simple formatter options + +| Option | Default | Description | +| --- | --- | --- | +| `format` | `%timestamp% %levelName% (%level%): %message% %extra%` | Every `%key%` is replaced with that key of the log event | +| `dateTimeFormat` | `c` (ISO 8601) | The [date format](https://www.php.net/manual/en/datetime.format.php) of the timestamp and of any date value | + +The log event has the keys `timestamp`, `level`, `levelName`, `message` and `context`, plus anything added by processors. +The default format does not print the context; add `%context%` to print it as JSON: + +```php +'formatter' => [ + 'name' => 'simple', + 'options' => [ + 'format' => '%timestamp% %levelName%: %message% %context%', + 'dateTimeFormat' => 'Y-m-d H:i:s', + ], +], +``` + +## How values are formatted + +- Dates (`DateTime`, `DateTimeImmutable` or any `DateTimeInterface`) use the configured date format, in both formatters. +- Arrays and iterable objects are written as JSON. +- Objects with a `__toString()` method are cast to string by the `simple` formatter. +- The `json` formatter keeps strings as strings: `"0712345678"` stays a string, it is not turned into a number. +- Invalid UTF-8 is replaced with the Unicode replacement character instead of failing. + +To add your own formatter, see [Registering custom plugins](registering-custom-plugins.md). diff --git a/docs/book/v6/grouping-log-files-by-date.md b/docs/book/v6/grouping-log-files-by-date.md new file mode 100644 index 0000000..6f9e438 --- /dev/null +++ b/docs/book/v6/grouping-log-files-by-date.md @@ -0,0 +1,22 @@ +# Grouping log files by date + +By default, logs will be written to the same file: `log/dk.log`. + +Optionally, you can use date format specifiers wrapped between curly braces in your stream writer's `stream` option to automatically group your logs by day, week, month, year, etc. + +Examples: + +- `log/dk-{Y}-{m}-{d}.log` will create a new log file each day (eg: `log/dk-2021-01-01.log`) +- `log/dk-{Y}-{W}.log` will create a new log file each week (eg: `log/dk-2021-10.log`) + +The full list of format specifiers is available in the [PHP docs for datetime formatting](https://www.php.net/manual/en/datetime.format.php). + +The date is resolved when the logger is created, by `Dot\Log\Factory\LoggerFactory`. +A long-running process (a queue worker, for example) keeps writing to the file of the day it started. + +## Deleting old files + +When `log_lifetime` is set, the stream writer deletes its old files from the same directory. +Each placeholder in the file name matches letters and digits, and the rest of the name must match exactly: with `dk-{Y}-{m}-{d}.log`, the file `dk-2021-01-01.log` matches, `other-2021-01-01.log` does not. + +Streams without a placeholder are never cleaned up. diff --git a/docs/book/v6/overview.md b/docs/book/v6/overview.md new file mode 100644 index 0000000..ee2bf41 --- /dev/null +++ b/docs/book/v6/overview.md @@ -0,0 +1,31 @@ +# Overview + +Robust, composite PSR-3 compliant logger with filtering and formatting. + +`dot-log` 6 works with any PSR-11 container. It does not require `laminas/laminas-servicemanager`. + +## Badges + +![OSS Lifecycle](https://img.shields.io/osslifecycle/dotkernel/dot-log) +![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/6.0.0) + +[![GitHub issues](https://img.shields.io/github/issues/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/issues) +[![GitHub forks](https://img.shields.io/github/forks/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/network) +[![GitHub stars](https://img.shields.io/github/stars/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/stargazers) +[![GitHub license](https://img.shields.io/github/license/dotkernel/dot-log)](https://github.com/dotkernel/dot-log/blob/6.0/LICENSE.md) + +[![Build Static](https://github.com/dotkernel/dot-log/actions/workflows/continuous-integration.yml/badge.svg?branch=6.0)](https://github.com/dotkernel/dot-log/actions/workflows/continuous-integration.yml) +[![codecov](https://codecov.io/gh/dotkernel/dot-log/graph/badge.svg?token=JX19KTBRCZ)](https://codecov.io/gh/dotkernel/dot-log) +[![PHPStan](https://github.com/dotkernel/dot-log/actions/workflows/static-analysis.yml/badge.svg?branch=6.0)](https://github.com/dotkernel/dot-log/actions/workflows/static-analysis.yml) + +## Version History + +| Branch | Container | Log style implementation | PHP Version | +|--------|--------------------------|--------------------------|---------------------------------------------------------------------------------------------------------| +| 6.0 | Any PSR-11 container | PSR-Log | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/6.0.0) | +| 5.0 | Service Manager 4 | PSR-Log | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/5.3.1) | +| 4.1 | Service Manager 4 | Laminas Log style | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/4.1.4) | +| 4.0 | Service Manager 3 | Laminas Log style | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/4.0.6) | +| 3.0 | Service Manager 3 | Laminas Log | ![PHP from Packagist (specify version)](https://img.shields.io/packagist/php-v/dotkernel/dot-log/3.5.4) | + +Upgrading from 5.x? See [Upgrading](upgrading.md). diff --git a/docs/book/v6/registering-custom-plugins.md b/docs/book/v6/registering-custom-plugins.md new file mode 100644 index 0000000..b670106 --- /dev/null +++ b/docs/book/v6/registering-custom-plugins.md @@ -0,0 +1,92 @@ +# Registering custom plugins + +Writers, filters, formatters and processors are plugins. +`dot-log` builds them with four plugin managers, configured under these keys: + +| Plugin type | Config key | Interface | +| --- | --- | --- | +| Writer | `dot_log.writer_manager` | `Dot\Log\Writer\WriterInterface` | +| Filter | `dot_log.filter_manager` | `Dot\Log\Filter\FilterInterface` | +| Formatter | `dot_log.formatter_manager` | `Dot\Log\Formatter\FormatterInterface` | +| Processor | `dot_log.processor_manager` | `Dot\Log\Processor\ProcessorInterface` | + +Each key accepts: + +- `aliases`: a short name mapped to a class name, or to another alias +- `factories`: a class name (or alias) mapped to a factory class name or a callable + +```php + [ + 'filter_manager' => [ + 'aliases' => [ + 'business_hours' => \App\Log\BusinessHoursFilter::class, + ], + ], + 'formatter_manager' => [ + 'factories' => [ + 'app_line' => \App\Log\AppLineFormatterFactory::class, + ], + ], + 'loggers' => [ + 'my_logger' => [ + 'writers' => [ + [ + 'name' => 'stream', + 'options' => [ + 'stream' => __DIR__ . '/../../log/dk.log', + 'filters' => [['name' => 'business_hours']], + 'formatter' => ['name' => 'app_line'], + ], + ], + ], + ], + ], + ], +]; +``` + +## How a plugin name is resolved + +1. Aliases are followed, first by exact name, then lower-cased. +1. If a factory is registered for the result, the factory creates the plugin. +1. Otherwise, if the result is a class name, the class is instantiated. The options are passed to the constructor, or nothing when no options were given. +1. Otherwise, if the application container has a service with that name, the service is used. +1. Otherwise, `Dot\Log\Exception\ServiceNotFoundException` is thrown. + +The plugin must implement the interface of its type, or `Dot\Log\Exception\InvalidArgumentException` is thrown. +Plugins are never shared: every writer gets its own filter and formatter instances. + +## Factories + +A factory is called with the application container, the resolved name and the options: + +```php +` service. +Version 6 removes it: register `Dot\Log\Factory\LoggerFactory` for each logger you use. + +Before, `config/config.php` listed `\Dot\Log\ConfigProvider::class`, and `config/autoload/logger.global.php` held only the logger configuration: + +```php +return [ + 'dot_log' => [ + 'loggers' => [ + 'default_logger' => [/* ... */], + ], + ], +]; +``` + +After, `config/autoload/logger.global.php` also registers the logger: + +```php +return [ + 'dependencies' => [ + 'factories' => [ + 'dot-log.default_logger' => \Dot\Log\Factory\LoggerFactory::class, + ], + ], + 'dot_log' => [ + 'loggers' => [ + 'default_logger' => [/* ... */], + ], + ], +]; +``` + +`Dot\Log\ConfigProvider` still exists but registers nothing, so it can stay in `config/config.php` or be removed. + +Packages that fetch a logger by name, such as `dotkernel/dot-errorhandler` with `'logger' => 'dot-log.default_logger'`, keep working once that name is registered. + +## Changes that can break code + +| Change | Symptom | Fix | +| --- | --- | --- | +| `LoggerAbstractServiceFactory` removed | `ServiceNotFoundException` for `dot-log.` | Register `'dot-log.' => LoggerFactory::class` (see above) | +| `ConfigProvider` returns `[]` | Services `LogWriterManager`, `LogFilterManager`, `LogFormatterManager`, `LogProcessorManager`, `Dot\Log\Logger` and the plugin manager class names are not registered | You rarely need them: `LoggerFactory` builds the managers from `dot_log.*_manager`. If you do, register the `*PluginManagerFactory` and `LoggerServiceFactory` classes yourself | +| The plugin managers no longer extend `Laminas\ServiceManager\AbstractPluginManager` | Calls to `setService()`, `setFactory()`, `setAlias()`, `configure()` with other keys, or `get()` with options fail | Configure plugins under `dot_log.*_manager` with `aliases` and `factories`, see [Registering custom plugins](registering-custom-plugins.md). Use `build($name, $options)` | +| `Laminas\ServiceManager\Exception\InvalidServiceException` and `ServiceNotFoundException` are no longer thrown by the managers | `catch` blocks miss the exception | Catch `Dot\Log\Exception\InvalidArgumentException`, or `Dot\Log\Exception\ServiceNotFoundException` for unknown plugins (it implements `Psr\Container\NotFoundExceptionInterface`) | +| `Dot\Log\Formatter\Base` renamed to `AbstractFormatter`, now abstract, and its `format()` replaced by `normalizeEvent()` | Fatal error: class `Base` not found | Extend `AbstractFormatter`, implement `format(array $event): string`, and call `normalizeEvent()` for the normalized values | +| `FormatterInterface::format()` takes `array` and returns `string` | Fatal error in custom formatters declared with `iterable` or returning arrays | Change the signature to `format(array $event): string` | +| `FilterInterface::filter()` returns `bool` | Fatal error in custom filters declared as `bool\|int\|null` | Return `bool` | +| `Logger::getWriterPluginManager()`, `getProcessorPluginManager()`, `writerPlugin()`, `processorPlugin()` no longer return `null` | Subclasses overriding them with nullable return types fail | Remove the `?` from the return types | +| Event `timestamp` is a `DateTimeImmutable` | Custom formatters or processors checking `instanceof DateTime` miss it | Check `instanceof DateTimeInterface` | +| Context placeholders: `Stringable` objects are cast, booleans become `true`/`false`, other objects become `[object ClassName]`, arrays become `[array]` | Messages read `user ID-42` instead of `user object` | Nothing to do, unless something parses the old output | +| `Json` formatter no longer uses `JSON_NUMERIC_CHECK` | `"0712345678"` is written as a string, not as `712345678` | Update log parsers that relied on numbers | +| Error handler: `context.errno` is the PHP error number | `errno` was the log level (for example `4`), it is now `E_WARNING` (`2`) or similar | Update log parsers that read `errno` | +| `Backtrace` processor ignores `Dot\Log` and `Psr\Log` frames | `file`, `line`, `class` and `function` now show your code instead of `Dot\Log\Logger::log` | Nothing to do. Ignored namespaces now match whole namespace segments | +| `Regex` filter validates its pattern first | `InvalidArgumentException` instead of `TypeError` for a missing pattern | Catch `Dot\Log\Exception\InvalidArgumentException` | +| `Level` filter validates its operator | `InvalidArgumentException` at configuration time instead of `ValueError` at log time | Use one of the documented operators | +| `Stream` log clean-up only matches the writer's own file names | Files that matched the loose old pattern are no longer deleted | Nothing to do | +| `Logger::log()` rejects non-integer levels such as `2.5` | `InvalidArgumentException` | Pass a level code or a PSR-3 level name | +| `laminas/laminas-validator` is no longer installed | Class `Laminas\Validator\...` not found in your validator configuration | `composer require laminas/laminas-validator`. The `validator` filter itself works without it: it accepts any object with an `isValid()` method | +| `Validator::$validator` is typed `object` instead of `Laminas\Validator\ValidatorInterface` | Subclasses redeclaring the property with the old type fail | Declare it as `object`, or do not redeclare it | + +## Fixed behaviour you may have worked around + +- Custom plugins configured under `dot_log.writer_manager`, `filter_manager`, `formatter_manager` and `processor_manager` were ignored. They are now used. +- The writer `level` (or `priority`) was documented as optional but omitting it threw a `TypeError`. It now defaults to `1`. +- A `Stream` writer without a formatter crashed. It now uses the `simple` formatter. +- Formatter options were ignored when the formatter was given by class name. They are now passed to the constructor. +- The `simple` formatter wrote a literal `%extra%` for events from the logger. It now writes nothing for an empty `extra`. +- Destroying a logger emptied the writers queue returned by `getWriters()`. + +## New + +- `Dot\Log\Factory\LoggerFactory`. +- The `json` formatter alias and the `callback` filter. +- `priority` as an alias of the writer and processor `level` key. +- `Logger::createErrorHandler()` and `Logger::createExceptionHandler()` return the handlers without registering them. +- `Stream::getOldLogsPattern()` shows which file names the log clean-up matches. diff --git a/docs/book/v6/usage.md b/docs/book/v6/usage.md new file mode 100644 index 0000000..1f0ece2 --- /dev/null +++ b/docs/book/v6/usage.md @@ -0,0 +1,98 @@ +# Usage + +Basic usage of the logger is illustrated below. + +The messages are written to see which logs are written and which are not written. + +```php +/** @var \Psr\Log\LoggerInterface $logger */ +$logger = $container->get('dot-log.my_logger'); + +$logger->emergency('0 EMERG'); +$logger->alert('1 ALERT'); +$logger->critical('2 CRITICAL'); +$logger->error('3 ERR'); +$logger->warning('4 WARN'); +$logger->notice('5 NOTICE'); +$logger->info('6 INF'); +$logger->debug('7 debug'); +$logger->log(\Dot\Log\Logger::NOTICE, 'NOTICE from log()'); +$logger->log(\Psr\Log\LogLevel::NOTICE, 'NOTICE from log() with a PSR-3 level name'); +``` + +`log()` accepts a level code from `0` to `7` or a PSR-3 level name, and throws `Dot\Log\Exception\InvalidArgumentException` for anything else. + +## Placeholders + +`dot-log` implements placeholder interpolation as described in PSR-3. +Placeholders MUST be delimited with single opening/closing braces: `{placeholder}`, with the names composed only of the characters `A-Z`, `a-z`, `0-9`, underscore `_`, and period `.`. +Placeholders are interpolated as follows: + +| Context value | Replacement | +| --- | --- | +| string, integer, float | The value | +| boolean | `true` or `false` | +| object with `__toString()` | The string value | +| `DateTimeInterface` | The date in RFC 3339 format, for example `2026-01-02T03:04:05+00:00` | +| other object | `[object ClassName]` | +| array and other types | `[array]`, and so on | +| `null` or a missing key | Not replaced | + +```php +$logger->info('User {user} logged in at {time}', [ + 'user' => $user, // a Stringable object + 'time' => new DateTimeImmutable(), +]); +``` + +## Logging PHP errors and exceptions + +The logger can register itself as PHP error handler, exception handler and fatal-error shutdown function, either with options or with static methods: + +```php +'dot_log' => [ + 'loggers' => [ + 'my_logger' => [ + 'errorhandler' => true, + 'exceptionhandler' => true, + 'fatal_error_shutdownfunction' => true, + 'writers' => [ + // ... + ], + ], + ], +], +``` + +```php +\Dot\Log\Logger::registerErrorHandler($logger); +\Dot\Log\Logger::registerExceptionHandler($logger); +\Dot\Log\Logger::registerFatalErrorShutdownFunction($logger); +``` + +- Errors are logged only when they are included in `error_reporting()`. +- The context of a logged error has the keys `errno` (the PHP error number, for example `E_WARNING`), `file` and `line`. +- An exception is logged with every previous exception, the innermost first. The context has `file`, `line` and `trace`. + +## Processors + +Processors change the event before it reaches the writers: + +| Name | Effect | +| --- | --- | +| `backtrace` | Adds `file`, `line`, `class` and `function` of the code that called the logger to the context. Option `ignoredNamespaces` adds namespaces to skip, besides `Dot\Log` and `Psr\Log` | +| `psrplaceholder` | Interpolates placeholders. The logger already does this, so it is only needed for events built by hand | +| `requestid` | Adds a `requestId` to the context, the same for every event of a request | +| `referenceid` | Adds a `referenceId` to the context. It can be set with `setReferenceId()` | + +```php +'my_logger' => [ + 'processors' => [ + ['name' => 'backtrace'], + ['name' => 'requestid'], + ], + 'writers' => [ + // ... + ], +], +``` diff --git a/log.global.php.dist b/log.global.php.dist index 2f883d0..340458e 100644 --- a/log.global.php.dist +++ b/log.global.php.dist @@ -1,26 +1,46 @@ [ + 'dependencies' => [ + 'factories' => [ + // register one entry per logger defined under dot_log.loggers + 'dot-log.default_logger' => LoggerFactory::class, + ], + ], + 'dot_log' => [ 'loggers' => [ - //define log services here - 'stream_logger' => [ + 'default_logger' => [ 'writers' => [ - 'name' => 'stream', - 'level' => \Dot\Log\Logger::DEBUG, - 'options' => [ - 'stream' => 'php://output', - 'formatter' => [ - 'name' => 'MyFormatter', - ], - 'filters' => [ - [ - 'name' => 'MyFilter', + 'FileWriter' => [ + // writer plugin: "stream", "noop", or a class implementing Dot\Log\Writer\WriterInterface + 'name' => 'stream', + // optional priority among the writers of this logger, default 1 + 'level' => Logger::ALERT, + 'options' => [ + // {Y}, {m}, {d} and other date() characters are replaced with the current date + 'stream' => 'log/error-log-{Y}-{m}-{d}.log', + // optional, default "simple"; use "json" for one JSON object per line + 'formatter' => [ + 'name' => 'json', + ], + 'filters' => [ + 'importantMessages' => [ + 'name' => 'level', + 'options' => [ + 'operator' => '<=', + 'level' => Logger::WARN, + ], + ], ], + // optional; null or omitted disables the deletion of old log files. + // An integer deletes this writer's log files older than that many days. + 'log_lifetime' => null, ], - // optional key that can be omitted or set to null to disable auto-deletion of logs - // accepts an integer representing the number of days after which a log will be deleted - 'log_lifetime' => null, ], ], ], diff --git a/mkdocs.yml b/mkdocs.yml index 5322abc..7a033d8 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -2,22 +2,35 @@ docs_dir: docs/book site_dir: docs/html extra: project: Packages - current_version: v5 + current_version: v6 versions: + - v6 - v5 - v4 - v3 nav: - Home: index.md + - v6: + - "Overview": v6/overview.md + - "Registering Loggers": v6/adding-config-provider.md + - "Configuring the writer(s)": v6/configuring-writer.md + - "Grouping log files by date": v6/grouping-log-files-by-date.md + - "Filtering log messages": v6/filtering-log-messages.md + - "Formatting Messages": v6/formatting-messages.md + - "Example with formatter": v6/example-with-formatter.md + - "Usage": v6/usage.md + - "Registering custom plugins": v6/registering-custom-plugins.md + - "Upgrading from 5.x": v6/upgrading.md - v5: - "Overview": v5/overview.md - - "Adding The Config Provider": v5/adding-config-provider.md - - "Configuring the writer(s)": v5/configuring-writer.md - - "Grouping log files by date": v5/grouping-log-files-by-date.md - - "Filtering log messages": v5/filtering-log-messages.md - - "Formatting Messages": v5/formatting-messages.md - - "Example with formatter": v5/example-with-formatter.md - - "Usage": v5/usage.md + - "Adding The Config Provider": v5/adding-config-provider.md + - "Configuring the writer(s)": v5/configuring-writer.md + - "Grouping log files by date": v5/grouping-log-files-by-date.md + - "Filtering log messages": v5/filtering-log-messages.md + - "Formatting Messages": v5/formatting-messages.md + - "Example with formatter": v5/example-with-formatter.md + - "Usage": v5/usage.md + - "Upgrading from 4.x": v5/upgrading.md - v4: - "Overview": v4/overview.md - "Adding The Config Provider": v4/adding-config-provider.md diff --git a/phpstan.neon b/phpstan.neon index 88a2a9a..08d6acd 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -1,12 +1,8 @@ includes: - vendor/phpstan/phpstan-phpunit/extension.neon parameters: - level: 5 + level: 8 paths: - src - test treatPhpDocTypesAsCertain: false - ignoreErrors: - - - message: '/Undefined variable: \$test/' - path: test/LoggerTest.php diff --git a/phpunit.xml b/phpunit.xml index 818b281..4001a2d 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -1,16 +1,23 @@ ./test - - + ./src diff --git a/src/ConfigProvider.php b/src/ConfigProvider.php index 0805b44..0b729f5 100644 --- a/src/ConfigProvider.php +++ b/src/ConfigProvider.php @@ -4,51 +4,25 @@ namespace Dot\Log; -use Dot\Log\Factory\FilterPluginManagerFactory; -use Dot\Log\Factory\FormatterPluginManagerFactory; -use Dot\Log\Factory\LoggerAbstractServiceFactory; -use Dot\Log\Factory\ProcessorPluginManagerFactory; -use Dot\Log\Factory\WriterPluginManagerFactory; -use Dot\Log\Manager\FilterPluginManager; -use Dot\Log\Manager\FormatterPluginManager; -use Dot\Log\Manager\ProcessorPluginManager; -use Dot\Log\Manager\WriterPluginManager; - +/** + * Kept so that applications listing it keep working. dot-log registers no services: register a + * Dot\Log\Factory\LoggerFactory entry for each "dot-log." logger the application uses. + */ class ConfigProvider { + /** + * @return array + */ public function __invoke(): array { - return [ - 'dependencies' => $this->getDependencies(), - 'dot_log' => [ - 'formatter_manager' => [], - 'filter_manager' => [], - 'processor_manager' => [], - 'writer_manager' => [], - 'loggers' => [], - ], - ]; + return []; } + /** + * @return array + */ public function getDependencies(): array { - return [ - 'abstract_factories' => [ - LoggerAbstractServiceFactory::class, - ], - 'aliases' => [ - FilterPluginManager::class => 'LogFilterManager', - FormatterPluginManager::class => 'LogFormatterManager', - ProcessorPluginManager::class => 'LogProcessorManager', - WriterPluginManager::class => 'LogWriterManager', - ], - 'factories' => [ - Logger::class => LoggerServiceFactory::class, - 'LogFilterManager' => FilterPluginManagerFactory::class, - 'LogFormatterManager' => FormatterPluginManagerFactory::class, - 'LogProcessorManager' => ProcessorPluginManagerFactory::class, - 'LogWriterManager' => WriterPluginManagerFactory::class, - ], - ]; + return []; } } diff --git a/src/Exception/ServiceNotFoundException.php b/src/Exception/ServiceNotFoundException.php new file mode 100644 index 0000000..9d01e5b --- /dev/null +++ b/src/Exception/ServiceNotFoundException.php @@ -0,0 +1,11 @@ +has('config')) { - throw new Exception('Unable to find config'); + $config = $container->has('config') ? $container->get('config') : []; + if (! is_array($config)) { + throw new RuntimeException('Unable to find config'); } - $config = $container->get('config'); - - if (! isset($config['dot_log']) || ! is_array($config['dot_log'])) { - throw new Exception('Unable to find dot_log config'); - } - - $config = $config['dot_log']; - - if (! isset($config['filter_manager']) || ! is_array($config['filter_manager'])) { - throw new Exception('Unable to find filter_manager config'); + $managerConfig = $config['dot_log']['filter_manager'] ?? []; + if (! is_array($managerConfig)) { + throw new RuntimeException('The dot_log.filter_manager config must be an array'); } - return new FilterPluginManager($container, $config); + return new FilterPluginManager($container, $managerConfig); } } diff --git a/src/Factory/FormatterPluginManagerFactory.php b/src/Factory/FormatterPluginManagerFactory.php index 1754a31..016682c 100644 --- a/src/Factory/FormatterPluginManagerFactory.php +++ b/src/Factory/FormatterPluginManagerFactory.php @@ -4,39 +4,36 @@ namespace Dot\Log\Factory; +use Dot\Log\Exception\RuntimeException; use Dot\Log\Manager\FormatterPluginManager; -use Exception; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use function is_array; +/** + * Optional: creates a FormatterPluginManager from config['dot_log']['formatter_manager'], + * for applications that want the manager as a container service. + */ class FormatterPluginManagerFactory { /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception */ public function __invoke(ContainerInterface $container): FormatterPluginManager { - if (! $container->has('config')) { - throw new Exception('Unable to find config'); + $config = $container->has('config') ? $container->get('config') : []; + if (! is_array($config)) { + throw new RuntimeException('Unable to find config'); } - $config = $container->get('config'); - - if (! isset($config['dot_log']) || ! is_array($config['dot_log'])) { - throw new Exception('Unable to find dot_log config'); - } - - $config = $config['dot_log']; - - if (! isset($config['formatter_manager']) || ! is_array($config['formatter_manager'])) { - throw new Exception('Unable to find formatter_manager config'); + $managerConfig = $config['dot_log']['formatter_manager'] ?? []; + if (! is_array($managerConfig)) { + throw new RuntimeException('The dot_log.formatter_manager config must be an array'); } - return new FormatterPluginManager($container, $config); + return new FormatterPluginManager($container, $managerConfig); } } diff --git a/src/Factory/LoggerAbstractServiceFactory.php b/src/Factory/LoggerAbstractServiceFactory.php deleted file mode 100644 index 30d7ad5..0000000 --- a/src/Factory/LoggerAbstractServiceFactory.php +++ /dev/null @@ -1,130 +0,0 @@ -configKey = $configKey; - } - - /** - * @param string $requestedName - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function canCreate(ContainerInterface $container, $requestedName): bool - { - $parts = explode('.', $requestedName); - if (count($parts) !== 2) { - return false; - } - if ($parts[0] !== static::PREFIX) { - return false; - } - - $config = $this->getConfig($container); - if (empty($config)) { - return false; - } - - return isset($config[$parts[1]]); - } - - /** - * @param string $requestedName - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null): Logger - { - $parts = explode('.', $requestedName); - - $config = $this->getConfig($container); - $config = $config[$parts[1]]; - - $this->processConfig($config, $container); - - return new Logger($config); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - protected function getConfig(ContainerInterface $services): array - { - if (! $services->has('config')) { - $this->config = []; - } - - $config = $services->get('config'); - if (isset($config[$this->configKey])) { - $this->config = $config[$this->configKey]; - } - - if ( - ! empty($this->config) - && isset($this->config[$this->subConfigKey]) - && is_array($this->config[$this->subConfigKey]) - ) { - $this->config = $this->config[$this->subConfigKey]; - } - - return $this->config; - } - - protected function processConfig(array &$config, ContainerInterface $services): void - { - if (isset($config['writers'])) { - foreach ($config['writers'] as $index => $writerConfig) { - if (! empty($writerConfig['options']['stream'])) { - $config['writers'][$index]['options']['stream_format'] = - pathinfo($writerConfig['options']['stream'])['basename']; - $config['writers'][$index]['options']['stream'] = self::parseVariables( - $writerConfig['options']['stream'] - ); - } - } - } - - parent::processConfig($config, $services); - } - - private static function parseVariables(string $stream): string - { - preg_match_all('/{([a-z])}/i', $stream, $matches); - if (! empty($matches[1])) { - foreach ($matches[1] as $match) { - $stream = str_replace('{' . $match . '}', date($match), $stream); - } - } - - return $stream; - } -} diff --git a/src/Factory/LoggerFactory.php b/src/Factory/LoggerFactory.php new file mode 100644 index 0000000..e931652 --- /dev/null +++ b/src/Factory/LoggerFactory.php @@ -0,0 +1,101 @@ +] for the service "dot-log.". + * + * Register one entry per logger, with any PSR-11 container that passes the requested name to the factory: + * + * 'factories' => [ + * 'dot-log.default_logger' => \Dot\Log\Factory\LoggerFactory::class, + * ], + */ +class LoggerFactory extends LoggerServiceFactory +{ + public const PREFIX = 'dot-log.'; + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function __invoke(ContainerInterface $container, string $requestedName = ''): Logger + { + if (! str_starts_with($requestedName, self::PREFIX) || strlen($requestedName) === strlen(self::PREFIX)) { + throw new RuntimeException(sprintf( + 'LoggerFactory creates services named "%s"; "%s" was requested', + self::PREFIX, + $requestedName + )); + } + $name = substr($requestedName, strlen(self::PREFIX)); + + $loggers = $this->getApplicationConfig($container)['dot_log']['loggers'] ?? null; + if (! is_array($loggers)) { + throw new RuntimeException('Unable to find the "dot_log.loggers" config'); + } + + $config = $loggers[$name] ?? null; + if (! is_array($config)) { + throw new RuntimeException(sprintf('Unable to find the "dot_log.loggers.%s" config', $name)); + } + + $this->resolveStreamDates($config); + $this->processConfig($config, $container); + + return new Logger($config); + } + + /** + * Replaces date placeholders such as {Y}, {m} or {d} in writer streams with the current date, and keeps the + * original file name as "stream_format" for the log clean-up of the Stream writer. + * + * @param array $config + */ + protected function resolveStreamDates(array &$config): void + { + if (! isset($config['writers']) || ! is_array($config['writers'])) { + return; + } + + foreach ($config['writers'] as $index => $writerConfig) { + $stream = is_array($writerConfig) ? $writerConfig['options']['stream'] ?? null : null; + if (! is_string($stream) || $stream === '') { + continue; + } + + $config['writers'][$index]['options']['stream_format'] = pathinfo($stream, PATHINFO_BASENAME); + $config['writers'][$index]['options']['stream'] = self::parseVariables($stream); + } + } + + public static function parseVariables(string $stream): string + { + return (string) preg_replace_callback( + '/\{([a-z])}/i', + static fn (array $match): string => date($match[1]), + $stream + ); + } +} diff --git a/src/Factory/ProcessorPluginManagerFactory.php b/src/Factory/ProcessorPluginManagerFactory.php index fd3cbd8..2553941 100644 --- a/src/Factory/ProcessorPluginManagerFactory.php +++ b/src/Factory/ProcessorPluginManagerFactory.php @@ -4,39 +4,36 @@ namespace Dot\Log\Factory; +use Dot\Log\Exception\RuntimeException; use Dot\Log\Manager\ProcessorPluginManager; -use Exception; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use function is_array; +/** + * Optional: creates a ProcessorPluginManager from config['dot_log']['processor_manager'], + * for applications that want the manager as a container service. + */ class ProcessorPluginManagerFactory { /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception */ public function __invoke(ContainerInterface $container): ProcessorPluginManager { - if (! $container->has('config')) { - throw new Exception('Unable to find config'); + $config = $container->has('config') ? $container->get('config') : []; + if (! is_array($config)) { + throw new RuntimeException('Unable to find config'); } - $config = $container->get('config'); - - if (! isset($config['dot_log']) || ! is_array($config['dot_log'])) { - throw new Exception('Unable to find dot_log config'); - } - - $config = $config['dot_log']; - - if (! isset($config['processor_manager']) || ! is_array($config['processor_manager'])) { - throw new Exception('Unable to find processor_manager config'); + $managerConfig = $config['dot_log']['processor_manager'] ?? []; + if (! is_array($managerConfig)) { + throw new RuntimeException('The dot_log.processor_manager config must be an array'); } - return new ProcessorPluginManager($container, $config); + return new ProcessorPluginManager($container, $managerConfig); } } diff --git a/src/Factory/WriterFactory.php b/src/Factory/WriterFactory.php index ac0b463..f1143d3 100644 --- a/src/Factory/WriterFactory.php +++ b/src/Factory/WriterFactory.php @@ -4,17 +4,41 @@ namespace Dot\Log\Factory; -use Laminas\ServiceManager\Factory\FactoryInterface; +use Dot\Log\Exception\InvalidArgumentException; +use Dot\Log\Writer\WriterInterface; +use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; +use Psr\Container\NotFoundExceptionInterface; +use function class_exists; +use function is_a; use function is_string; +use function sprintf; -class WriterFactory implements FactoryInterface +/** + * Creates writers for the WriterPluginManager. Plugin managers given by service name are fetched from the container. + */ +class WriterFactory { - public function __invoke(ContainerInterface $container, string $requestedName, ?array $options = null): object - { - $options = (array) $options; + /** + * @param array|null $options + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function __invoke( + ContainerInterface $container, + string $requestedName, + ?array $options = null + ): WriterInterface { + if (! class_exists($requestedName) || ! is_a($requestedName, WriterInterface::class, true)) { + throw new InvalidArgumentException(sprintf( + '"%s" is not a class implementing %s', + $requestedName, + WriterInterface::class + )); + } + $options = (array) $options; $options = $this->populateOptions($options, $container, 'filter_manager', 'LogFilterManager'); $options = $this->populateOptions($options, $container, 'formatter_manager', 'LogFormatterManager'); @@ -23,6 +47,11 @@ public function __invoke(ContainerInterface $container, string $requestedName, ? /** * Populates the options array with the correct container value. + * + * @param array $options + * @return array + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ private function populateOptions( array $options, @@ -30,14 +59,13 @@ private function populateOptions( string $name, string $defaultService ): array { - if (isset($options[$name]) && is_string($options[$name])) { + if (isset($options[$name]) && is_string($options[$name]) && $container->has($options[$name])) { $options[$name] = $container->get($options[$name]); return $options; } if (! isset($options[$name]) && $container->has($defaultService)) { $options[$name] = $container->get($defaultService); - return $options; } return $options; diff --git a/src/Factory/WriterPluginManagerFactory.php b/src/Factory/WriterPluginManagerFactory.php index ac06921..091d8d9 100644 --- a/src/Factory/WriterPluginManagerFactory.php +++ b/src/Factory/WriterPluginManagerFactory.php @@ -4,39 +4,36 @@ namespace Dot\Log\Factory; +use Dot\Log\Exception\RuntimeException; use Dot\Log\Manager\WriterPluginManager; -use Exception; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; use function is_array; +/** + * Optional: creates a WriterPluginManager from config['dot_log']['writer_manager'], + * for applications that want the manager as a container service. + */ class WriterPluginManagerFactory { /** * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface - * @throws Exception */ public function __invoke(ContainerInterface $container): WriterPluginManager { - if (! $container->has('config')) { - throw new Exception('Unable to find config'); + $config = $container->has('config') ? $container->get('config') : []; + if (! is_array($config)) { + throw new RuntimeException('Unable to find config'); } - $config = $container->get('config'); - - if (! isset($config['dot_log']) || ! is_array($config['dot_log'])) { - throw new Exception('Unable to find dot_log config'); - } - - $config = $config['dot_log']; - - if (! isset($config['writer_manager']) || ! is_array($config['writer_manager'])) { - throw new Exception('Unable to find writer_manager config'); + $managerConfig = $config['dot_log']['writer_manager'] ?? []; + if (! is_array($managerConfig)) { + throw new RuntimeException('The dot_log.writer_manager config must be an array'); } - return new WriterPluginManager($container, $config); + return new WriterPluginManager($container, $managerConfig); } } diff --git a/src/Filter/Callback.php b/src/Filter/Callback.php new file mode 100644 index 0000000..4a8797b --- /dev/null +++ b/src/Filter/Callback.php @@ -0,0 +1,52 @@ +): bool|iterable $callback + */ + public function __construct(callable|iterable $callback) + { + if (! is_callable($callback)) { + if ($callback instanceof Traversable) { + $callback = iterator_to_array($callback); + } + $callback = $callback['callback'] ?? null; + } + + if (! is_callable($callback)) { + throw new InvalidArgumentException(sprintf( + 'Callback must be callable; received "%s"', + get_debug_type($callback) + )); + } + + $this->callback = Closure::fromCallable($callback); + } + + /** + * @param array $event + */ + public function filter(array $event): bool + { + return (bool) ($this->callback)($event); + } +} diff --git a/src/Filter/FilterInterface.php b/src/Filter/FilterInterface.php index d8a71dc..ccf2421 100644 --- a/src/Filter/FilterInterface.php +++ b/src/Filter/FilterInterface.php @@ -8,6 +8,8 @@ interface FilterInterface { /** * Returns TRUE to accept the message, FALSE to block it. + * + * @param array $event */ - public function filter(array $event): bool|int|null; + public function filter(array $event): bool; } diff --git a/src/Filter/Level.php b/src/Filter/Level.php index c5ae852..2e1493d 100644 --- a/src/Filter/Level.php +++ b/src/Filter/Level.php @@ -8,14 +8,18 @@ use Traversable; use function gettype; +use function implode; +use function in_array; use function is_array; use function is_int; +use function is_numeric; use function iterator_to_array; use function sprintf; -use function version_compare; class Level implements FilterInterface { + public const OPERATORS = ['<', 'lt', '<=', 'le', '>', 'gt', '>=', 'ge', '==', '=', 'eq', '!=', '<>', 'ne']; + protected int $level; protected string $operator; @@ -23,6 +27,8 @@ class Level implements FilterInterface /** * Filter logging by $level. By default, it will accept any log * event whose level is less than or equal to $level. + * + * @param int|iterable $level */ public function __construct(iterable|int $level, ?string $operator = null) { @@ -40,15 +46,39 @@ public function __construct(iterable|int $level, ?string $operator = null) )); } + $operator ??= '<='; + if (! in_array($operator, self::OPERATORS, true)) { + throw new InvalidArgumentException(sprintf( + 'Operator must be one of "%s", received "%s"', + implode('", "', self::OPERATORS), + $operator + )); + } + $this->level = $level; - $this->operator = $operator ?? '<='; + $this->operator = $operator; } /** * Returns TRUE to accept the message, FALSE to block it. + * + * @param array $event */ - public function filter(array $event): bool|int|null + public function filter(array $event): bool { - return version_compare((string) $event['level'], (string) $this->level, $this->operator); + if (! isset($event['level']) || ! is_numeric($event['level'])) { + return false; + } + + $level = (int) $event['level']; + + return match ($this->operator) { + '<', 'lt' => $level < $this->level, + '<=', 'le' => $level <= $this->level, + '>', 'gt' => $level > $this->level, + '>=', 'ge' => $level >= $this->level, + '==', '=', 'eq' => $level === $this->level, + default => $level !== $this->level, + }; } } diff --git a/src/Filter/Regex.php b/src/Filter/Regex.php index d96f4a8..f99d595 100644 --- a/src/Filter/Regex.php +++ b/src/Filter/Regex.php @@ -5,11 +5,12 @@ namespace Dot\Log\Filter; use Dot\Log\Exception\InvalidArgumentException; -use ErrorException; use Laminas\Stdlib\ErrorHandler; use Traversable; use function is_array; +use function is_scalar; +use function is_string; use function iterator_to_array; use function preg_match; use function sprintf; @@ -20,19 +21,25 @@ class Regex implements FilterInterface /** * Regex to match */ - protected mixed $regex; + protected string $regex; /** * Filter out any log messages not matching the pattern * - * @throws ErrorException + * @param string|iterable $regex a pattern, or options with the key "regex" */ - public function __construct(iterable $regex) + public function __construct(string|iterable $regex) { if ($regex instanceof Traversable) { $regex = iterator_to_array($regex); } - $regex = $regex['regex'] ?? null; + if (is_array($regex)) { + $regex = $regex['regex'] ?? null; + } + if (! is_string($regex) || $regex === '') { + throw new InvalidArgumentException('Option "regex" must be a non-empty string'); + } + ErrorHandler::start(); $result = preg_match($regex, ''); $error = ErrorHandler::stop(); @@ -47,13 +54,16 @@ public function __construct(iterable $regex) /** * Returns TRUE to accept the message, FALSE to block it. + * + * @param array $event */ public function filter(array $event): bool { - $message = $event['message']; - if (is_array($event['message'])) { + $message = $event['message'] ?? ''; + if (is_array($message)) { $message = var_export($message, true); } - return preg_match($this->regex, $message) > 0; + + return preg_match($this->regex, is_scalar($message) ? (string) $message : '') > 0; } } diff --git a/src/Filter/SuppressFilter.php b/src/Filter/SuppressFilter.php index 51380bd..cd199d4 100644 --- a/src/Filter/SuppressFilter.php +++ b/src/Filter/SuppressFilter.php @@ -19,6 +19,8 @@ class SuppressFilter implements FilterInterface /** * This is a simple boolean filter. + * + * @param bool|iterable $suppress */ public function __construct(bool|iterable $suppress = false) { @@ -50,6 +52,8 @@ public function suppress(bool $suppress): void /** * Returns TRUE to accept the message, FALSE to block it. + * + * @param array $event */ public function filter(array $event): bool { diff --git a/src/Filter/Validator.php b/src/Filter/Validator.php index 30f6ff3..8433de3 100644 --- a/src/Filter/Validator.php +++ b/src/Filter/Validator.php @@ -4,48 +4,68 @@ namespace Dot\Log\Filter; +use Closure; use Dot\Log\Exception\InvalidArgumentException; -use Laminas\Validator\ValidatorInterface as LaminasValidator; use Traversable; -use function gettype; +use function get_debug_type; use function is_array; use function is_object; use function iterator_to_array; +use function method_exists; use function sprintf; +/** + * Accepts a log event when the validator accepts its message. + * + * The validator is any object with an isValid(mixed $value): bool method, for example a + * Laminas\Validator\ValidatorInterface implementation. dot-log does not require laminas/laminas-validator. + */ class Validator implements FilterInterface { - /** - * Regex to match - */ - protected LaminasValidator $validator; + protected object $validator; + + /** @var Closure(mixed): mixed */ + private Closure $isValid; /** - * Filter out any log messages not matching the validator + * @param iterable|object $validator a validator, or options with the key "validator" */ - public function __construct(iterable|LaminasValidator $validator) + public function __construct(iterable|object $validator) { - if ($validator instanceof Traversable && ! $validator instanceof LaminasValidator) { - $validator = iterator_to_array($validator); + if (! self::isValidator($validator)) { + if ($validator instanceof Traversable) { + $validator = iterator_to_array($validator); + } + if (is_array($validator)) { + $validator = $validator['validator'] ?? null; + } } - if (is_array($validator)) { - $validator = $validator['validator'] ?? null; - } - if (! $validator instanceof LaminasValidator) { + + if (! is_object($validator) || ! method_exists($validator, 'isValid')) { throw new InvalidArgumentException(sprintf( - 'Parameter of type %s is invalid; must implement Laminas\Validator\ValidatorInterface', - is_object($validator) ? $validator::class : gettype($validator) + 'Parameter of type %s is invalid; must be an object with an isValid() method,' + . ' such as a Laminas\Validator\ValidatorInterface', + get_debug_type($validator) )); } + $this->validator = $validator; + $this->isValid = $validator->isValid(...); } /** * Returns TRUE to accept the message, FALSE to block it. + * + * @param array $event */ public function filter(array $event): bool { - return $this->validator->isValid($event['message']); + return (bool) ($this->isValid)($event['message'] ?? null); + } + + private static function isValidator(mixed $value): bool + { + return is_object($value) && method_exists($value, 'isValid'); } } diff --git a/src/Formatter/AbstractFormatter.php b/src/Formatter/AbstractFormatter.php new file mode 100644 index 0000000..7324142 --- /dev/null +++ b/src/Formatter/AbstractFormatter.php @@ -0,0 +1,129 @@ +|null $dateTimeFormat + */ + public function __construct(string|iterable|null $dateTimeFormat = null) + { + if ($dateTimeFormat instanceof Traversable) { + $dateTimeFormat = iterator_to_array($dateTimeFormat); + } + + if (is_array($dateTimeFormat)) { + $dateTimeFormat = $dateTimeFormat['dateTimeFormat'] ?? null; + } + + if (is_string($dateTimeFormat)) { + $this->dateTimeFormat = $dateTimeFormat; + } + } + + /** + * Normalizes every value of the event. The "extra" key is kept as an array. + * + * @param array $event + * @return array + */ + public function normalizeEvent(array $event): array + { + foreach ($event as $key => $value) { + if ('extra' === $key && is_array($value)) { + $event[$key] = $this->normalizeEvent($value); + } else { + $event[$key] = $this->normalize($value); + } + } + + return $event; + } + + /** + * Normalize all non-scalar data types (except null) into a string value + */ + protected function normalize(mixed $value): bool|float|int|string|null + { + if (is_scalar($value) || null === $value) { + return $value; + } + + if ($value instanceof DateTimeInterface) { + return $value->format($this->getDateTimeFormat()); + } + + if ($value instanceof Traversable) { + return (string) json_encode(iterator_to_array($value), static::JSON_FLAGS); + } + + if (is_array($value)) { + return (string) json_encode($value, static::JSON_FLAGS); + } + + if (is_resource($value)) { + return sprintf('resource(%s)', get_resource_type($value)); + } + + if (is_object($value)) { + if ($value instanceof Stringable) { + return (string) $value; + } + + return sprintf('object(%s) %s', $value::class, (string) json_encode($value, static::JSON_FLAGS)); + } + + return gettype($value); + } + + public function getDateTimeFormat(): string + { + return $this->dateTimeFormat; + } + + public function setDateTimeFormat(string $dateTimeFormat): static + { + $this->dateTimeFormat = $dateTimeFormat; + return $this; + } +} diff --git a/src/Formatter/Base.php b/src/Formatter/Base.php deleted file mode 100644 index 428f9ae..0000000 --- a/src/Formatter/Base.php +++ /dev/null @@ -1,127 +0,0 @@ -dateTimeFormat = $dateTimeFormat; - } - } - - /** - * Formats data to be written by the writer. - * - * @psalm-suppress InvalidReturnType - * @psalm-suppress InvalidReturnStatement - */ - public function format(iterable $event): iterable|string - { - foreach ($event as $key => $value) { - // Keep extra as an array - if ('extra' === $key && is_array($value)) { - $event[$key] = self::format($value); - } else { - $event[$key] = $this->normalize($value); - } - } - - return $event; - } - - /** - * Normalize all non-scalar data types (except null) in a string value - */ - protected function normalize(mixed $value): mixed - { - if (is_scalar($value) || null === $value) { - return $value; - } - - // better readable JSON - static $jsonFlags; - if ($jsonFlags === null) { - $jsonFlags = 0; - $jsonFlags |= defined('JSON_UNESCAPED_SLASHES') ? JSON_UNESCAPED_SLASHES : 0; - $jsonFlags |= defined('JSON_UNESCAPED_UNICODE') ? JSON_UNESCAPED_UNICODE : 0; - } - - // Error suppression is used in several of these cases as a fix for each of - // #5383 and #4616. Without it, #4616 fails whenever recursion occurs during - // json_encode() operations; usage of a dedicated error handler callback - // causes #5383 to fail when the Logger is being used as an error handler. - // The only viable solution here is error suppression, ugly as it may be. - if ($value instanceof DateTime) { - $value = $value->format($this->getDateTimeFormat()); - } elseif ($value instanceof Traversable) { - $value = json_encode(iterator_to_array($value), $jsonFlags); - } elseif (is_array($value)) { - $value = json_encode($value, $jsonFlags); - } elseif (is_object($value) && ! method_exists($value, '__toString')) { - $value = sprintf('object(%s) %s', $value::class, json_encode($value)); - } elseif (is_resource($value)) { - $value = sprintf('resource(%s)', get_resource_type($value)); - } elseif (! is_object($value)) { - $value = gettype($value); - } - - return (string) $value; - } - - /** - * {@inheritDoc} - */ - public function getDateTimeFormat(): string - { - return $this->dateTimeFormat; - } - - /** - * {@inheritDoc} - */ - public function setDateTimeFormat(string $dateTimeFormat): static - { - $this->dateTimeFormat = $dateTimeFormat; - return $this; - } -} diff --git a/src/Formatter/FormatterInterface.php b/src/Formatter/FormatterInterface.php index 7b46042..0a24c48 100644 --- a/src/Formatter/FormatterInterface.php +++ b/src/Formatter/FormatterInterface.php @@ -9,17 +9,16 @@ interface FormatterInterface /** * Default format specifier for DateTime objects is ISO 8601 * - * @see http://php.net/manual/en/function.date.php + * @see https://www.php.net/manual/en/datetime.format.php */ public const DEFAULT_DATETIME_FORMAT = 'c'; /** - * Formats data into a single line to be written by the writer. + * Formats a log event into a single line to be written by the writer. * - * @return string|array Either a formatted line to write to the log, or the - * updated event information to provide to the writer. + * @param array $event */ - public function format(iterable $event): iterable|string; + public function format(array $event): string; /** * Get the format specifier for DateTime objects @@ -29,7 +28,7 @@ public function getDateTimeFormat(): string; /** * Set the format specifier for DateTime objects * - * @see http://php.net/manual/en/function.date.php + * @see https://www.php.net/manual/en/datetime.format.php */ public function setDateTimeFormat(string $dateTimeFormat): static; } diff --git a/src/Formatter/Json.php b/src/Formatter/Json.php index 9713567..7ed57b8 100644 --- a/src/Formatter/Json.php +++ b/src/Formatter/Json.php @@ -4,52 +4,54 @@ namespace Dot\Log\Formatter; -use DateTime; +use DateTimeInterface; +use function array_walk_recursive; use function json_encode; -use const JSON_NUMERIC_CHECK; +use const JSON_INVALID_UTF8_SUBSTITUTE; +use const JSON_PARTIAL_OUTPUT_ON_ERROR; use const JSON_PRESERVE_ZERO_FRACTION; use const JSON_UNESCAPED_SLASHES; use const JSON_UNESCAPED_UNICODE; class Json implements FormatterInterface { + public const JSON_FLAGS = JSON_UNESCAPED_SLASHES + | JSON_UNESCAPED_UNICODE + | JSON_PRESERVE_ZERO_FRACTION + | JSON_INVALID_UTF8_SUBSTITUTE + | JSON_PARTIAL_OUTPUT_ON_ERROR; + /** * Format specifier for DateTime objects in event data (default: ISO 8601) * - * @see http://php.net/manual/en/function.date.php + * @see https://www.php.net/manual/en/datetime.format.php */ protected string $dateTimeFormat = self::DEFAULT_DATETIME_FORMAT; /** - * Formats data into a single line to be written by the writer. + * Formats data into a single line of JSON. Dates anywhere in the event use the configured date format. * - * @psalm-suppress InvalidArrayAccess + * @param array $event */ - public function format(iterable $event): string + public function format(array $event): string { - if (isset($event['timestamp']) && $event['timestamp'] instanceof DateTime) { - $event['timestamp'] = $event['timestamp']->format($this->getDateTimeFormat()); - } - - return (string) json_encode( - $event, - JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK | JSON_PRESERVE_ZERO_FRACTION - ); + $dateTimeFormat = $this->getDateTimeFormat(); + array_walk_recursive($event, static function (mixed &$value) use ($dateTimeFormat): void { + if ($value instanceof DateTimeInterface) { + $value = $value->format($dateTimeFormat); + } + }); + + return (string) json_encode($event, self::JSON_FLAGS); } - /** - * {@inheritDoc} - */ public function getDateTimeFormat(): string { return $this->dateTimeFormat; } - /** - * {@inheritDoc} - */ public function setDateTimeFormat(string $dateTimeFormat): static { $this->dateTimeFormat = $dateTimeFormat; diff --git a/src/Formatter/Simple.php b/src/Formatter/Simple.php index 3c8771c..97965d0 100644 --- a/src/Formatter/Simple.php +++ b/src/Formatter/Simple.php @@ -7,16 +7,14 @@ use Dot\Log\Exception\InvalidArgumentException; use Traversable; -use function array_key_exists; -use function count; use function is_array; use function is_string; use function iterator_to_array; use function rtrim; +use function str_contains; use function str_replace; -use function strpos; -class Simple extends Base +class Simple extends AbstractFormatter { public const DEFAULT_FORMAT = '%timestamp% %levelName% (%level%): %message% %extra%'; @@ -25,6 +23,11 @@ class Simple extends Base */ protected string $format; + /** + * @param string|iterable|null $format a format, or options with the keys "format" and + * "dateTimeFormat" + * @param string|iterable|null $dateTimeFormat + */ public function __construct(iterable|string|null $format = null, string|iterable|null $dateTimeFormat = null) { if ($format instanceof Traversable) { @@ -47,14 +50,18 @@ public function __construct(iterable|string|null $format = null, string|iterable /** * Formats data into a single line to be written by the writer. + * + * @param array $event */ - public function format(iterable $event): array|string + public function format(array $event): string { $output = $this->format; - $event = parent::format($event); + // Events from Dot\Log\Logger carry no "extra" key: print nothing rather than a literal "%extra%" + $event += ['extra' => []]; + $event = $this->normalizeEvent($event); foreach ($event as $name => $value) { - if ('extra' === $name && is_array($value) && count($value)) { + if ('extra' === $name && is_array($value) && $value !== []) { $value = $this->normalize($value); } elseif ('extra' === $name) { // Don't print an empty array @@ -63,12 +70,10 @@ public function format(iterable $event): array|string $output = str_replace("%$name%", (string) $value, $output); } - if ( - array_key_exists('extra', $event) && empty($event['extra']) - && false !== strpos($this->format, '%extra%') - ) { + if ($event['extra'] === [] && str_contains($this->format, '%extra%')) { $output = rtrim($output, ' '); } + return $output; } } diff --git a/src/Logger.php b/src/Logger.php index b47cc69..4762424 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -4,7 +4,9 @@ namespace Dot\Log; -use DateTime; +use Closure; +use DateTimeImmutable; +use DateTimeInterface; use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Exception\RuntimeException; use Dot\Log\Manager\ProcessorPluginManager; @@ -13,25 +15,31 @@ use Dot\Log\Writer\WriterInterface; use ErrorException; use Exception; -use Laminas\ServiceManager\ServiceManager; -use Laminas\Stdlib\ArrayUtils; use Laminas\Stdlib\SplPriorityQueue; use Psr\Container\ContainerExceptionInterface; use Psr\Log\AbstractLogger; use Psr\Log\LogLevel; use Stringable; +use Throwable; use Traversable; use function array_reverse; use function array_search; +use function class_exists; use function count; use function error_get_last; use function error_reporting; -use function gettype; +use function floor; +use function get_debug_type; use function in_array; use function is_array; +use function is_bool; +use function is_int; use function is_numeric; +use function is_object; +use function is_scalar; use function is_string; +use function iterator_to_array; use function preg_match_all; use function register_shutdown_function; use function restore_error_handler; @@ -75,6 +83,8 @@ class Logger extends AbstractLogger /** * Map native PHP errors to level + * + * @var array */ public static array $errorLevelMap = [ E_NOTICE => self::NOTICE, @@ -109,7 +119,9 @@ class Logger extends AbstractLogger protected static bool $registeredExceptionHandler = false; /** - * List of level code => level (short) name + * List of PSR-3 level name => level code + * + * @var array */ protected array $levels = [ LogLevel::EMERGENCY => self::EMERG, @@ -122,8 +134,10 @@ class Logger extends AbstractLogger LogLevel::DEBUG => self::DEBUG, ]; + /** @var SplPriorityQueue */ protected SplPriorityQueue $writers; + /** @var SplPriorityQueue */ protected SplPriorityQueue $processors; protected ?WriterPluginManager $writerPlugins = null; @@ -134,10 +148,14 @@ class Logger extends AbstractLogger * Constructor * * Set options for a logger. Accepted options are: - * - writers: array of writers to add to this logger - * - exceptionhandler: if true, register this logger as exceptionhandler - * - errorhandler: if true, register this logger as errorhandler + * - writers: list of writers, each [name, level|priority, options]; level/priority defaults to 1 + * - processors: list of processors, each [name, level|priority, options]; level/priority defaults to 1 + * - writer_plugin_manager / processor_plugin_manager: plugin manager instances + * - exceptionhandler: if true, register this logger as exception handler + * - errorhandler: if true, register this logger as error handler + * - fatal_error_shutdownfunction: if true, register a shutdown function logging fatal errors * + * @param iterable|null $options * @throws ContainerExceptionInterface */ public function __construct(?iterable $options = null) @@ -146,10 +164,10 @@ public function __construct(?iterable $options = null) $this->processors = new SplPriorityQueue(); if ($options instanceof Traversable) { - $options = ArrayUtils::iteratorToArray((array) $options); + $options = iterator_to_array($options); } - if (! $options) { + if ($options === null || $options === []) { return; } @@ -171,27 +189,15 @@ public function __construct(?iterable $options = null) if (isset($options['writers']) && is_array($options['writers'])) { foreach ($options['writers'] as $writer) { - if (! isset($writer['name'])) { - throw new InvalidArgumentException('Options must contain a name for the writer'); - } - - $level = $writer['level'] ?? null; - $writerOptions = $writer['options'] ?? null; - - $this->addWriter($writer['name'], $level, $writerOptions); + [$name, $level, $writerOptions] = $this->readPluginSpec($writer, 'writer'); + $this->addWriter($name, $level, $writerOptions); } } if (isset($options['processors']) && is_array($options['processors'])) { foreach ($options['processors'] as $processor) { - if (! isset($processor['name'])) { - throw new InvalidArgumentException('Options must contain a name for the processor'); - } - - $level = $processor['level'] ?? null; - $processorOptions = $processor['options'] ?? null; - - $this->addProcessor($processor['name'], $level, $processorOptions); + [$name, $level, $processorOptions] = $this->readPluginSpec($processor, 'processor'); + $this->addProcessor($name, $level, $processorOptions); } } @@ -209,11 +215,11 @@ public function __construct(?iterable $options = null) } /** - * Shutdown all writers + * Shutdown all writers. Iterates a copy: iterating an SplPriorityQueue removes its elements. */ public function __destruct() { - foreach ($this->writers as $writer) { + foreach ($this->writers->toArray() as $writer) { try { $writer->shutdown(); } catch (Exception) { @@ -221,10 +227,10 @@ public function __destruct() } } - public function getWriterPluginManager(): ?WriterPluginManager + public function getWriterPluginManager(): WriterPluginManager { if (null === $this->writerPlugins) { - $this->setWriterPluginManager(new WriterPluginManager(new ServiceManager())); + $this->writerPlugins = new WriterPluginManager(); } return $this->writerPlugins; } @@ -238,16 +244,19 @@ public function setWriterPluginManager(WriterPluginManager $writerPlugins): stat /** * Get a writer instance * + * @param array|null $options * @throws ContainerExceptionInterface */ - public function writerPlugin(string $name, ?array $options = null): ?WriterInterface + public function writerPlugin(string $name, ?array $options = null): WriterInterface { - return $this->getWriterPluginManager()?->build($name, $options); + return $this->getWriterPluginManager()->build($name, $options); } /** * Add a writer to a logger * + * @param int $level the writer priority: writers with a higher value run first + * @param array|null $options * @throws ContainerExceptionInterface */ public function addWriter(WriterInterface|string $writer, int $level = 1, ?array $options = null): static @@ -261,17 +270,23 @@ public function addWriter(WriterInterface|string $writer, int $level = 1, ?array return $this; } + /** + * @return SplPriorityQueue + */ public function getWriters(): SplPriorityQueue { return $this->writers; } + /** + * @param SplPriorityQueue $writers + */ public function setWriters(SplPriorityQueue $writers): static { foreach ($writers->toArray() as $writer) { - if (! $writer instanceof Writer\WriterInterface) { + if (! $writer instanceof WriterInterface) { throw new InvalidArgumentException( - 'Writers must be a SplPriorityQueue of Laminas\Log\Writer' + 'Writers must be a SplPriorityQueue of ' . WriterInterface::class ); } } @@ -279,27 +294,27 @@ public function setWriters(SplPriorityQueue $writers): static return $this; } - public function getProcessorPluginManager(): ?ProcessorPluginManager + public function getProcessorPluginManager(): ProcessorPluginManager { if (null === $this->processorPlugins) { - $this->setProcessorPluginManager(new ProcessorPluginManager(new ServiceManager())); + $this->processorPlugins = new ProcessorPluginManager(); } return $this->processorPlugins; } /** - * @param class-string|ProcessorPluginManager $plugins + * @param string|ProcessorPluginManager $plugins a ProcessorPluginManager instance or class name */ public function setProcessorPluginManager(string|ProcessorPluginManager $plugins): static { - if (is_string($plugins)) { + if (is_string($plugins) && class_exists($plugins)) { $plugins = new $plugins(); } if (! $plugins instanceof ProcessorPluginManager) { throw new InvalidArgumentException(sprintf( - 'processor plugin manager must extend %s\ProcessorPluginManager; received %s', - __NAMESPACE__, - $plugins::class + 'Processor plugin manager must extend %s; received %s', + ProcessorPluginManager::class, + get_debug_type($plugins) )); } @@ -308,14 +323,17 @@ public function setProcessorPluginManager(string|ProcessorPluginManager $plugins } /** + * @param array|null $options * @throws ContainerExceptionInterface */ - public function processorPlugin(string $name, ?array $options = null): ?ProcessorInterface + public function processorPlugin(string $name, ?array $options = null): ProcessorInterface { - return $this->getProcessorPluginManager()?->build($name, $options); + return $this->getProcessorPluginManager()->build($name, $options); } /** + * @param int $level the processor priority: processors with a higher value run first + * @param array|null $options * @throws ContainerExceptionInterface */ public function addProcessor( @@ -332,86 +350,142 @@ public function addProcessor( return $this; } + /** + * @return SplPriorityQueue + */ public function getProcessors(): SplPriorityQueue { return $this->processors; } + /** + * @param int|string $level a level code (0 to 7) or a PSR-3 level name + * @param iterable $context + */ public function log(mixed $level, string|Stringable $message, iterable $context = []): void { - if (! is_numeric($level)) { - if (isset($this->levels[$level])) { - $level = $this->levels[$level]; - } - } - - if (($level < 0) || ($level >= count($this->levels))) { - throw new InvalidArgumentException(sprintf( - '$level must be an integer >= 0 and < %d; received %s', - count($this->levels), - var_export($level, true) - )); - } + $level = $this->normalizeLevel($level); if ($context instanceof Traversable) { - $context = ArrayUtils::iteratorToArray((array) $context); + $context = iterator_to_array($context); } if ($this->writers->count() === 0) { throw new RuntimeException('No log writer specified'); } - $timestamp = new DateTime(); - - $message = $this->handlePlaceholders((string) $message, $context); - $event = [ - 'timestamp' => $timestamp, + 'timestamp' => new DateTimeImmutable(), 'level' => $level, - 'levelName' => array_search((int) $level, $this->levels, true), - 'message' => $message, + 'levelName' => array_search($level, $this->levels, true), + 'message' => $this->handlePlaceholders((string) $message, $context), 'context' => $context, ]; - /** @var ProcessorInterface $processor */ foreach ($this->processors->toArray() as $processor) { $event = $processor->process($event); } - /** @var WriterInterface $writer */ foreach ($this->writers->toArray() as $writer) { $writer->write($event); } } + /** + * Replaces {placeholder} with the matching context value. Null and missing values are left in place. + * + * @param array $context + */ protected function handlePlaceholders(string $message, array $context): string { - if (preg_match_all('/\{([\w.]+)}/', $message, $matches)) { - $replacements = []; - foreach ($matches[1] as $match) { - if (! isset($context[$match])) { - continue; - } - - $placeholderValue = $context[$match]; + if (! preg_match_all('/\{([\w.]+)}/', $message, $matches)) { + return $message; + } - if (is_string($placeholderValue) || is_numeric($placeholderValue)) { - $replacements["{{$match}}"] = (string) $placeholderValue; - } else { - $replacements["{{$match}}"] = gettype($placeholderValue); - } + $replacements = []; + foreach ($matches[1] as $match) { + if (! isset($context[$match])) { + continue; } - $message = strtr($message, $replacements); + $replacements['{' . $match . '}'] = self::placeholderValue($context[$match]); } - return $message; + return strtr($message, $replacements); + } + + /** + * String representation of a context value used in a placeholder. + */ + public static function placeholderValue(mixed $value): string + { + return match (true) { + is_bool($value) => $value ? 'true' : 'false', + is_scalar($value), $value instanceof Stringable => (string) $value, + $value instanceof DateTimeInterface => $value->format(DateTimeInterface::RFC3339), + is_object($value) => '[object ' . $value::class . ']', + default => '[' . get_debug_type($value) . ']', + }; + } + + protected function normalizeLevel(mixed $level): int + { + if (is_string($level) && isset($this->levels[$level])) { + $level = $this->levels[$level]; + } elseif (is_numeric($level) && floor((float) $level) === (float) $level) { + $level = (int) $level; + } + + if (! is_int($level) || $level < 0 || $level >= count($this->levels)) { + throw new InvalidArgumentException(sprintf( + '$level must be an integer >= 0 and < %d; received %s', + count($this->levels), + var_export($level, true) + )); + } + + return $level; + } + + /** + * Reads [name, level|priority, options] of a writer or processor from the logger options. + * + * @return array{0: string, 1: int, 2: array|null} + */ + private function readPluginSpec(mixed $spec, string $type): array + { + if ($spec instanceof Traversable) { + $spec = iterator_to_array($spec); + } + + if (! is_array($spec) || ! isset($spec['name']) || ! is_string($spec['name'])) { + throw new InvalidArgumentException('Options must contain a name for the ' . $type); + } + + $level = $spec['level'] ?? $spec['priority'] ?? 1; + if (! is_numeric($level)) { + throw new InvalidArgumentException(sprintf( + 'The %s "%s" level must be an integer; received %s', + $type, + $spec['name'], + get_debug_type($level) + )); + } + + $options = $spec['options'] ?? null; + if ($options instanceof Traversable) { + $options = iterator_to_array($options); + } + + return [$spec['name'], (int) $level, is_array($options) ? $options : null]; } /** * Register logging system as an error handler to log PHP errors * - * @link http://www.php.net/manual/function.set-error-handler.php + * Returns the previous error handler (null when there was none), or false when already registered. + * + * @link https://www.php.net/manual/function.set-error-handler.php */ public static function registerErrorHandler(Logger $logger, bool $continueNativeHandler = false): bool|null|callable { @@ -420,31 +494,41 @@ public static function registerErrorHandler(Logger $logger, bool $continueNative return false; } - $errorLevelMap = static::$errorLevelMap; + $previous = set_error_handler(static::createErrorHandler($logger, $continueNativeHandler)); - $previous = set_error_handler( - static function ($level, $message, $file, $line) use ($logger, $errorLevelMap, $continueNativeHandler) { - $iniLevel = error_reporting(); - - if ($iniLevel & $level) { - if (isset($errorLevelMap[$level])) { - $level = $errorLevelMap[$level]; - } else { - $level = Logger::INFO; - } - $logger->log($level, $message, [ - 'errno' => $level, - 'file' => $file, - 'line' => $line, - ]); - } + static::$registeredErrorHandler = true; + return $previous; + } + + /** + * The error handler registered by registerErrorHandler(). It logs errors included in error_reporting(). + * + * @return Closure(int, string, string, int): bool + */ + public static function createErrorHandler(Logger $logger, bool $continueNativeHandler = false): Closure + { + $errorLevelMap = static::$errorLevelMap; - return ! $continueNativeHandler; + return static function ( + int $errno, + string $message, + string $file, + int $line + ) use ( + $logger, + $errorLevelMap, + $continueNativeHandler + ): bool { + if (error_reporting() & $errno) { + $logger->log($errorLevelMap[$errno] ?? self::INFO, $message, [ + 'errno' => $errno, + 'file' => $file, + 'line' => $line, + ]); } - ); - static::$registeredErrorHandler = true; - return $previous; + return ! $continueNativeHandler; + }; } public static function unregisterErrorHandler(): void @@ -489,7 +573,7 @@ public static function registerFatalErrorShutdownFunction(Logger $logger): bool } $logger->log( - $errorLevelMap[$error['type']], + $errorLevelMap[$error['type']] ?? self::ERR, $error['message'], [ 'file' => $error['file'], @@ -506,7 +590,7 @@ public static function registerFatalErrorShutdownFunction(Logger $logger): bool /** * Register a logging system as an exception handler to log PHP exceptions * - * @link http://www.php.net/manual/en/function.set-exception-handler.php + * @link https://www.php.net/manual/en/function.set-exception-handler.php */ public static function registerExceptionHandler(Logger $logger): bool { @@ -515,38 +599,47 @@ public static function registerExceptionHandler(Logger $logger): bool return false; } + set_exception_handler(static::createExceptionHandler($logger)); + + static::$registeredExceptionHandler = true; + return true; + } + + /** + * The exception handler registered by registerExceptionHandler(). It logs the exception and every previous + * exception, the innermost first. + * + * @return Closure(Throwable): void + */ + public static function createExceptionHandler(Logger $logger): Closure + { $errorLevelMap = static::$errorLevelMap; - set_exception_handler(static function ($exception) use ($logger, $errorLevelMap) { + return static function (Throwable $exception) use ($logger, $errorLevelMap): void { $logMessages = []; do { - $level = Logger::ERR; + $level = self::ERR; if ($exception instanceof ErrorException && isset($errorLevelMap[$exception->getSeverity()])) { $level = $errorLevelMap[$exception->getSeverity()]; } - $extra = [ - 'file' => $exception->getFile(), - 'line' => $exception->getLine(), - 'trace' => $exception->getTrace(), - ]; - $logMessages[] = [ 'level' => $level, 'message' => $exception->getMessage(), - 'extra' => $extra, + 'extra' => [ + 'file' => $exception->getFile(), + 'line' => $exception->getLine(), + 'trace' => $exception->getTrace(), + ], ]; $exception = $exception->getPrevious(); - } while ($exception); + } while ($exception !== null); foreach (array_reverse($logMessages) as $logMessage) { $logger->log($logMessage['level'], $logMessage['message'], $logMessage['extra']); } - }); - - static::$registeredExceptionHandler = true; - return true; + }; } public static function unregisterExceptionHandler(): void diff --git a/src/LoggerServiceFactory.php b/src/LoggerServiceFactory.php index 51bc7cd..7fa86e9 100644 --- a/src/LoggerServiceFactory.php +++ b/src/LoggerServiceFactory.php @@ -6,31 +6,45 @@ use ArrayAccess; use Dot\Log\Exception\InvalidArgumentException; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Factory\FactoryInterface; +use Dot\Log\Manager\FilterPluginManager; +use Dot\Log\Manager\FormatterPluginManager; +use Dot\Log\Manager\ProcessorPluginManager; +use Dot\Log\Manager\WriterPluginManager; use Psr\Container\ContainerExceptionInterface; use Psr\Container\ContainerInterface; use Psr\Container\NotFoundExceptionInterface; +use Traversable; -use function gettype; +use function get_debug_type; use function is_array; -use function is_iterable; -use function is_object; use function is_string; use function iterator_to_array; +use function sprintf; -class LoggerServiceFactory implements FactoryInterface +/** + * Creates the logger registered as Dot\Log\Logger, configured under the "log" config key. + * + * Works with any PSR-11 container that calls factories as $factory($container, $requestedName). + */ +class LoggerServiceFactory { /** - * @param string $requestedName * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ - public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null): Logger + public function __invoke(ContainerInterface $container, string $requestedName = Logger::class): Logger { - // Configure the logger - $config = $container->get('config'); + $config = $this->getApplicationConfig($container); $logConfig = $config['log'] ?? []; + if ($logConfig instanceof Traversable) { + $logConfig = iterator_to_array($logConfig); + } + if (! is_array($logConfig)) { + throw new InvalidArgumentException(sprintf( + 'config "log" must be an array; %s provided', + get_debug_type($logConfig) + )); + } $this->processConfig($logConfig, $container); @@ -38,57 +52,117 @@ public function __invoke(ContainerInterface $container, $requestedName, ?array $ } /** - * Process and return the configuration from the container. + * Injects the plugin managers and validates the writers. + * + * Plugin managers named in the logger config are fetched from the container. Otherwise, they are built from the + * "dot_log" config keys "writer_manager", "filter_manager", "formatter_manager" and "processor_manager". + * + * @param array $config + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ protected function processConfig(array &$config, ContainerInterface $services): void { - if ( - isset($config['writer_plugin_manager']) - && is_string($config['writer_plugin_manager']) - && $services->has($config['writer_plugin_manager']) - ) { - $config['writer_plugin_manager'] = $services->get($config['writer_plugin_manager']); + $writerManager = $this->fromContainer($config['writer_plugin_manager'] ?? null, $services); + if (! $writerManager instanceof WriterPluginManager) { + $writerManager = $this->createWriterPluginManager($services); } + $config['writer_plugin_manager'] = $writerManager; - if ( - (! isset($config['writer_plugin_manager']) - || ! $config['writer_plugin_manager'] instanceof AbstractPluginManager) - && $services->has('LogWriterManager') - ) { - $config['writer_plugin_manager'] = $services->get('LogWriterManager'); + $processorManager = $this->fromContainer($config['processor_plugin_manager'] ?? null, $services); + if (! $processorManager instanceof ProcessorPluginManager) { + $processorManager = new ProcessorPluginManager( + $services, + $this->getManagerConfig($services, 'processor_manager') + ); } + $config['processor_plugin_manager'] = $processorManager; - if ( - isset($config['processor_plugin_manager']) - && is_string($config['processor_plugin_manager']) - && $services->has($config['processor_plugin_manager']) - ) { - $config['processor_plugin_manager'] = $services->get($config['processor_plugin_manager']); - } - - if ( - (! isset($config['processor_plugin_manager']) - || ! $config['processor_plugin_manager'] instanceof AbstractPluginManager) - && $services->has('LogProcessorManager') - ) { - $config['processor_plugin_manager'] = $services->get('LogProcessorManager'); + if (! isset($config['writers'])) { + return; } - if (! isset($config['writers']) || ! is_iterable($config['writers'])) { - return; + if ($config['writers'] instanceof Traversable) { + $config['writers'] = iterator_to_array($config['writers']); } if (! is_array($config['writers'])) { - $config['writers'] = iterator_to_array($config['writers']); + unset($config['writers']); + return; } foreach ($config['writers'] as $writerConfig) { if (! is_array($writerConfig) && ! $writerConfig instanceof ArrayAccess) { - $type = is_object($writerConfig) ? $writerConfig::class : gettype($writerConfig); throw new InvalidArgumentException( - 'config log.writers[] must contain array or ArrayAccess, ' . $type . ' provided' + 'config log.writers[] must contain array or ArrayAccess, ' + . get_debug_type($writerConfig) . ' provided' ); } } } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + protected function createWriterPluginManager(ContainerInterface $services): WriterPluginManager + { + return new WriterPluginManager( + $services, + $this->getManagerConfig($services, 'writer_manager'), + new FilterPluginManager($services, $this->getManagerConfig($services, 'filter_manager')), + new FormatterPluginManager($services, $this->getManagerConfig($services, 'formatter_manager')), + ); + } + + /** + * @return array + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + protected function getApplicationConfig(ContainerInterface $container): array + { + if (! $container->has('config')) { + return []; + } + + $config = $container->get('config'); + if ($config instanceof Traversable) { + $config = iterator_to_array($config); + } + + return is_array($config) ? $config : []; + } + + /** + * @return array + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + protected function getManagerConfig(ContainerInterface $container, string $key): array + { + $dotLog = $this->getApplicationConfig($container)['dot_log'] ?? []; + if (! is_array($dotLog) || ! isset($dotLog[$key])) { + return []; + } + + if (! is_array($dotLog[$key])) { + throw new InvalidArgumentException(sprintf('config "dot_log.%s" must be an array', $key)); + } + + return $dotLog[$key]; + } + + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + private function fromContainer(mixed $service, ContainerInterface $services): mixed + { + if (is_string($service) && $services->has($service)) { + return $services->get($service); + } + + return $service; + } } diff --git a/src/Manager/AbstractPluginManager.php b/src/Manager/AbstractPluginManager.php new file mode 100644 index 0000000..bd4204c --- /dev/null +++ b/src/Manager/AbstractPluginManager.php @@ -0,0 +1,195 @@ + plugin name => class name or another alias + * - factories: array class name => factory. + * A factory is called as $factory(ContainerInterface $container, string $requestedName, ?array $options) + * + * @template-covariant T of object + */ +abstract class AbstractPluginManager implements ContainerInterface +{ + /** @var array */ + protected array $aliases = []; + + /** @var array */ + protected array $factories = []; + + /** @var class-string */ + protected string $instanceOf; + + /** + * @param array $config + */ + public function __construct(protected ?ContainerInterface $container = null, array $config = []) + { + $this->configure($config); + } + + /** + * @param array $config + */ + public function configure(array $config): static + { + if (isset($config['aliases'])) { + if (! is_array($config['aliases'])) { + throw new InvalidArgumentException('Plugin manager "aliases" must be an array'); + } + foreach ($config['aliases'] as $alias => $target) { + if (! is_string($alias) || ! is_string($target)) { + throw new InvalidArgumentException('Plugin manager aliases must map strings to strings'); + } + $this->aliases[$alias] = $target; + } + } + + if (isset($config['factories'])) { + if (! is_array($config['factories'])) { + throw new InvalidArgumentException('Plugin manager "factories" must be an array'); + } + foreach ($config['factories'] as $name => $factory) { + if (! is_string($name) || (! is_string($factory) && ! is_callable($factory))) { + throw new InvalidArgumentException( + 'Plugin manager factories must map strings to a factory class name or a callable' + ); + } + $this->factories[$name] = $factory; + } + } + + return $this; + } + + /** + * Build a new plugin instance. Plugins are never shared. + * + * @param array|null $options + * @return T + * @throws ContainerExceptionInterface + */ + public function build(string $name, ?array $options = null): object + { + $resolved = $this->resolveAlias($name); + + if (array_key_exists($resolved, $this->factories)) { + $factory = $this->factories[$resolved]; + if (is_string($factory) && ! is_callable($factory)) { + if (! class_exists($factory)) { + throw new InvalidArgumentException(sprintf( + 'Factory "%s" for plugin "%s" does not exist', + $factory, + $name + )); + } + $factory = new $factory(); + } + if (! is_callable($factory)) { + throw new InvalidArgumentException(sprintf('Factory for plugin "%s" is not callable', $name)); + } + $instance = $factory($this->getCreationContext(), $resolved, $options); + } elseif (class_exists($resolved)) { + $instance = $options === null ? new $resolved() : new $resolved($options); + } elseif ($this->container !== null && $this->container->has($name)) { + $instance = $this->container->get($name); + } else { + throw new ServiceNotFoundException(sprintf( + 'Unable to resolve plugin "%s" in %s', + $name, + static::class + )); + } + + $this->validate($instance); + + return $instance; + } + + /** + * @return T + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + public function get(string $id): object + { + return $this->build($id); + } + + public function has(string $id): bool + { + $resolved = $this->resolveAlias($id); + + return array_key_exists($resolved, $this->factories) + || class_exists($resolved) + || ($this->container !== null && $this->container->has($id)); + } + + /** + * Validate the plugin is of the expected type. + * + * @phpstan-assert T $instance + */ + public function validate(mixed $instance): void + { + if (! $instance instanceof $this->instanceOf) { + throw new InvalidArgumentException(sprintf( + '%s can only create instances of %s; %s is invalid', + static::class, + $this->instanceOf, + get_debug_type($instance) + )); + } + } + + /** + * The container passed to plugin factories: the application container when one was given, otherwise this manager. + */ + public function getCreationContext(): ContainerInterface + { + return $this->container ?? $this; + } + + protected function resolveAlias(string $name): string + { + $seen = []; + while (true) { + if (isset($this->aliases[$name])) { + $target = $this->aliases[$name]; + } elseif (isset($this->aliases[strtolower($name)])) { + $target = $this->aliases[strtolower($name)]; + } else { + return $name; + } + + if (isset($seen[$target])) { + throw new InvalidArgumentException(sprintf('Circular plugin alias detected for "%s"', $name)); + } + $seen[$target] = true; + $name = $target; + } + } +} diff --git a/src/Manager/FilterPluginManager.php b/src/Manager/FilterPluginManager.php index 85db26a..dedfb96 100644 --- a/src/Manager/FilterPluginManager.php +++ b/src/Manager/FilterPluginManager.php @@ -4,27 +4,21 @@ namespace Dot\Log\Manager; +use Dot\Log\Filter\Callback; use Dot\Log\Filter\FilterInterface; use Dot\Log\Filter\Level; use Dot\Log\Filter\Regex; use Dot\Log\Filter\SuppressFilter; use Dot\Log\Filter\Validator; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; -use Laminas\ServiceManager\Factory\InvokableFactory; - -use function gettype; -use function is_object; -use function sprintf; /** - * @template F of FilterPluginManager - * @extends AbstractPluginManager + * @extends AbstractPluginManager */ class FilterPluginManager extends AbstractPluginManager { - /** @var string[] */ + /** @var array */ protected array $aliases = [ + 'callback' => Callback::class, 'level' => Level::class, 'regex' => Regex::class, 'suppress' => SuppressFilter::class, @@ -32,35 +26,6 @@ class FilterPluginManager extends AbstractPluginManager 'validator' => Validator::class, ]; - /** @inheritDoc */ - protected array $factories = [ - Level::class => InvokableFactory::class, - Regex::class => InvokableFactory::class, - SuppressFilter::class => InvokableFactory::class, - Validator::class => InvokableFactory::class, - ]; - + /** @var class-string */ protected string $instanceOf = FilterInterface::class; - - /** - * Allow many filters of the same type - */ - protected bool $sharedByDefault = false; - - /** - * Validate the plugin is of the expected type. - * - * Validates against `$instanceOf`. - */ - public function validate(mixed $instance): void - { - if (! $instance instanceof $this->instanceOf) { - throw new InvalidServiceException(sprintf( - '%s can only create instances of %s; %s is invalid', - static::class, - $this->instanceOf, - is_object($instance) ? $instance::class : gettype($instance) - )); - } - } } diff --git a/src/Manager/FormatterPluginManager.php b/src/Manager/FormatterPluginManager.php index e22e8ed..c23b4e1 100644 --- a/src/Manager/FormatterPluginManager.php +++ b/src/Manager/FormatterPluginManager.php @@ -5,52 +5,20 @@ namespace Dot\Log\Manager; use Dot\Log\Formatter\FormatterInterface; +use Dot\Log\Formatter\Json; use Dot\Log\Formatter\Simple; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; -use Laminas\ServiceManager\Factory\InvokableFactory; - -use function gettype; -use function is_object; -use function sprintf; /** - * @template F of FormatterPluginManager - * @extends AbstractPluginManager + * @extends AbstractPluginManager */ class FormatterPluginManager extends AbstractPluginManager { - /** @var string[] */ + /** @var array */ protected array $aliases = [ + 'json' => Json::class, 'simple' => Simple::class, ]; - /** @inheritDoc */ - protected array $factories = [ - Simple::class => InvokableFactory::class, - ]; - + /** @var class-string */ protected string $instanceOf = FormatterInterface::class; - - /** - * Allow many formatters of the same type - */ - protected bool $sharedByDefault = false; - - /** - * Validate the plugin is of the expected type. - * - * Validates against `$instanceOf`. - */ - public function validate(mixed $instance): void - { - if (! $instance instanceof $this->instanceOf) { - throw new InvalidServiceException(sprintf( - '%s can only create instances of %s; %s is invalid', - static::class, - $this->instanceOf, - is_object($instance) ? $instance::class : gettype($instance) - )); - } - } } diff --git a/src/Manager/ProcessorPluginManager.php b/src/Manager/ProcessorPluginManager.php index a04fde8..58e7111 100644 --- a/src/Manager/ProcessorPluginManager.php +++ b/src/Manager/ProcessorPluginManager.php @@ -9,21 +9,13 @@ use Dot\Log\Processor\PsrPlaceholder; use Dot\Log\Processor\ReferenceId; use Dot\Log\Processor\RequestId; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; -use Laminas\ServiceManager\Factory\InvokableFactory; - -use function gettype; -use function is_object; -use function sprintf; /** - * @template P of ProcessorPluginManager - * @extends AbstractPluginManager

+ * @extends AbstractPluginManager */ class ProcessorPluginManager extends AbstractPluginManager { - /** @var string[] */ + /** @var array */ protected array $aliases = [ 'backtrace' => Backtrace::class, 'psrplaceholder' => PsrPlaceholder::class, @@ -31,35 +23,6 @@ class ProcessorPluginManager extends AbstractPluginManager 'requestid' => RequestId::class, ]; - /** @inheritDoc */ - protected array $factories = [ - Backtrace::class => InvokableFactory::class, - PsrPlaceholder::class => InvokableFactory::class, - ReferenceId::class => InvokableFactory::class, - RequestId::class => InvokableFactory::class, - ]; - + /** @var class-string */ protected string $instanceOf = ProcessorInterface::class; - - /** - * Allow many processors of the same type - */ - protected bool $sharedByDefault = false; - - /** - * Validate the plugin is of the expected type. - * - * Validates against `$instanceOf`. - */ - public function validate(mixed $instance): void - { - if (! $instance instanceof $this->instanceOf) { - throw new InvalidServiceException(sprintf( - '%s can only create instances of %s; %s is invalid', - static::class, - $this->instanceOf, - is_object($instance) ? $instance::class : gettype($instance) - )); - } - } } diff --git a/src/Manager/WriterPluginManager.php b/src/Manager/WriterPluginManager.php index 5c937eb..436d375 100644 --- a/src/Manager/WriterPluginManager.php +++ b/src/Manager/WriterPluginManager.php @@ -8,20 +8,14 @@ use Dot\Log\Writer\Noop; use Dot\Log\Writer\Stream; use Dot\Log\Writer\WriterInterface; -use Laminas\ServiceManager\AbstractPluginManager; -use Laminas\ServiceManager\Exception\InvalidServiceException; - -use function gettype; -use function is_object; -use function sprintf; +use Psr\Container\ContainerInterface; /** - * @template W of WriterPluginManager - * @extends AbstractPluginManager + * @extends AbstractPluginManager */ class WriterPluginManager extends AbstractPluginManager { - /** @var string[] */ + /** @var array */ protected array $aliases = [ 'noop' => Noop::class, 'stream' => Stream::class, @@ -32,33 +26,44 @@ class WriterPluginManager extends AbstractPluginManager 'laminaslogwriternull' => Noop::class, ]; - /** @inheritDoc */ + /** @var array */ protected array $factories = [ Noop::class => WriterFactory::class, Stream::class => WriterFactory::class, ]; + /** @var class-string */ protected string $instanceOf = WriterInterface::class; /** - * Allow many writers of the same type + * @param array $config */ - protected bool $sharedByDefault = false; + public function __construct( + ?ContainerInterface $container = null, + array $config = [], + protected ?FilterPluginManager $filterPluginManager = null, + protected ?FormatterPluginManager $formatterPluginManager = null, + ) { + parent::__construct($container, $config); + } /** - * Validate the plugin is of the expected type. + * Writers built by this manager share its filter and formatter managers, unless the options name others. * - * Validates against `$instanceOf`. + * @param array|null $options */ - public function validate(mixed $instance): void + public function build(string $name, ?array $options = null): WriterInterface { - if (! $instance instanceof $this->instanceOf) { - throw new InvalidServiceException(sprintf( - '%s can only create instances of %s; %s is invalid', - static::class, - $this->instanceOf, - is_object($instance) ? $instance::class : gettype($instance) - )); + if ($this->filterPluginManager !== null && ! isset($options['filter_manager'])) { + $options = (array) $options; + $options['filter_manager'] = $this->filterPluginManager; } + + if ($this->formatterPluginManager !== null && ! isset($options['formatter_manager'])) { + $options = (array) $options; + $options['formatter_manager'] = $this->formatterPluginManager; + } + + return parent::build($name, $options); } } diff --git a/src/Processor/Backtrace.php b/src/Processor/Backtrace.php index b484284..ab06027 100644 --- a/src/Processor/Backtrace.php +++ b/src/Processor/Backtrace.php @@ -7,35 +7,48 @@ use function array_merge; use function array_shift; use function debug_backtrace; -use function strpos; +use function is_array; +use function is_string; +use function rtrim; +use function str_starts_with; use const DEBUG_BACKTRACE_IGNORE_ARGS; class Backtrace implements ProcessorInterface { /** - * Maximum stack level of backtrace (PHP > 5.4.0) + * Maximum stack level of backtrace */ protected int $traceLimit = 10; /** * Classes within these namespaces in the stack are ignored + * + * @var list */ - protected array $ignoredNamespaces = ['Laminas\\Log']; + protected array $ignoredNamespaces = ['Dot\\Log', 'Psr\\Log']; /** * Set options for a backtrace processor. Accepted options are: * - ignoredNamespaces: array of namespaces to be excluded from the logged backtrace + * + * @param array|null $options */ public function __construct(?array $options = null) { - if (! empty($options['ignoredNamespaces'])) { - $this->ignoredNamespaces = array_merge($this->ignoredNamespaces, (array) $options['ignoredNamespaces']); + $ignored = $options['ignoredNamespaces'] ?? []; + foreach (is_array($ignored) ? $ignored : [$ignored] as $namespace) { + if (is_string($namespace) && $namespace !== '') { + $this->ignoredNamespaces[] = $namespace; + } } } /** - * Adds the origin of the log() call to the event extras + * Adds the origin of the log() call to the event context + * + * @param array $event + * @return array */ public function process(array $event): array { @@ -60,7 +73,7 @@ public function process(array $event): array ]; $context = $origin; - if (isset($event['context'])) { + if (isset($event['context']) && is_array($event['context'])) { $context = array_merge($origin, $event['context']); } $event['context'] = $context; @@ -68,6 +81,9 @@ public function process(array $event): array return $event; } + /** + * @return list + */ public function getIgnoredNamespaces(): array { return $this->ignoredNamespaces; @@ -75,6 +91,8 @@ public function getIgnoredNamespaces(): array /** * Provide backtrace as slim as possible + * + * @return list'|'::'}> */ protected function getBacktrace(): array { @@ -87,7 +105,8 @@ protected function getBacktrace(): array protected function shouldIgnoreFrame(string $class): bool { foreach ($this->ignoredNamespaces as $ignoredNamespace) { - if (false !== strpos($class, $ignoredNamespace)) { + $ignoredNamespace = rtrim($ignoredNamespace, '\\'); + if ($class === $ignoredNamespace || str_starts_with($class, $ignoredNamespace . '\\')) { return true; } } diff --git a/src/Processor/ProcessorInterface.php b/src/Processor/ProcessorInterface.php index 7483f44..deee662 100644 --- a/src/Processor/ProcessorInterface.php +++ b/src/Processor/ProcessorInterface.php @@ -8,6 +8,9 @@ interface ProcessorInterface { /** * Processes a log message before it is given to the writers + * + * @param array $event + * @return array */ public function process(array $event): array; } diff --git a/src/Processor/PsrPlaceholder.php b/src/Processor/PsrPlaceholder.php index 3a93c68..8e7b31d 100644 --- a/src/Processor/PsrPlaceholder.php +++ b/src/Processor/PsrPlaceholder.php @@ -4,29 +4,38 @@ namespace Dot\Log\Processor; -use function gettype; +use Stringable; + +use function get_debug_type; +use function is_array; use function is_object; use function is_scalar; -use function method_exists; -use function strpos; +use function is_string; +use function str_contains; use function strtr; class PsrPlaceholder implements ProcessorInterface { + /** + * @param array $event + * @return array + */ public function process(array $event): array { - if (false === strpos($event['message'], '{')) { + if ( + ! isset($event['message']) + || ! is_string($event['message']) + || ! str_contains($event['message'], '{') + || ! isset($event['context']) + || ! is_array($event['context']) + ) { return $event; } $replacements = []; foreach ($event['context'] as $key => $val) { - if ( - $val === null - || is_scalar($val) - || (is_object($val) && method_exists($val, "__toString")) - ) { - $replacements['{' . $key . '}'] = $val; + if ($val === null || is_scalar($val) || $val instanceof Stringable) { + $replacements['{' . $key . '}'] = (string) $val; continue; } @@ -35,7 +44,7 @@ public function process(array $event): array continue; } - $replacements['{' . $key . '}'] = '[' . gettype($val) . ']'; + $replacements['{' . $key . '}'] = '[' . get_debug_type($val) . ']'; } $event['message'] = strtr($event['message'], $replacements); diff --git a/src/Processor/ReferenceId.php b/src/Processor/ReferenceId.php index ccdbb07..6780ff0 100644 --- a/src/Processor/ReferenceId.php +++ b/src/Processor/ReferenceId.php @@ -4,12 +4,17 @@ namespace Dot\Log\Processor; +use function is_array; + class ReferenceId extends RequestId implements ProcessorInterface { /** * Adds an identifier for the request to the log. * * This enables to filter the log for messages belonging to a specific request + * + * @param array $event + * @return array */ public function process(array $event): array { @@ -17,7 +22,7 @@ public function process(array $event): array return $event; } - if (! isset($event['context'])) { + if (! isset($event['context']) || ! is_array($event['context'])) { $event['context'] = []; } diff --git a/src/Processor/RequestId.php b/src/Processor/RequestId.php index dc2fcc7..33a61a8 100644 --- a/src/Processor/RequestId.php +++ b/src/Processor/RequestId.php @@ -4,7 +4,11 @@ namespace Dot\Log\Processor; +use function is_array; +use function is_scalar; +use function is_string; use function md5; +use function microtime; class RequestId implements ProcessorInterface { @@ -14,6 +18,9 @@ class RequestId implements ProcessorInterface * Adds an identifier for the request to the log, unless one has already been set. * * This enables to filter the log for messages belonging to a specific request + * + * @param array $event + * @return array */ public function process(array $event): array { @@ -21,7 +28,7 @@ public function process(array $event): array return $event; } - if (! isset($event['context'])) { + if (! isset($event['context']) || ! is_array($event['context'])) { $event['context'] = []; } @@ -34,16 +41,16 @@ public function process(array $event): array */ protected function getIdentifier(): string { - if ($this->identifier) { + if ($this->identifier !== null && $this->identifier !== '') { return $this->identifier; } - $identifier = (string) $_SERVER['REQUEST_TIME_FLOAT']; + $requestTime = $_SERVER['REQUEST_TIME_FLOAT'] ?? null; + $identifier = is_scalar($requestTime) ? (string) $requestTime : (string) microtime(true); - if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { - $identifier .= $_SERVER['HTTP_X_FORWARDED_FOR']; - } elseif (isset($_SERVER['REMOTE_ADDR'])) { - $identifier .= $_SERVER['REMOTE_ADDR']; + $client = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? ''; + if (is_string($client)) { + $identifier .= $client; } $this->identifier = md5($identifier); diff --git a/src/Writer/AbstractWriter.php b/src/Writer/AbstractWriter.php index d9ff319..b0a93f6 100644 --- a/src/Writer/AbstractWriter.php +++ b/src/Writer/AbstractWriter.php @@ -11,18 +11,14 @@ use Dot\Log\Formatter\FormatterInterface; use Dot\Log\Manager\FilterPluginManager; use Dot\Log\Manager\FormatterPluginManager; -use ErrorException; -use Exception; -use Laminas\ServiceManager\ServiceManager; use Laminas\Stdlib\ErrorHandler; use Psr\Container\ContainerExceptionInterface; use Traversable; use function class_exists; -use function gettype; +use function get_debug_type; use function is_array; use function is_int; -use function is_object; use function is_string; use function iterator_to_array; use function sprintf; @@ -35,6 +31,7 @@ abstract class AbstractWriter implements WriterInterface protected ?FormatterPluginManager $formatterPlugins = null; + /** @var list */ protected array $filters = []; protected ?FormatterInterface $formatter = null; @@ -47,15 +44,16 @@ abstract class AbstractWriter implements WriterInterface /** * Error level passed to Laminas\Stdlib\ErrorHandler::start for errors reported during calls to write */ - protected int|bool $errorsToExceptionsConversionLevel = E_WARNING; + protected int $errorsToExceptionsConversionLevel = E_WARNING; /** - * Constructor - * * Set options for a writer. Accepted options are: - * - filters: array of filters to add to this filter - * - formatter: formatter for this writer + * - filter_manager: FilterPluginManager instance or class name + * - formatter_manager: FormatterPluginManager instance or class name + * - filters: a filter, or a list of filters (FilterInterface, level as int, plugin name, or [name, options]) + * - formatter: a formatter (FormatterInterface, plugin name, or [name, options]) * + * @param iterable|null $options * @throws ContainerExceptionInterface */ public function __construct(?iterable $options = null) @@ -64,53 +62,51 @@ public function __construct(?iterable $options = null) $options = iterator_to_array($options); } - if (is_array($options)) { - if (isset($options['filter_manager'])) { - $this->setFilterPluginManager($options['filter_manager']); - } + if (! is_array($options)) { + return; + } - if (isset($options['formatter_manager'])) { - $this->setFormatterPluginManager($options['formatter_manager']); - } + $filterManager = $options['filter_manager'] ?? null; + if (is_string($filterManager) || $filterManager instanceof FilterPluginManager) { + $this->setFilterPluginManager($filterManager); + } elseif ($filterManager !== null) { + throw $this->invalidManagerOption('filter_manager', $filterManager); + } - if (isset($options['filters'])) { - $filters = $options['filters']; - if (is_int($filters) || is_string($filters) || $filters instanceof FilterInterface) { - $this->addFilter($filters); - } elseif (is_array($filters)) { - foreach ($filters as $filter) { - if (is_int($filter) || is_string($filter) || $filter instanceof FilterInterface) { - $this->addFilter($filter); - } elseif (is_array($filter)) { - if (! isset($filter['name'])) { - throw new InvalidArgumentException( - 'Options must contain a name for the filter' - ); - } - $filterOptions = $filter['options'] ?? null; - $this->addFilter($filter['name'], $filterOptions); + $formatterManager = $options['formatter_manager'] ?? null; + if (is_string($formatterManager) || $formatterManager instanceof FormatterPluginManager) { + $this->setFormatterPluginManager($formatterManager); + } elseif ($formatterManager !== null) { + throw $this->invalidManagerOption('formatter_manager', $formatterManager); + } + + if (isset($options['filters'])) { + $filters = $options['filters']; + if (is_int($filters) || is_string($filters) || $filters instanceof FilterInterface) { + $this->addFilter($filters); + } elseif (is_array($filters)) { + foreach ($filters as $filter) { + if (is_int($filter) || is_string($filter) || $filter instanceof FilterInterface) { + $this->addFilter($filter); + } elseif (is_array($filter)) { + if (! isset($filter['name']) || ! is_string($filter['name'])) { + throw new InvalidArgumentException('Options must contain a name for the filter'); } + $this->addFilter($filter['name'], $this->optionsOrNull($filter['options'] ?? null)); } } } + } - if (isset($options['formatter'])) { - $formatter = $options['formatter']; - if (is_string($formatter) || $formatter instanceof FormatterInterface) { - $this->setFormatter($formatter); - } elseif (is_array($formatter)) { - if (! isset($formatter['name'])) { - throw new InvalidArgumentException('Options must contain a name for the formatter'); - } - $formatterOptions = $formatter['options'] ?? null; - - $formatterClass = $formatter['name']; - if (class_exists($formatterClass)) { - $formatterClass = new $formatterClass(); - } - - $this->setFormatter($formatterClass, $formatterOptions); + if (isset($options['formatter'])) { + $formatter = $options['formatter']; + if (is_string($formatter) || $formatter instanceof FormatterInterface) { + $this->setFormatter($formatter); + } elseif (is_array($formatter)) { + if (! isset($formatter['name']) || ! is_string($formatter['name'])) { + throw new InvalidArgumentException('Options must contain a name for the formatter'); } + $this->setFormatter($formatter['name'], $this->optionsOrNull($formatter['options'] ?? null)); } } } @@ -118,6 +114,7 @@ public function __construct(?iterable $options = null) /** * Add a filter specific to this writer. * + * @param array|null $options * @throws ContainerExceptionInterface */ public function addFilter(int|string|FilterInterface $filter, ?array $options = null): WriterInterface @@ -130,39 +127,31 @@ public function addFilter(int|string|FilterInterface $filter, ?array $options = $filter = $this->filterPlugin($filter, $options); } - if (! $filter instanceof FilterInterface) { - throw new InvalidArgumentException(sprintf( - 'Filter must implement %s\Filter\FilterInterface; received "%s"', - __NAMESPACE__, - is_object($filter) ? $filter::class : gettype($filter) - )); - } - $this->filters[] = $filter; return $this; } - public function getFilterPluginManager(): ?FilterPluginManager + public function getFilterPluginManager(): FilterPluginManager { if (null === $this->filterPlugins) { - $this->setFilterPluginManager(new FilterPluginManager(new ServiceManager())); + $this->filterPlugins = new FilterPluginManager(); } return $this->filterPlugins; } /** - * @param class-string|FilterPluginManager $plugins + * @param string|FilterPluginManager $plugins a FilterPluginManager instance or class name */ public function setFilterPluginManager(string|FilterPluginManager $plugins): static { - if (is_string($plugins)) { + if (is_string($plugins) && class_exists($plugins)) { $plugins = new $plugins(); } if (! $plugins instanceof FilterPluginManager) { throw new InvalidArgumentException(sprintf( - 'Writer plugin manager must extend %s; received %s', + 'Filter plugin manager must extend %s; received %s', FilterPluginManager::class, - $plugins::class + get_debug_type($plugins) )); } @@ -171,37 +160,36 @@ public function setFilterPluginManager(string|FilterPluginManager $plugins): sta } /** + * @param array|null $options * @throws ContainerExceptionInterface */ - public function filterPlugin(string $name, ?array $options = null): mixed + public function filterPlugin(string $name, ?array $options = null): FilterInterface { - return $this->getFilterPluginManager()?->build($name, $options); + return $this->getFilterPluginManager()->build($name, $options); } - public function getFormatterPluginManager(): ?FormatterPluginManager + public function getFormatterPluginManager(): FormatterPluginManager { if (null === $this->formatterPlugins) { - $this->setFormatterPluginManager(new FormatterPluginManager(new ServiceManager())); + $this->formatterPlugins = new FormatterPluginManager(); } return $this->formatterPlugins; } /** - * @param class-string|FormatterPluginManager $plugins + * @param string|FormatterPluginManager $plugins a FormatterPluginManager instance or class name */ public function setFormatterPluginManager(string|FormatterPluginManager $plugins): static { - if (is_string($plugins)) { + if (is_string($plugins) && class_exists($plugins)) { $plugins = new $plugins(); } if (! $plugins instanceof FormatterPluginManager) { - throw new InvalidArgumentException( - sprintf( - 'Writer plugin manager must extend %s; received %s', - FormatterPluginManager::class, - $plugins::class - ) - ); + throw new InvalidArgumentException(sprintf( + 'Formatter plugin manager must extend %s; received %s', + FormatterPluginManager::class, + get_debug_type($plugins) + )); } $this->formatterPlugins = $plugins; @@ -209,17 +197,18 @@ public function setFormatterPluginManager(string|FormatterPluginManager $plugins } /** + * @param array|null $options * @throws ContainerExceptionInterface */ - public function formatterPlugin(string $name, ?array $options = null): mixed + public function formatterPlugin(string $name, ?array $options = null): FormatterInterface { - return $this->getFormatterPluginManager()?->build($name, $options); + return $this->getFormatterPluginManager()->build($name, $options); } /** * Log a message to this writer. * - * @throws ErrorException + * @param array $event */ public function write(array $event): void { @@ -230,30 +219,27 @@ public function write(array $event): void } $errorHandlerStarted = false; - if ($this->convertWriteErrorsToExceptions && ! ErrorHandler::started()) { ErrorHandler::start($this->errorsToExceptionsConversionLevel); $errorHandlerStarted = true; } + $error = null; try { $this->doWrite($event); - } catch (Exception $e) { + } finally { if ($errorHandlerStarted) { - ErrorHandler::stop(); + $error = ErrorHandler::stop(); } - throw $e; } - if ($errorHandlerStarted) { - $error = ErrorHandler::stop(); - if ($error) { - throw new RuntimeException("Unable to write", 0, $error); - } + if ($error !== null) { + throw new RuntimeException('Unable to write', 0, $error); } } /** + * @param array|null $options * @throws ContainerExceptionInterface */ public function setFormatter(FormatterInterface|string $formatter, ?array $options = null): WriterInterface @@ -262,14 +248,6 @@ public function setFormatter(FormatterInterface|string $formatter, ?array $optio $formatter = $this->formatterPlugin($formatter, $options); } - if (! $formatter instanceof FormatterInterface) { - throw new InvalidArgumentException(sprintf( - 'Formatter must implement %s\Formatter\FormatterInterface; received "%s"', - __NAMESPACE__, - is_object($formatter) ? $formatter::class : gettype($formatter) - )); - } - $this->formatter = $formatter; return $this; } @@ -298,6 +276,29 @@ public function shutdown(): void /** * Write a message to the log + * + * @param array $event */ abstract protected function doWrite(array $event): void; + + /** + * @return array|null + */ + private function optionsOrNull(mixed $options): ?array + { + if ($options instanceof Traversable) { + return iterator_to_array($options); + } + + return is_array($options) ? $options : null; + } + + private function invalidManagerOption(string $key, mixed $value): InvalidArgumentException + { + return new InvalidArgumentException(sprintf( + 'Option "%s" must be a plugin manager instance or class name; received %s', + $key, + get_debug_type($value) + )); + } } diff --git a/src/Writer/Noop.php b/src/Writer/Noop.php index 701bb3f..a5e9f9e 100644 --- a/src/Writer/Noop.php +++ b/src/Writer/Noop.php @@ -8,6 +8,8 @@ class Noop extends AbstractWriter { /** * Write a message to the log. + * + * @param array $event */ protected function doWrite(array $event): void { diff --git a/src/Writer/Stream.php b/src/Writer/Stream.php index 3010b1f..27f8f61 100644 --- a/src/Writer/Stream.php +++ b/src/Writer/Stream.php @@ -7,12 +7,13 @@ use DateTimeImmutable; use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Exception\RuntimeException; -use ErrorException; +use Dot\Log\Formatter\Simple; use Exception; use Laminas\Stdlib\ErrorHandler; use Psr\Container\ContainerExceptionInterface; use Traversable; +use function array_map; use function chmod; use function dirname; use function error_log; @@ -23,8 +24,10 @@ use function fwrite; use function get_resource_type; use function gettype; +use function implode; use function is_array; use function is_dir; +use function is_int; use function is_link; use function is_numeric; use function is_resource; @@ -33,10 +36,11 @@ use function iterator_to_array; use function pathinfo; use function preg_grep; -use function preg_match_all; +use function preg_match; +use function preg_quote; +use function preg_split; use function scandir; use function sprintf; -use function str_replace; use function stream_get_meta_data; use function time; use function touch; @@ -49,6 +53,11 @@ class Stream extends AbstractWriter { private const DEFAULT_PERMISSIONS = 0666; + /** + * Date placeholders in a stream name, for example {Y} + */ + public const PLACEHOLDER_PATTERN = '/\{[a-z]\}/i'; + /** * Separator between log entries */ @@ -56,6 +65,8 @@ class Stream extends AbstractWriter /** * Holds the PHP stream to log to. + * + * @var resource|closed-resource */ protected mixed $stream; @@ -64,8 +75,10 @@ class Stream extends AbstractWriter protected ?string $streamFormat = null; /** + * @param string|resource|iterable $streamOrUrl a path or URL, a stream resource, or options: + * stream, mode, log_separator, chmod, log_lifetime, stream_format, filters, formatter, + * filter_manager, formatter_manager * @throws ContainerExceptionInterface - * @throws ErrorException */ public function __construct( mixed $streamOrUrl, @@ -89,6 +102,10 @@ public function __construct( $streamOrUrl = $streamOrUrl['stream'] ?? null; } + if (! $this->hasFormatter()) { + $this->setFormatter(new Simple()); + } + // Setting the default mode if (null === $mode) { $mode = 'a'; @@ -101,7 +118,6 @@ public function __construct( )); } - $error = null; if (is_resource($streamOrUrl)) { if ('stream' !== get_resource_type($streamOrUrl)) { throw new InvalidArgumentException(sprintf( @@ -118,25 +134,26 @@ public function __construct( } $this->stream = $streamOrUrl; - } else { + } elseif (is_string($streamOrUrl)) { ErrorHandler::start(); - if (isset($filePermissions) && ! file_exists($streamOrUrl) && is_writable(dirname($streamOrUrl))) { + if (is_int($filePermissions) && ! file_exists($streamOrUrl) && is_writable(dirname($streamOrUrl))) { touch($streamOrUrl); chmod($streamOrUrl, $filePermissions); } - $this->stream = fopen($streamOrUrl, $mode); - $error = ErrorHandler::stop(); - } + $stream = fopen($streamOrUrl, $mode); + $error = ErrorHandler::stop(); - if (! $this->stream) { - throw new RuntimeException(sprintf( - '"%s" cannot be opened with mode "%s"', - $streamOrUrl, - $mode - ), 0, $error); + if ($stream === false) { + throw new RuntimeException(sprintf( + '"%s" cannot be opened with mode "%s"', + $streamOrUrl, + $mode + ), 0, $error); + } + $this->stream = $stream; } - if (null !== $logSeparator) { + if (is_string($logSeparator)) { $this->setLogSeparator($logSeparator); } @@ -148,11 +165,11 @@ public function __construct( if ($logLifetime >= time()) { $logLifetime = null; } - } catch (Exception $e) { + } catch (Exception) { $logLifetime = null; } - if ($logLifetime !== null && $streamFormat !== null) { + if ($logLifetime !== null && is_string($streamFormat)) { $this->streamFormat = $streamFormat; } @@ -162,11 +179,17 @@ public function __construct( /** * Write a message to the log. + * + * @param array $event */ protected function doWrite(array $event): void { - $line = $this->formatter->format($event) . $this->logSeparator; - fwrite($this->stream, $line); + if (! is_resource($this->stream)) { + throw new RuntimeException('The log stream is closed'); + } + + $formatter = $this->getFormatter() ?? new Simple(); + fwrite($this->stream, $formatter->format($event) . $this->logSeparator); } /** @@ -200,29 +223,32 @@ public function shutdown(): void } } + /** + * Deletes log files of this writer that are older than the configured lifetime. + * + * Runs only when the configured stream contains date placeholders such as {Y}: only then can this writer's + * files be told apart from other files in the same directory. + */ protected function removeOldLogs(): void { - preg_match_all('/{([a-z])}/i', $this->streamFormat, $matches); - - if (! empty($matches[1])) { - foreach ($matches[1] as $match) { - $this->streamFormat = str_replace('{' . $match . '}', '\d+', $this->streamFormat); - } + $pattern = $this->getOldLogsPattern(); + if ($pattern === null || ! is_resource($this->stream)) { + return; + } - $this->streamFormat = str_replace('.', '\.', $this->streamFormat); + $path = stream_get_meta_data($this->stream)['uri'] ?? null; + if (! is_string($path)) { + return; } - $streamData = stream_get_meta_data($this->stream); - $path = $streamData['uri']; $directory = pathinfo($path, PATHINFO_DIRNAME); - if (! is_dir($directory)) { error_log("{$directory} is not a directory"); return; } $files = scandir($directory) ?: []; - $matches = preg_grep('/^' . $this->streamFormat . '$/', $files) ?: []; + $matches = preg_grep($pattern, $files) ?: []; foreach ($matches as $match) { $match = sprintf('%s/%s', $directory, $match); @@ -244,4 +270,24 @@ protected function removeOldLogs(): void } } } + + /** + * Builds the pattern matching the file names this writer creates, or null when the stream has no date placeholder. + * + * Every placeholder matches letters and digits (date() returns month and day names for some characters); the rest + * of the file name is matched literally. + */ + public function getOldLogsPattern(): ?string + { + if ($this->streamFormat === null || ! preg_match(self::PLACEHOLDER_PATTERN, $this->streamFormat)) { + return null; + } + + $parts = preg_split(self::PLACEHOLDER_PATTERN, $this->streamFormat) ?: []; + + return '/^' . implode( + '[A-Za-z0-9]+', + array_map(static fn (string $part): string => preg_quote($part, '/'), $parts) + ) . '$/'; + } } diff --git a/src/Writer/WriterInterface.php b/src/Writer/WriterInterface.php index d0b3992..cae7b69 100644 --- a/src/Writer/WriterInterface.php +++ b/src/Writer/WriterInterface.php @@ -21,6 +21,8 @@ public function setFormatter(FormatterInterface|string $formatter): WriterInterf /** * Write a log message + * + * @param array $event */ public function write(array $event): void; diff --git a/test/ConfigProviderTest.php b/test/ConfigProviderTest.php index ea5619e..ca370ab 100644 --- a/test/ConfigProviderTest.php +++ b/test/ConfigProviderTest.php @@ -5,61 +5,15 @@ namespace DotTest\Log; use Dot\Log\ConfigProvider; -use Dot\Log\Logger; -use Dot\Log\Manager\FilterPluginManager; -use Dot\Log\Manager\FormatterPluginManager; -use Dot\Log\Manager\ProcessorPluginManager; -use Dot\Log\Manager\WriterPluginManager; use PHPUnit\Framework\TestCase; class ConfigProviderTest extends TestCase { - protected array $config; - - protected function setUp(): void - { - $this->config = (new ConfigProvider())(); - } - - public function testHasDependencies(): void - { - $this->assertArrayHasKey('dependencies', $this->config); - } - - public function testDependenciesHasFactories(): void - { - $this->assertArrayHasKey('factories', $this->config['dependencies']); - $this->assertArrayHasKey(Logger::class, $this->config['dependencies']['factories']); - $this->assertArrayHasKey('LogFilterManager', $this->config['dependencies']['factories']); - $this->assertArrayHasKey('LogFormatterManager', $this->config['dependencies']['factories']); - $this->assertArrayHasKey('LogProcessorManager', $this->config['dependencies']['factories']); - $this->assertArrayHasKey('LogWriterManager', $this->config['dependencies']['factories']); - } - - public function testDependenciesHasAliases(): void + public function testRegistersNothing(): void { - $this->assertArrayHasKey('aliases', $this->config['dependencies']); - $this->assertArrayHasKey(FilterPluginManager::class, $this->config['dependencies']['aliases']); - $this->assertArrayHasKey(FormatterPluginManager::class, $this->config['dependencies']['aliases']); - $this->assertArrayHasKey(ProcessorPluginManager::class, $this->config['dependencies']['aliases']); - $this->assertArrayHasKey(WriterPluginManager::class, $this->config['dependencies']['aliases']); - } - - public function testDependenciesHasAbstractFactories(): void - { - $this->assertArrayHasKey('abstract_factories', $this->config['dependencies']); - } + $provider = new ConfigProvider(); - public function testConfigHasDotLog(): void - { - $this->assertArrayHasKey('dot_log', $this->config); - $this->assertIsArray($this->config['dot_log']); - } - - public function testDotLogKeysReturnArray(): void - { - foreach ($this->config['dot_log'] as $key) { - $this->assertIsArray($key); - } + $this->assertSame([], $provider()); + $this->assertSame([], $provider->getDependencies()); } } diff --git a/test/Factory/FilterPluginManagerFactoryTest.php b/test/Factory/FilterPluginManagerFactoryTest.php deleted file mode 100644 index fd51de5..0000000 --- a/test/Factory/FilterPluginManagerFactoryTest.php +++ /dev/null @@ -1,101 +0,0 @@ -container = $this->createMock(ContainerInterface::class); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutConfig(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(false); - - $this->expectExceptionMessage('Unable to find config'); - $this->expectException(\Exception::class); - (new FilterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutDotLog(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturnMap([]); - - $this->expectExceptionMessage('Unable to find dot_log config'); - $this->expectException(\Exception::class); - (new FilterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutFilterConfig(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturn([ - 'dot_log' => [], - ]); - - $this->expectExceptionMessage('Unable to find filter_manager config'); - $this->expectException(\Exception::class); - (new FilterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillInstantiate(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturn([ - 'dot_log' => ['filter_manager' => []], - ]); - - $factory = (new FilterPluginManagerFactory())($this->container); - - $this->assertSame(FilterPluginManager::class, $factory::class); - } -} diff --git a/test/Factory/FormatterPluginManagerFactoryTest.php b/test/Factory/FormatterPluginManagerFactoryTest.php deleted file mode 100644 index 23b6c0b..0000000 --- a/test/Factory/FormatterPluginManagerFactoryTest.php +++ /dev/null @@ -1,101 +0,0 @@ -container = $this->createMock(ContainerInterface::class); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutConfig(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(false); - - $this->expectExceptionMessage('Unable to find config'); - $this->expectException(\Exception::class); - (new FormatterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutDotLog(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturnMap([]); - - $this->expectExceptionMessage('Unable to find dot_log config'); - $this->expectException(\Exception::class); - (new FormatterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutFormatterConfig(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturn([ - 'dot_log' => [], - ]); - - $this->expectExceptionMessage('Unable to find formatter_manager config'); - $this->expectException(\Exception::class); - (new FormatterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillInstantiate(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturn([ - 'dot_log' => ['formatter_manager' => []], - ]); - - $factory = (new FormatterPluginManagerFactory())($this->container); - - $this->assertSame(FormatterPluginManager::class, $factory::class); - } -} diff --git a/test/Factory/LoggerAbstractServiceFactoryTest.php b/test/Factory/LoggerAbstractServiceFactoryTest.php deleted file mode 100644 index 7a444e9..0000000 --- a/test/Factory/LoggerAbstractServiceFactoryTest.php +++ /dev/null @@ -1,77 +0,0 @@ - [ - 'loggers' => [ - 'test-log' => [], - ], - ], - ]; - - /** - * @throws Exception - */ - protected function setUp(): void - { - $this->container = $this->createMock(ContainerInterface::class); - $this->factory = new LoggerAbstractServiceFactory(); - } - - /** - * @throws ContainerExceptionInterface - */ - public function testWillInstantiate(): void - { - $this->container - ->method('has') - ->willReturn(true, false, false); - - $this->container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn($this->config); - - $factory = (new LoggerAbstractServiceFactory())($this->container, 'dot-log.test-log'); - - $this->assertSame(Logger::class, $factory::class); - } - - /** - * @throws NotFoundExceptionInterface - * @throws ContainerExceptionInterface - */ - public function testCanCreate(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->expects($this->once()) - ->method('get') - ->with('config') - ->willReturn($this->config); - - $this->assertIsBool($this->factory->canCreate($this->container, '')); - $this->assertFalse($this->factory->canCreate($this->container, '')); - $this->assertTrue($this->factory->canCreate($this->container, 'dot-log.test-log')); - } -} diff --git a/test/Factory/LoggerFactoryTest.php b/test/Factory/LoggerFactoryTest.php new file mode 100644 index 0000000..3a629f2 --- /dev/null +++ b/test/Factory/LoggerFactoryTest.php @@ -0,0 +1,232 @@ +directory = sys_get_temp_dir() . '/dot-log-test-' . uniqid(); + mkdir($this->directory); + } + + protected function tearDown(): void + { + array_map(unlink(...), glob($this->directory . '/*') ?: []); + if (is_dir($this->directory)) { + rmdir($this->directory); + } + } + + /** + * @param array $loggers + * @param array $dotLog + */ + private function container(array $loggers, array $dotLog = []): InMemoryContainer + { + return new InMemoryContainer([ + 'config' => ['dot_log' => ['loggers' => $loggers] + $dotLog], + ]); + } + + public function testCreatesTheNamedLogger(): void + { + $container = $this->container(['app' => ['writers' => [['name' => 'noop']]]]); + + $logger = (new LoggerFactory())($container, 'dot-log.app'); + + $writers = $logger->getWriters()->toArray(); + $this->assertCount(1, $writers); + $this->assertInstanceOf(Noop::class, $writers[0]); + } + + public function testLoggerWithoutWriters(): void + { + $logger = (new LoggerFactory())($this->container(['empty' => []]), 'dot-log.empty'); + + $this->assertCount(0, $logger->getWriters()); + } + + /** + * Regression tests: the abstract factory threw or returned true for these cases. + * + * @return iterable, string, string}> + */ + public static function provideMissingConfig(): iterable + { + yield 'no config service' => [[], 'dot-log.app', 'Unable to find the "dot_log.loggers" config']; + yield 'no dot_log key' => [['config' => []], 'dot-log.app', 'Unable to find the "dot_log.loggers" config']; + yield 'no loggers key' => [ + ['config' => ['dot_log' => ['formatter_manager' => []]]], + 'dot-log.formatter_manager', + 'Unable to find the "dot_log.loggers" config', + ]; + yield 'unknown logger' => [ + ['config' => ['dot_log' => ['loggers' => ['app' => []]]]], + 'dot-log.other', + 'Unable to find the "dot_log.loggers.other" config', + ]; + yield 'logger config not an array' => [ + ['config' => ['dot_log' => ['loggers' => ['app' => 'x']]]], + 'dot-log.app', + 'Unable to find the "dot_log.loggers.app" config', + ]; + yield 'missing prefix' => [ + ['config' => ['dot_log' => ['loggers' => ['app' => []]]]], + 'app', + 'LoggerFactory creates services named "dot-log."; "app" was requested', + ]; + yield 'empty name' => [ + ['config' => ['dot_log' => ['loggers' => ['app' => []]]]], + 'dot-log.', + 'LoggerFactory creates services named "dot-log."; "dot-log." was requested', + ]; + } + + /** + * @param array $services + */ + #[DataProvider('provideMissingConfig')] + public function testMissingConfigIsReported(array $services, string $requestedName, string $message): void + { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage($message); + + (new LoggerFactory())(new InMemoryContainer($services), $requestedName); + } + + public function testResolvesDatePlaceholdersInStreams(): void + { + $container = $this->container([ + 'app' => [ + 'writers' => [ + [ + 'name' => 'stream', + 'options' => ['stream' => $this->directory . '/app-{Y}-{m}-{d}.log'], + ], + ], + ], + ]); + + (new LoggerFactory())($container, 'dot-log.app')->info('dated'); + + $file = $this->directory . '/app-' . date('Y-m-d') . '.log'; + $this->assertFileExists($file); + $this->assertStringContainsString('dated', (string) file_get_contents($file)); + } + + public function testParseVariables(): void + { + $this->assertSame('log/' . date('Y') . '-x-{}.log', LoggerFactory::parseVariables('log/{Y}-x-{}.log')); + } + + /** + * Regression test: dot_log.*_manager config was ignored. + */ + public function testUsesCustomPluginsFromTheManagerConfig(): void + { + $container = $this->container( + [ + 'app' => [ + 'writers' => [ + [ + 'name' => 'memory', + 'options' => ['filters' => [['name' => 'block']], 'formatter' => 'custom_json'], + ], + ], + ], + ], + [ + 'writer_manager' => ['aliases' => ['memory' => MemoryWriter::class]], + 'filter_manager' => [ + 'factories' => ['block' => static fn (): SuppressFilter => new SuppressFilter(true)], + ], + 'formatter_manager' => ['aliases' => ['custom_json' => Json::class]], + ] + ); + + $logger = (new LoggerFactory())($container, 'dot-log.app'); + $writer = $logger->getWriters()->toArray()[0]; + $logger->info('blocked'); + + $this->assertInstanceOf(MemoryWriter::class, $writer); + $this->assertSame([], $writer->events); + } + + /** + * The documented configuration (docs/book/v6/configuring-writer.md) must work as written. + */ + public function testDocumentedWriterConfiguration(): void + { + $container = $this->container([ + 'my_logger' => [ + 'writers' => [ + 'FileWriter' => [ + 'name' => 'stream', + 'level' => Logger::ALERT, + 'options' => [ + 'stream' => $this->directory . '/dk.log', + 'filters' => [ + 'allMessages' => [ + 'name' => 'level', + 'options' => ['operator' => '>=', 'level' => Logger::EMERG], + ], + ], + 'formatter' => ['name' => 'json'], + 'log_lifetime' => null, + ], + ], + ], + ], + ]); + + (new LoggerFactory())($container, 'dot-log.my_logger')->warning('user {id} logged in', ['id' => 7]); + + $line = json_decode(trim((string) file_get_contents($this->directory . '/dk.log')), true); + $this->assertIsArray($line); + $this->assertSame('user 7 logged in', $line['message']); + $this->assertSame(Logger::WARN, $line['level']); + $this->assertSame('warning', $line['levelName']); + } + + /** + * Integration: the factory works with a minimal PSR-11 container. + */ + public function testWorksWithAMinimalPsr11Container(): void + { + $container = new InMemoryContainer( + ['config' => ['dot_log' => ['loggers' => ['app' => ['writers' => [['name' => 'noop']]]]]]], + ['dot-log.app' => LoggerFactory::class] + ); + + $this->assertInstanceOf(Logger::class, $container->get('dot-log.app')); + } +} diff --git a/test/Factory/PluginManagerFactoryTest.php b/test/Factory/PluginManagerFactoryTest.php new file mode 100644 index 0000000..894d39a --- /dev/null +++ b/test/Factory/PluginManagerFactoryTest.php @@ -0,0 +1,122 @@ +>, class-string}> + */ + public static function provideFactories(): iterable + { + yield 'filter' => [ + new FilterPluginManagerFactory(), + 'filter_manager', + FilterPluginManager::class, + SuppressFilter::class, + ]; + yield 'formatter' => [ + new FormatterPluginManagerFactory(), + 'formatter_manager', + FormatterPluginManager::class, + Json::class, + ]; + yield 'processor' => [ + new ProcessorPluginManagerFactory(), + 'processor_manager', + ProcessorPluginManager::class, + RequestId::class, + ]; + yield 'writer' => [ + new WriterPluginManagerFactory(), + 'writer_manager', + WriterPluginManager::class, + Noop::class, + ]; + } + + /** + * @param class-string> $managerClass + */ + #[DataProvider('provideFactories')] + public function testCreatesAnEmptyManagerWithoutConfig( + callable $factory, + string $key, + string $managerClass, + string $pluginClass + ): void { + $this->assertFalse((new $managerClass())->has('custom'), $pluginClass . ' is not registered by default'); + $this->assertInstanceOf($managerClass, $factory(new InMemoryContainer())); + $this->assertInstanceOf($managerClass, $factory(new InMemoryContainer(['config' => []]))); + } + + /** + * Regression test: the factories passed the whole dot_log config, so custom plugins were ignored. + * + * @param class-string> $managerClass + * @param class-string $pluginClass + */ + #[DataProvider('provideFactories')] + public function testAppliesTheManagerConfig( + callable $factory, + string $key, + string $managerClass, + string $pluginClass + ): void { + $container = new InMemoryContainer([ + 'config' => ['dot_log' => [$key => ['aliases' => ['custom' => $pluginClass]]]], + ]); + + $manager = $factory($container); + + $this->assertInstanceOf(AbstractPluginManager::class, $manager); + $this->assertInstanceOf($pluginClass, $manager->build('custom')); + $this->assertSame($container, $manager->getCreationContext()); + } + + #[DataProvider('provideFactories')] + public function testRejectsANonArrayManagerConfig( + callable $factory, + string $key, + string $managerClass, + string $pluginClass + ): void { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The dot_log.' . $key . ' config must be an array'); + + $factory(new InMemoryContainer(['config' => ['dot_log' => [$key => 'invalid']]])); + } + + #[DataProvider('provideFactories')] + public function testRejectsANonArrayConfig( + callable $factory, + string $key, + string $managerClass, + string $pluginClass + ): void { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Unable to find config'); + + $factory(new InMemoryContainer(['config' => 'invalid'])); + } +} diff --git a/test/Factory/ProcessorPluginManagerFactoryTest.php b/test/Factory/ProcessorPluginManagerFactoryTest.php deleted file mode 100644 index 9d08015..0000000 --- a/test/Factory/ProcessorPluginManagerFactoryTest.php +++ /dev/null @@ -1,101 +0,0 @@ -container = $this->createMock(ContainerInterface::class); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutConfig(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(false); - - $this->expectExceptionMessage('Unable to find config'); - $this->expectException(\Exception::class); - (new ProcessorPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutDotLog(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturnMap([]); - - $this->expectExceptionMessage('Unable to find dot_log config'); - $this->expectException(\Exception::class); - (new ProcessorPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutProcessorConfig(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturn([ - 'dot_log' => [], - ]); - - $this->expectExceptionMessage('Unable to find processor_manager config'); - $this->expectException(\Exception::class); - (new ProcessorPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillInstantiate(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturn([ - 'dot_log' => ['processor_manager' => []], - ]); - - $factory = (new ProcessorPluginManagerFactory())($this->container); - - $this->assertSame(ProcessorPluginManager::class, $factory::class); - } -} diff --git a/test/Factory/WriterFactoryTest.php b/test/Factory/WriterFactoryTest.php index c8a0fbd..c77a054 100644 --- a/test/Factory/WriterFactoryTest.php +++ b/test/Factory/WriterFactoryTest.php @@ -4,38 +4,62 @@ namespace DotTest\Log\Factory; +use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Factory\WriterFactory; -use Dot\Log\Writer\AbstractWriter; +use Dot\Log\Formatter\Json; +use Dot\Log\Manager\FilterPluginManager; +use Dot\Log\Manager\FormatterPluginManager; use Dot\Log\Writer\Stream; -use PHPUnit\Framework\MockObject\Exception; -use PHPUnit\Framework\MockObject\MockObject; +use DotTest\Log\Fixture\InMemoryContainer; +use DotTest\Log\Fixture\MemoryWriter; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\ContainerInterface; +use stdClass; class WriterFactoryTest extends TestCase { - private ContainerInterface|MockObject $container; + public function testCreatesTheWriterWithOptions(): void + { + $writer = (new WriterFactory())(new InMemoryContainer(), Stream::class, [ + 'stream' => 'php://memory', + 'log_separator' => '|', + ]); + + $this->assertInstanceOf(Stream::class, $writer); + $this->assertSame('|', $writer->getLogSeparator()); + } + + public function testInjectsDefaultManagerServicesWhenTheContainerHasThem(): void + { + $filters = new FilterPluginManager(); + $formatters = new FormatterPluginManager(null, ['aliases' => ['custom' => Json::class]]); + $container = new InMemoryContainer([ + 'LogFilterManager' => $filters, + 'LogFormatterManager' => $formatters, + ]); - /** - * @throws Exception - */ - protected function setUp(): void + $writer = (new WriterFactory())($container, MemoryWriter::class); + + $this->assertInstanceOf(MemoryWriter::class, $writer); + $this->assertSame($filters, $writer->getFilterPluginManager()); + $this->assertSame($formatters, $writer->getFormatterPluginManager()); + } + + public function testResolvesManagersNamedAsServices(): void { - $this->container = $this->createMock(ContainerInterface::class); + $formatters = new FormatterPluginManager(); + $container = new InMemoryContainer(['my.formatters' => $formatters]); + + $writer = (new WriterFactory())($container, MemoryWriter::class, ['formatter_manager' => 'my.formatters']); + + $this->assertInstanceOf(MemoryWriter::class, $writer); + $this->assertSame($formatters, $writer->getFormatterPluginManager()); } - /** - * @throws ContainerExceptionInterface - */ - public function testWillInstantiate(): void + public function testRejectsClassesThatAreNotWriters(): void { - $factory = (new WriterFactory())( - $this->container, - Stream::class, - ['stream' => __DIR__ . '/../../log/dk.log'] - ); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('"stdClass" is not a class implementing Dot\Log\Writer\WriterInterface'); - $this->assertInstanceOf(AbstractWriter::class, $factory); + (new WriterFactory())(new InMemoryContainer(), stdClass::class); } } diff --git a/test/Factory/WriterPluginManagerFactoryTest.php b/test/Factory/WriterPluginManagerFactoryTest.php deleted file mode 100644 index 9fe1941..0000000 --- a/test/Factory/WriterPluginManagerFactoryTest.php +++ /dev/null @@ -1,101 +0,0 @@ -container = $this->createMock(ContainerInterface::class); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutConfig(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(false); - - $this->expectExceptionMessage('Unable to find config'); - $this->expectException(\Exception::class); - (new WriterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutDotLog(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturnMap([]); - - $this->expectExceptionMessage('Unable to find dot_log config'); - $this->expectException(\Exception::class); - (new WriterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillNotInstantiateWithoutWriterConfig(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturn([ - 'dot_log' => [], - ]); - - $this->expectExceptionMessage('Unable to find writer_manager config'); - $this->expectException(\Exception::class); - (new WriterPluginManagerFactory())($this->container); - } - - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillInstantiate(): void - { - $this->container->expects($this->once()) - ->method('has') - ->with('config') - ->willReturn(true); - - $this->container->method('get')->willReturn([ - 'dot_log' => ['writer_manager' => []], - ]); - - $factory = (new WriterPluginManagerFactory())($this->container); - - $this->assertSame(WriterPluginManager::class, $factory::class); - } -} diff --git a/test/Filter/CallbackTest.php b/test/Filter/CallbackTest.php new file mode 100644 index 0000000..d167061 --- /dev/null +++ b/test/Filter/CallbackTest.php @@ -0,0 +1,36 @@ + $event['level'] === Logger::ERR); + + $this->assertTrue($filter->filter(['level' => Logger::ERR])); + $this->assertFalse($filter->filter(['level' => Logger::INFO])); + } + + public function testAcceptsOptions(): void + { + $this->assertTrue((new Callback(['callback' => static fn (): bool => true]))->filter([])); + $this->assertFalse((new Callback(new ArrayObject(['callback' => static fn (): bool => false])))->filter([])); + } + + public function testRejectsAMissingCallback(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Callback must be callable; received "null"'); + + new Callback([]); + } +} diff --git a/test/Filter/LevelTest.php b/test/Filter/LevelTest.php index c3a69e7..2a2c5ef 100644 --- a/test/Filter/LevelTest.php +++ b/test/Filter/LevelTest.php @@ -4,57 +4,92 @@ namespace DotTest\Log\Filter; +use ArrayObject; use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Filter\Level; +use Dot\Log\Logger; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; class LevelTest extends TestCase { - private Level $subject; - - public function setUp(): void + public function testDefaultOperatorAcceptsLevelsUpToTheLimit(): void { - $this->subject = new Level(47); + $filter = new Level(Logger::WARN); + + $this->assertTrue($filter->filter(['level' => Logger::ERR])); + $this->assertTrue($filter->filter(['level' => Logger::WARN])); + $this->assertFalse($filter->filter(['level' => Logger::INFO])); } - public function testWillInstantiateWithInt(): void + public function testAcceptsOptions(): void { - $this->assertSame(Level::class, $this->subject::class); + $this->assertTrue((new Level(['level' => 4, 'operator' => '==']))->filter(['level' => 4])); + $this->assertTrue((new Level(new ArrayObject(['level' => 4, 'operator' => 'ne'])))->filter(['level' => 3])); } - public function testWillInstantiateWithArray(): void + /** + * @return iterable + */ + public static function provideOperators(): iterable { - $input = ['level' => 47]; - - $result = new Level($input); - - $this->assertSame(Level::class, $result::class); + foreach (['<', 'lt'] as $op) { + yield $op . ' lower' => [$op, 3, true]; + yield $op . ' equal' => [$op, 4, false]; + } + foreach (['<=', 'le'] as $op) { + yield $op . ' equal' => [$op, 4, true]; + yield $op . ' higher' => [$op, 5, false]; + } + foreach (['>', 'gt'] as $op) { + yield $op . ' higher' => [$op, 5, true]; + yield $op . ' equal' => [$op, 4, false]; + } + foreach (['>=', 'ge'] as $op) { + yield $op . ' equal' => [$op, 4, true]; + yield $op . ' lower' => [$op, 3, false]; + } + foreach (['==', '=', 'eq'] as $op) { + yield $op . ' equal' => [$op, 4, true]; + yield $op . ' other' => [$op, 3, false]; + } + foreach (['!=', '<>', 'ne'] as $op) { + yield $op . ' other' => [$op, 3, true]; + yield $op . ' equal' => [$op, 4, false]; + } } - public function testWillNotInstantiateWithEmptyArray(): void + #[DataProvider('provideOperators')] + public function testOperators(string $operator, int $eventLevel, bool $accepted): void { - $input = []; - - $this->expectExceptionMessage('Level must be a number, received "NULL"'); - $this->expectException(InvalidArgumentException::class); - new Level($input); + $this->assertSame($accepted, (new Level(4, $operator))->filter(['level' => $eventLevel])); } - public function testFilterWillAcceptMessage(): void + public function testRejectsEventsWithoutANumericLevel(): void { - $input = ['level' => 47]; + $this->assertFalse((new Level(7))->filter([])); + $this->assertFalse((new Level(7))->filter(['level' => 'debug'])); + } - $result = $this->subject->filter($input); + public function testWillNotInstantiateWithEmptyArray(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Level must be a number, received "NULL"'); - $this->assertTrue($result); + new Level([]); } - public function testFilterWillNotAcceptMessage(): void + /** + * Regression test: an invalid operator was accepted and failed with ValueError on the first log call. + */ + public function testRejectsAnInvalidOperator(): void { - $input = ['level' => 244]; - - $result = $this->subject->filter($input); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Operator must be one of "<", "lt", "<=", "le", ">", "gt", ">=", "ge", "==", "=", "eq", "!=", "<>", "ne",' + . ' received "=<"' + ); - $this->assertFalse($result); + new Level(['level' => 3, 'operator' => '=<']); } } diff --git a/test/Filter/RegexTest.php b/test/Filter/RegexTest.php index dde63a4..d191158 100644 --- a/test/Filter/RegexTest.php +++ b/test/Filter/RegexTest.php @@ -4,55 +4,77 @@ namespace DotTest\Log\Filter; +use ArrayObject; +use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Filter\Regex; -use ErrorException; +use Laminas\Stdlib\ErrorHandler; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use TypeError; class RegexTest extends TestCase { - private Regex $subject; + public function testFiltersByPattern(): void + { + $filter = new Regex(['regex' => '/(a)(b)*(c)/']); - /** - * @throws ErrorException - */ - public function setUp(): void + $this->assertTrue($filter->filter(['message' => 'ac'])); + $this->assertFalse($filter->filter(['message' => 'bc'])); + } + + public function testAcceptsAPatternString(): void + { + $this->assertTrue((new Regex('/^x/'))->filter(['message' => 'xyz'])); + $this->assertTrue((new Regex(new ArrayObject(['regex' => '/^x/'])))->filter(['message' => 'xyz'])); + } + + public function testArrayMessagesAreExported(): void { - $this->subject = new Regex(['regex' => '/(a)(b)*(c)/']); + $this->assertTrue((new Regex('/needle/'))->filter(['message' => ['key' => 'needle']])); } - public function testWillInstantiate(): void + public function testMissingMessageDoesNotMatch(): void { - $this->assertSame(Regex::class, $this->subject::class); + $this->assertFalse((new Regex('/./'))->filter([])); } /** - * @throws ErrorException + * @return iterable|string}> */ - public function testWillNotInstantiateWithEmptyArray(): void + public static function provideMissingPatterns(): iterable { - $this->expectExceptionMessage( - 'preg_match(): Argument #1 ($pattern) must be of type string, null given' - ); - $this->expectException(TypeError::class); - new Regex([]); + yield 'empty array' => [[]]; + yield 'empty string' => ['']; + yield 'not a string' => [['regex' => 1]]; } - public function testFilterWillAcceptMessage(): void + /** + * Regression test: an empty pattern threw a TypeError and left an error handler active. + * + * @param array|string $regex + */ + #[DataProvider('provideMissingPatterns')] + public function testRejectsAMissingPattern(array|string $regex): void { - $input = ['message' => 'ac']; - - $result = $this->subject->filter($input); + try { + new Regex($regex); + $this->fail('Expected InvalidArgumentException'); + } catch (InvalidArgumentException $exception) { + $this->assertSame('Option "regex" must be a non-empty string', $exception->getMessage()); + } - $this->assertTrue($result); + $this->assertFalse(ErrorHandler::started()); } - public function testFilterWillNotAcceptMessage(): void + public function testRejectsAnInvalidPattern(): void { - $input = ['message' => 'What a wonderful day to write tests']; - - $result = $this->subject->filter($input); + try { + new Regex(['regex' => '/(unclosed/']); + $this->fail('Expected InvalidArgumentException'); + } catch (InvalidArgumentException $exception) { + $this->assertSame('Invalid regular expression "/(unclosed/"', $exception->getMessage()); + $this->assertNotNull($exception->getPrevious()); + } - $this->assertFalse($result); + $this->assertFalse(ErrorHandler::started()); } } diff --git a/test/Filter/SuppressFilterTest.php b/test/Filter/SuppressFilterTest.php index 942abde..9208282 100644 --- a/test/Filter/SuppressFilterTest.php +++ b/test/Filter/SuppressFilterTest.php @@ -4,43 +4,34 @@ namespace DotTest\Log\Filter; +use ArrayObject; use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Filter\SuppressFilter; use PHPUnit\Framework\TestCase; class SuppressFilterTest extends TestCase { - private SuppressFilter $subject; - - public function setUp(): void + public function testAcceptsByDefault(): void { - $this->subject = new SuppressFilter(); + $this->assertTrue((new SuppressFilter())->filter([])); } - public function testWillInstantiate(): void + public function testSuppress(): void { - $this->assertSame(SuppressFilter::class, $this->subject::class); + $filter = new SuppressFilter(['suppress' => true]); + $this->assertFalse($filter->filter([])); + + $filter->suppress(false); + $this->assertTrue($filter->filter([])); + + $this->assertFalse((new SuppressFilter(new ArrayObject(['suppress' => true])))->filter([])); } public function testWillNotInstantiate(): void { - $this->expectExceptionMessage( - 'Suppress must be a boolean; received "string"' - ); $this->expectException(InvalidArgumentException::class); - new SuppressFilter(['suppress' => 'oups']); - } + $this->expectExceptionMessage('Suppress must be a boolean; received "string"'); - public function testFilter(): void - { - $result = $this->subject->filter([]); - - $this->assertIsBool($result); - } - - public function testSuppress(): void - { - $this->expectNotToPerformAssertions(); - $this->subject->suppress(true); + new SuppressFilter(['suppress' => 'oups']); } } diff --git a/test/Filter/ValidatorTest.php b/test/Filter/ValidatorTest.php index 1370801..1d3a233 100644 --- a/test/Filter/ValidatorTest.php +++ b/test/Filter/ValidatorTest.php @@ -4,49 +4,77 @@ namespace DotTest\Log\Filter; +use ArrayObject; +use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Filter\Validator; -use InvalidArgumentException; -use Laminas\Validator\NotEmpty; +use Dot\Log\Manager\FilterPluginManager; +use DotTest\Log\Fixture\NotEmptyValidator; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; +use stdClass; class ValidatorTest extends TestCase { - private Validator $subject; - - protected function setUp(): void + public function testFiltersWithTheValidator(): void { - $this->subject = new Validator(['validator' => new NotEmpty()]); - } + $validator = new NotEmptyValidator(); + $filter = new Validator(['validator' => $validator]); - public function testWillInstantiate(): void - { - $this->assertSame(Validator::class, $this->subject::class); + $this->assertTrue($filter->filter(['message' => 'What a wonderful day to write tests'])); + $this->assertFalse($filter->filter(['message' => ''])); + $this->assertSame(['What a wonderful day to write tests', ''], $validator->values); } - public function testWillNotInstantiateWithEmptyArray(): void + public function testAcceptsAValidatorInstanceOrTraversableOptions(): void { - $this->expectExceptionMessage( - 'Parameter of type NULL is invalid; must implement Laminas\Validator\ValidatorInterface' + $this->assertFalse((new Validator(new NotEmptyValidator()))->filter([])); + $this->assertTrue( + (new Validator(new ArrayObject(['validator' => new NotEmptyValidator()])))->filter(['message' => 'x']) ); - $this->expectException(InvalidArgumentException::class); - new Validator([]); } - public function testFilterWillAcceptMessage(): void + public function testNonBooleanResultsAreCast(): void { - $input = ['message' => 'What a wonderful day to write tests']; + $validator = new class { + public function isValid(mixed $value): int + { + return $value === 'ok' ? 1 : 0; + } + }; - $result = $this->subject->filter($input); + $this->assertTrue((new Validator($validator))->filter(['message' => 'ok'])); + $this->assertFalse((new Validator($validator))->filter(['message' => 'no'])); + } - $this->assertTrue($result); + public function testBuiltByThePluginManager(): void + { + $filter = (new FilterPluginManager())->build('validator', ['validator' => new NotEmptyValidator()]); + + $this->assertTrue($filter->filter(['message' => 'x'])); } - public function testFilterWillNotAcceptMessage(): void + /** + * @return iterable|object, string}> + */ + public static function provideInvalidValidators(): iterable { - $input = ['message' => '']; + yield 'empty options' => [[], 'null']; + yield 'object without isValid()' => [['validator' => new stdClass()], 'stdClass']; + yield 'object given directly' => [new stdClass(), 'stdClass']; + } - $result = $this->subject->filter($input); + /** + * @param array|object $validator + */ + #[DataProvider('provideInvalidValidators')] + public function testRejectsInvalidValidators(array|object $validator, string $type): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'Parameter of type ' . $type . ' is invalid; must be an object with an isValid() method,' + . ' such as a Laminas\Validator\ValidatorInterface' + ); - $this->assertFalse($result); + new Validator($validator); } } diff --git a/test/Fixture/ContainerException.php b/test/Fixture/ContainerException.php new file mode 100644 index 0000000..b8c36de --- /dev/null +++ b/test/Fixture/ContainerException.php @@ -0,0 +1,12 @@ + $services + * @param array $factories + */ + public function __construct( + private array $services = [], + private readonly array $factories = [], + ) { + } + + public function get(string $id): mixed + { + if (array_key_exists($id, $this->services)) { + return $this->services[$id]; + } + + if (! array_key_exists($id, $this->factories)) { + throw new NotFoundException(sprintf('Service "%s" not found', $id)); + } + + $factory = $this->factories[$id]; + try { + if (is_string($factory) && ! is_callable($factory)) { + $factory = new $factory(); + } + if (! is_callable($factory)) { + throw new ContainerException(sprintf('Factory for "%s" is not callable', $id)); + } + $service = $factory($this, $id); + } catch (Throwable $exception) { + throw new ContainerException(sprintf('Service "%s" could not be created', $id), 0, $exception); + } + + return $this->services[$id] = $service; + } + + public function has(string $id): bool + { + return array_key_exists($id, $this->services) || array_key_exists($id, $this->factories); + } +} diff --git a/test/Mock.php b/test/Fixture/MemoryWriter.php similarity index 60% rename from test/Mock.php rename to test/Fixture/MemoryWriter.php index 533f91f..41f605b 100644 --- a/test/Mock.php +++ b/test/Fixture/MemoryWriter.php @@ -2,33 +2,28 @@ declare(strict_types=1); -namespace DotTest\Log; +namespace DotTest\Log\Fixture; use Dot\Log\Writer\AbstractWriter; -class Mock extends AbstractWriter +/** + * Keeps every written event in memory. + */ +class MemoryWriter extends AbstractWriter { - /** - * array of log events - */ + /** @var list> */ public array $events = []; - /** - * shutdown called? - */ public bool $shutdown = false; /** - * Write a message to the log. + * @param array $event */ public function doWrite(array $event): void { $this->events[] = $event; } - /** - * Record shutdown - */ public function shutdown(): void { $this->shutdown = true; diff --git a/test/Fixture/NotEmptyValidator.php b/test/Fixture/NotEmptyValidator.php new file mode 100644 index 0000000..8bed378 --- /dev/null +++ b/test/Fixture/NotEmptyValidator.php @@ -0,0 +1,21 @@ + */ + public array $values = []; + + public function isValid(mixed $value): bool + { + $this->values[] = $value; + + return $value !== null && $value !== ''; + } +} diff --git a/test/Fixture/NotFoundException.php b/test/Fixture/NotFoundException.php new file mode 100644 index 0000000..5b1e114 --- /dev/null +++ b/test/Fixture/NotFoundException.php @@ -0,0 +1,12 @@ +> */ public array $events = []; /** - * Returns TRUE to accept the message + * @param array $event */ public function filter(array $event): bool { diff --git a/test/Formatter/AbstractFormatterTest.php b/test/Formatter/AbstractFormatterTest.php new file mode 100644 index 0000000..ace73f8 --- /dev/null +++ b/test/Formatter/AbstractFormatterTest.php @@ -0,0 +1,83 @@ +subject = new class extends AbstractFormatter { + /** + * @param array $event + */ + public function format(array $event): string + { + return ''; + } + }; + } + + public function testNormalizeEvent(): void + { + $resource = fopen('php://memory', 'r'); + $this->assertNotFalse($resource); + + $normalized = $this->subject->normalizeEvent([ + 'scalar' => 1, + 'null' => null, + 'array' => ['a' => 'b/c'], + 'iterable' => new ArrayObject(['x' => 1]), + 'date' => new DateTimeImmutable('2026-01-02 03:04:05+00:00'), + 'mutable' => new DateTime('2026-01-02 03:04:05+00:00'), + 'stringable' => new class implements Stringable { + public function __toString(): string + { + return 'text'; + } + }, + 'object' => new stdClass(), + 'resource' => $resource, + 'extra' => ['nested' => ['k' => 'v']], + ]); + fclose($resource); + + $this->assertSame([ + 'scalar' => 1, + 'null' => null, + 'array' => '{"a":"b/c"}', + 'iterable' => '{"x":1}', + 'date' => '2026-01-02T03:04:05+00:00', + 'mutable' => '2026-01-02T03:04:05+00:00', + 'stringable' => 'text', + 'object' => 'object(stdClass) {}', + 'resource' => 'resource(stream)', + 'extra' => ['nested' => '{"k":"v"}'], + ], $normalized); + } + + public function testDateTimeFormat(): void + { + $this->assertSame(FormatterInterface::DEFAULT_DATETIME_FORMAT, $this->subject->getDateTimeFormat()); + $this->assertSame($this->subject, $this->subject->setDateTimeFormat('Y-m-d')); + $this->assertSame( + ['date' => '2026-01-02'], + $this->subject->normalizeEvent(['date' => new DateTimeImmutable('2026-01-02')]) + ); + } +} diff --git a/test/Formatter/BaseTest.php b/test/Formatter/BaseTest.php deleted file mode 100644 index a0096f6..0000000 --- a/test/Formatter/BaseTest.php +++ /dev/null @@ -1,43 +0,0 @@ -subject = new Base(); - } - - public function testWillInstantiate(): void - { - $this->assertSame(Base::class, $this->subject::class); - } - - public function testFormat(): void - { - $input = ['value']; - $result = $this->subject->format($input); - $this->assertSame($input, $result); - } - - public function testGetDatetimeFormat(): void - { - $result = $this->subject->getDateTimeFormat(); - $this->assertSame(FormatterInterface::DEFAULT_DATETIME_FORMAT, $result); - } - - public function testSetDatetimeFormat(): void - { - $result = $this->subject->setDateTimeFormat('Y-m-d H:i:s'); - $this->assertSame(Base::class, $result::class); - } -} diff --git a/test/Formatter/JsonTest.php b/test/Formatter/JsonTest.php index a80a8c3..f6458ee 100644 --- a/test/Formatter/JsonTest.php +++ b/test/Formatter/JsonTest.php @@ -5,35 +5,59 @@ namespace DotTest\Log\Formatter; use DateTime; +use DateTimeImmutable; use Dot\Log\Formatter\FormatterInterface; use Dot\Log\Formatter\Json; use PHPUnit\Framework\TestCase; class JsonTest extends TestCase { - private Json $subject; + public function testFormat(): void + { + $result = (new Json())->format([ + 'message' => 'a/b ü', + 'timestamp' => new DateTime('2026-01-02 03:04:05+00:00'), + 'amount' => 1.0, + ]); + + $this->assertSame('{"message":"a/b ü","timestamp":"2026-01-02T03:04:05+00:00","amount":1.0}', $result); + } - protected function setUp(): void + /** + * Regression test: DateTimeImmutable was serialized as an object. + */ + public function testFormatsImmutableAndNestedDates(): void { - $this->subject = new Json(); + $date = new DateTimeImmutable('2026-01-02 03:04:05+00:00'); + $result = (new Json())->setDateTimeFormat('Y-m-d')->format([ + 'timestamp' => $date, + 'context' => ['since' => $date], + ]); + + $this->assertSame('{"timestamp":"2026-01-02","context":{"since":"2026-01-02"}}', $result); } - public function testFormat(): void + /** + * Regression test: JSON_NUMERIC_CHECK turned "0712345678" into 712345678. + */ + public function testKeepsNumericStrings(): void { - $input = ['awesome array', 'timestamp' => new DateTime()]; - $result = $this->subject->format($input); - $this->assertIsString($result); + $result = (new Json())->format(['context' => ['phone' => '0712345678', 'zip' => '01234']]); + + $this->assertSame('{"context":{"phone":"0712345678","zip":"01234"}}', $result); } - public function testGetDatetimeFormat(): void + public function testInvalidUtf8IsSubstituted(): void { - $result = $this->subject->getDateTimeFormat(); - $this->assertSame(FormatterInterface::DEFAULT_DATETIME_FORMAT, $result); + $this->assertSame("{\"message\":\"a\u{FFFD}\"}", (new Json())->format(['message' => "a\xB1"])); } - public function testSetDatetimeFormat(): void + public function testDateTimeFormat(): void { - $result = $this->subject->setDateTimeFormat('Y-m-d H:i:s'); - $this->assertSame(Json::class, $result::class); + $subject = new Json(); + + $this->assertSame(FormatterInterface::DEFAULT_DATETIME_FORMAT, $subject->getDateTimeFormat()); + $this->assertSame($subject, $subject->setDateTimeFormat('Y-m-d H:i:s')); + $this->assertSame('Y-m-d H:i:s', $subject->getDateTimeFormat()); } } diff --git a/test/Formatter/SimpleTest.php b/test/Formatter/SimpleTest.php index c3bb946..a97a800 100644 --- a/test/Formatter/SimpleTest.php +++ b/test/Formatter/SimpleTest.php @@ -4,36 +4,71 @@ namespace DotTest\Log\Formatter; +use ArrayObject; use DateTime; +use DateTimeImmutable; use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Formatter\Simple; use PHPUnit\Framework\TestCase; class SimpleTest extends TestCase { - private Simple $subject; + /** + * @param array $extra + * @return array + */ + private function event(array $extra = []): array + { + return [ + 'timestamp' => new DateTimeImmutable('2026-01-02 03:04:05+00:00'), + 'levelName' => 'critical', + 'level' => 2, + 'message' => 'Test Message', + 'extra' => $extra, + ]; + } - protected function setUp(): void + public function testDefaultFormat(): void { - $this->subject = new Simple(Simple::DEFAULT_FORMAT); + $this->assertSame( + '2026-01-02T03:04:05+00:00 critical (2): Test Message', + (new Simple())->format($this->event()) + ); } - public function testWillInstantiate(): void + public function testExtraIsPrintedAsJson(): void { - $this->assertSame(Simple::class, $this->subject::class); + $this->assertSame( + '2026-01-02T03:04:05+00:00 critical (2): Test Message {"user":"x"}', + (new Simple())->format($this->event(['user' => 'x'])) + ); } - public function testWillNotInstantiate(): void + /** + * Regression test: events from Logger have no "extra" key, and a literal "%extra%" was written. + */ + public function testEventWithoutExtra(): void { - $this->expectExceptionMessage('Format must be a string'); - $this->expectException(InvalidArgumentException::class); - new Simple(['format' => new DateTime()]); + $event = $this->event(); + unset($event['extra']); + + $this->assertSame('2026-01-02T03:04:05+00:00 critical (2): Test Message', (new Simple())->format($event)); + } + + public function testCustomFormatAndDateFormatFromOptions(): void + { + $formatter = new Simple(new ArrayObject(['format' => '%timestamp% %message%', 'dateTimeFormat' => 'Y'])); + + $this->assertSame('2026 Test Message', $formatter->format($this->event())); + $this->assertSame('Test Message', (new Simple('%message%'))->format($this->event())); + $this->assertSame('2026', (new Simple('%timestamp%', 'Y'))->format($this->event())); } - public function testFormat(): void + public function testWillNotInstantiate(): void { - $input = ['message' => 'Test Message', 'levelName' => 'Critical']; - $result = $this->subject->format($input); - $this->assertIsString($result); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Format must be a string'); + + new Simple(['format' => new DateTime()]); } } diff --git a/test/LoggerServiceFactoryTest.php b/test/LoggerServiceFactoryTest.php index b9a055b..d5bc6a7 100644 --- a/test/LoggerServiceFactoryTest.php +++ b/test/LoggerServiceFactoryTest.php @@ -4,215 +4,131 @@ namespace DotTest\Log; +use ArrayObject; +use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Logger; use Dot\Log\LoggerServiceFactory; use Dot\Log\Manager\ProcessorPluginManager; use Dot\Log\Manager\WriterPluginManager; use Dot\Log\Processor\PsrPlaceholder; use Dot\Log\Writer\Noop; -use Laminas\ServiceManager\Exception\ServiceNotCreatedException; -use Laminas\ServiceManager\Exception\ServiceNotFoundException; -use Laminas\ServiceManager\ServiceLocatorInterface; -use Laminas\ServiceManager\ServiceManager; -use Laminas\Stdlib\ArrayObject; +use DotTest\Log\Fixture\InMemoryContainer; +use DotTest\Log\Fixture\MemoryWriter; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; -use Psr\Container\NotFoundExceptionInterface; use stdClass; -use function count; - class LoggerServiceFactoryTest extends TestCase { - protected ServiceLocatorInterface $serviceManager; - - /** - * Set up LoggerServiceFactory and loggers configuration. - */ - protected function setUp(): void + public function testCreatesALoggerFromTheLogConfig(): void { - $this->serviceManager = new ServiceManager([ - 'aliases' => [ - 'Dot\Log' => Logger::class, - ], - 'factories' => [ - Logger::class => LoggerServiceFactory::class, - ], - 'services' => [ - 'config' => [ - 'log' => [], - ], - ], - ]); - } - - public static function providerValidLoggerService(): array - { - return [ - [Logger::class], - ['Dot\Log'], - ]; - } + $container = new InMemoryContainer(['config' => ['log' => ['writers' => [['name' => 'noop']]]]]); - public static function providerInvalidLoggerService(): array - { - return [ - ['log'], - ['Logger\Application\Frontend'], - ['writers'], - ]; - } + $logger = (new LoggerServiceFactory())($container, Logger::class); - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - * @dataProvider providerValidLoggerService - */ - public function testValidLoggerService(string $service): void - { - $actual = $this->serviceManager->get($service); - self::assertInstanceOf(Logger::class, $actual); + $this->assertCount(1, $logger->getWriters()); } - /** - * @dataProvider providerInvalidLoggerService - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testInvalidLoggerService(string $service): void + public function testCreatesALoggerWithoutConfig(): void { - $this->expectException(ServiceNotFoundException::class); - $this->serviceManager->get($service); + $this->assertCount(0, (new LoggerServiceFactory())(new InMemoryContainer())->getWriters()); } - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillInjectWriterPluginManagerIfAvailable(): void + public function testWillInjectWriterPluginManagerNamedAsService(): void { - $writers = new WriterPluginManager(new ServiceManager()); - - $services = new ServiceManager([ - 'factories' => [ - Logger::class => LoggerServiceFactory::class, - ], - 'services' => [ - 'LogWriterManager' => $writers, - 'config' => [ - 'log' => [ - 'writers' => [['name' => 'noop', 'level' => 1]], - ], + $writers = new WriterPluginManager(null, ['aliases' => ['memory' => MemoryWriter::class]]); + $container = new InMemoryContainer([ + 'MyWriters' => $writers, + 'config' => [ + 'log' => [ + 'writer_plugin_manager' => 'MyWriters', + 'writers' => [['name' => 'memory', 'level' => 1]], ], ], ]); - $log = $services->get(Logger::class); - $logWriters = $log->getWriters(); - self::assertEquals(1, count($logWriters)); - $this->assertInstanceOf(Noop::class, $logWriters->current()); + $logger = (new LoggerServiceFactory())($container, Logger::class); + + $this->assertSame($writers, $logger->getWriterPluginManager()); + $this->assertInstanceOf(MemoryWriter::class, $logger->getWriters()->current()); } - /** - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface - */ - public function testWillInjectProcessorPluginManagerIfAvailable(): void + public function testWillInjectProcessorPluginManagerNamedAsService(): void { - $processors = new ProcessorPluginManager(new ServiceManager()); - - $services = new ServiceManager([ - 'factories' => [ - Logger::class => LoggerServiceFactory::class, - ], - 'services' => [ - 'LogProcessorManager' => $processors, - 'config' => [ - 'log' => [ - 'writers' => [['name' => Noop::class, 'level' => 1]], - 'processors' => [['name' => 'psrplaceholder', 'level' => 1]], - ], + $processors = new ProcessorPluginManager(); + $container = new InMemoryContainer([ + 'MyProcessors' => $processors, + 'config' => [ + 'log' => [ + 'processor_plugin_manager' => 'MyProcessors', + 'writers' => [['name' => Noop::class, 'level' => 1]], + 'processors' => [['name' => 'psrplaceholder', 'level' => 1]], ], ], ]); - $log = $services->get(Logger::class); - $logProcessors = $log->getProcessors(); - self::assertEquals(1, count($logProcessors)); - $this->assertInstanceOf(PsrPlaceholder::class, $logProcessors->current()); + $logger = (new LoggerServiceFactory())($container, Logger::class); + + $this->assertSame($processors, $logger->getProcessorPluginManager()); + $this->assertInstanceOf(PsrPlaceholder::class, $logger->getProcessors()->current()); } /** - * @dataProvider dataWritersValues() - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface + * @return iterable */ - public function testWritersValue(mixed $writers, int $count): void + public static function dataWritersValues(): iterable { - $services = new ServiceManager([ - 'factories' => [ - Logger::class => LoggerServiceFactory::class, - ], - 'services' => [ - 'config' => [ - 'log' => [ - 'writers' => $writers, - ], - ], - ], - ]); - - $log = $services->get(Logger::class); - self::assertCount($count, $log->getWriters()); + yield 'null' => [null, 0]; + yield 'string' => ['writers config', 0]; + yield 'number' => [1e3, 0]; + yield 'object' => [new stdClass(), 0]; + yield 'empty iterable' => [new ArrayObject(), 0]; + yield 'iterable' => [new ArrayObject([['name' => Noop::class, 'level' => 1]]), 1]; } - public static function dataWritersValues(): array + #[DataProvider('dataWritersValues')] + public function testWritersValue(mixed $writers, int $count): void { - return [ - 'null' => [null, 0], - 'string' => ['writers config', 0], - 'number' => [1e3, 0], - 'object' => [new stdClass(), 0], - 'empty iterable' => [new ArrayObject(), 0], - 'iterable' => [new ArrayObject([['name' => Noop::class, 'level' => 1]]), 1], - ]; + $container = new InMemoryContainer(['config' => ['log' => ['writers' => $writers]]]); + + $this->assertCount($count, (new LoggerServiceFactory())($container, Logger::class)->getWriters()); } /** - * @dataProvider dataInvalidWriterConfig() - * @throws ContainerExceptionInterface - * @throws NotFoundExceptionInterface + * @return iterable */ + public static function dataInvalidWriterConfig(): iterable + { + yield 'string' => ['invalid config', 'string']; + yield 'object' => [new stdClass(), 'stdClass']; + } + + #[DataProvider('dataInvalidWriterConfig')] public function testInvalidWriterConfig(mixed $value, string $type): void { - $services = new ServiceManager([ - 'factories' => [ - Logger::class => LoggerServiceFactory::class, - ], - 'services' => [ - 'config' => [ - 'log' => [ - 'writers' => [ - $value, - ], - ], - ], - ], - ]); + $container = new InMemoryContainer(['config' => ['log' => ['writers' => [$value]]]]); - self::expectException(ServiceNotCreatedException::class); - self::expectExceptionMessage( - 'config log.writers[] must contain array or ArrayAccess, ' . $type . ' provided' - ); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('config log.writers[] must contain array or ArrayAccess, ' . $type . ' provided'); - $services->get(Logger::class); + (new LoggerServiceFactory())($container, Logger::class); } - public static function dataInvalidWriterConfig(): array + public function testInvalidLogConfig(): void { - return [ - 'string' => ['invalid config', 'string'], - 'object' => [new stdClass(), 'stdClass'], - ]; + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('config "log" must be an array; string provided'); + + (new LoggerServiceFactory())(new InMemoryContainer(['config' => ['log' => 'x']]), Logger::class); + } + + public function testInvalidManagerConfig(): void + { + $container = new InMemoryContainer(['config' => ['dot_log' => ['writer_manager' => 'x']]]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('config "dot_log.writer_manager" must be an array'); + + (new LoggerServiceFactory())($container, Logger::class); } } diff --git a/test/LoggerTest.php b/test/LoggerTest.php index 9651332..b60412a 100644 --- a/test/LoggerTest.php +++ b/test/LoggerTest.php @@ -5,49 +5,72 @@ namespace DotTest\Log; use ArrayObject; +use DateTimeImmutable; +use DateTimeInterface; use Dot\Log\Exception\InvalidArgumentException; use Dot\Log\Exception\RuntimeException; +use Dot\Log\Exception\ServiceNotFoundException; use Dot\Log\Logger; +use Dot\Log\Manager\ProcessorPluginManager; use Dot\Log\Manager\WriterPluginManager; use Dot\Log\Processor\Backtrace; use Dot\Log\Processor\RequestId; use Dot\Log\Writer\Noop; use Dot\Log\Writer\Stream; +use DotTest\Log\Fixture\MemoryWriter; +use DotTest\Log\Fixture\RecordingFilter; use ErrorException; use Exception; -use Laminas\ServiceManager\Exception\ServiceNotFoundException; use Laminas\Stdlib\SplPriorityQueue; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerExceptionInterface; +use stdClass; +use Stringable; +use function array_column; use function count; -use function set_exception_handler; +use function error_reporting; +use function trigger_error; +use const E_ALL; +use const E_USER_DEPRECATED; use const E_USER_NOTICE; +use const E_USER_WARNING; class LoggerTest extends TestCase { private Logger $subject; + private MemoryWriter $writer; + protected function setUp(): void { $this->subject = new Logger(); + $this->writer = new MemoryWriter(); } - public function testUsesWriterPluginManagerByDefault(): void + /** + * @return array + */ + private function lastEvent(): array { - $this->assertInstanceOf(WriterPluginManager::class, $this->subject->getWriterPluginManager()); + $this->assertNotEmpty($this->writer->events); + + return $this->writer->events[0]; } - /** - * @throws ContainerExceptionInterface - */ - public function testPassingShortNameToPluginReturnsWriterByThatName(): void + public function testDefaultPluginManagersAreCreatedOnce(): void + { + $this->assertSame($this->subject->getWriterPluginManager(), $this->subject->getWriterPluginManager()); + $this->assertSame($this->subject->getProcessorPluginManager(), $this->subject->getProcessorPluginManager()); + } + + public function testUnknownWriterPlugin(): void { $this->expectException(ServiceNotFoundException::class); - $this->expectExceptionMessage( - 'Unable to resolve service "mock" to a factory; are you certain you provided it during configuration?' - ); + $this->expectExceptionMessage('Unable to resolve plugin "mock" in ' . WriterPluginManager::class); + $this->subject->writerPlugin('mock'); } @@ -55,252 +78,315 @@ public function testEmptyWriter(): void { $this->expectException(RuntimeException::class); $this->expectExceptionMessage('No log writer specified'); + $this->subject->log(Logger::INFO, 'test'); } - /** - * @throws ContainerExceptionInterface - */ public function testSetWriters(): void { - $writer = $this->subject->writerPlugin('null'); $writers = new SplPriorityQueue(); - $writers->insert($writer, 1); + $writers->insert($this->subject->writerPlugin('null'), 1); + $this->subject->setWriters($writers); - $writers = $this->subject->getWriters(); - $writer = $writers->extract(); - $this->assertInstanceOf(Noop::class, $writer); + $this->assertInstanceOf(Noop::class, $this->subject->getWriters()->extract()); } - /** - * @throws ContainerExceptionInterface - */ - public function testAddWriterWithLevel(): void + public function testSetWritersRejectsOtherObjects(): void { - $writer = $this->subject->writerPlugin('null'); - $this->subject->addWriter($writer, 3); - $writers = $this->subject->getWriters(); + $writers = new SplPriorityQueue(); + $writers->insert(new stdClass(), 1); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Writers must be a SplPriorityQueue of Dot\Log\Writer\WriterInterface'); - $writer = $writers->extract(); - $this->assertInstanceOf(Noop::class, $writer); + $this->subject->setWriters($writers); } - /** - * @throws ContainerExceptionInterface - */ - public function testAddWithSameLevel(): void + public function testWritersRunByPriority(): void { - $writer1 = $this->subject->writerPlugin('null'); - $this->subject->addWriter($writer1, 1); - $writer2 = $this->subject->writerPlugin('null'); - $this->subject->addWriter($writer2, 1); - $writers = $this->subject->getWriters(); + $low = new MemoryWriter(); + $high = new MemoryWriter(); + $this->subject->addWriter($low, 1); + $this->subject->addWriter($high, 3); - $writer = $writers->extract(); - $this->assertInstanceOf(Noop::class, $writer); - $writer = $writers->extract(); - $this->assertInstanceOf(Noop::class, $writer); + $this->assertSame([$high, $low], $this->subject->getWriters()->toArray()); } - /** - * @throws ContainerExceptionInterface - */ public function testLogging(): void { - $writer = new Mock(); - $this->subject->addWriter($writer); + $this->subject->addWriter($this->writer); + $this->subject->log(Logger::INFO, 'tottakai'); $this->subject->log(4, 'tottakai'); $this->subject->log('2', 'tottakai'); + $this->subject->log('debug', 'tottakai'); - $this->assertEquals(3, count($writer->events)); - foreach ($writer->events as $event) { - $this->assertStringContainsString('tottakai', $event['message']); - } + $this->assertCount(4, $this->writer->events); + $this->assertSame([6, 4, 2, 7], array_column($this->writer->events, 'level')); + $this->assertSame( + ['info', 'warning', 'critical', 'debug'], + array_column($this->writer->events, 'levelName') + ); + $this->assertInstanceOf(DateTimeImmutable::class, $this->lastEvent()['timestamp']); + } + + /** + * @return iterable + */ + public static function provideInvalidLevels(): iterable + { + yield 'negative' => [-1]; + yield 'too high' => [8]; + yield 'unknown name' => ['verbose']; + yield 'fraction' => [2.5]; + yield 'null' => [null]; + } + + #[DataProvider('provideInvalidLevels')] + #[Group('Laminas-7238')] + public function testRejectsInvalidLevels(mixed $level): void + { + $this->subject->addWriter($this->writer); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('$level must be an integer >= 0 and < 8; received '); + + $this->subject->log($level, 'Foo'); } - public static function provideTestPlaceholders(): array + /** + * @return iterable}> + */ + public static function provideTestPlaceholders(): iterable { $context = [ 'placeholder1' => 1, '#placeholder2' => 'placeholder2', - 'placeholder3' => new class { - }, + 'placeholder3' => new stdClass(), ]; - return [ - ["message with no placeholders", $context], - ["{placeholder1, {#placeholder2}, place_holder3} invalid placeholders", $context], - ["{placeholder1}, {#placeholder2}, {place_holder3}", []], + yield 'no placeholders' => ['message with no placeholders', $context]; + yield 'invalid placeholders' => [ + '{placeholder1, {#placeholder2}, place_holder3} invalid placeholders', + $context, ]; + yield 'no context' => ['{placeholder1}, {#placeholder2}, {place_holder3}', []]; + yield 'null value' => ['{nothing}', ['nothing' => null]]; } /** - * @dataProvider provideTestPlaceholders + * @param array $context */ + #[DataProvider('provideTestPlaceholders')] public function testLoggingWithoutValidPlaceholdersDoesNotModifyMessage(string $message, array $context): void { - $writer = new Mock(); - $this->subject->addWriter($writer); - $this->subject->log(Logger::INFO, $message, $context); + $this->subject->addWriter($this->writer); - $this->assertEquals(1, count($writer->events)); + $this->subject->log(Logger::INFO, $message, $context); - $this->assertEquals( - $message, - $writer->events[0]['message'] - ); + $this->assertSame($message, $this->lastEvent()['message']); } public function testLoggingWithValidPlaceholders(): void { - $message = - "{placeholder1}, {place.holder2}, {place_holder3} and {placeholder4}. {placeholder5} test {placeholder6}"; - $context = [ - 'placeholder1' => 1, - 'place.holder2' => 'placeholder2', - 'place_holder3' => new class { - public function hello(): string - { - return 'Hello world!'; - } - }, - 'placeholder4' => ['array' => 'placeholder4'], - 'placeholder5' => 5.5, - 'placeholder6' => static fn($arg1, $arg2) => $arg1 + $arg2, - ]; + $this->subject->addWriter($this->writer); + $stringable = new class implements Stringable { + public function __toString(): string + { + return 'ID-42'; + } + }; - $writer = new Mock(); - $this->subject->addWriter($writer); - $this->subject->log(Logger::INFO, $message, $context); + $this->subject->log( + Logger::INFO, + '{p1}, {place.holder2}, {place_holder3}, {p4}, {p5}, {p6}, {p7}, {p8}, {p9}', + [ + 'p1' => 1, + 'place.holder2' => 'placeholder2', + 'place_holder3' => new stdClass(), + 'p4' => ['array' => 'placeholder4'], + 'p5' => 5.5, + 'p6' => static fn (): int => 1, + 'p7' => $stringable, + 'p8' => new DateTimeImmutable('2026-01-02 03:04:05+00:00'), + 'p9' => false, + ] + ); - $this->assertEquals(1, count($writer->events)); - $this->assertEquals( - '1, placeholder2, object and array. 5.5 test object', - $writer->events[0]['message'] + $this->assertSame( + '1, placeholder2, [object stdClass], [array], 5.5, [object Closure], ID-42, ' + . '2026-01-02T03:04:05+00:00, false', + $this->lastEvent()['message'] + ); + } + + public function testPlaceholderValue(): void + { + $this->assertSame('true', Logger::placeholderValue(true)); + $this->assertSame( + (new DateTimeImmutable('@0'))->format(DateTimeInterface::RFC3339), + Logger::placeholderValue(new DateTimeImmutable('@0')) ); } - /** - * @throws ContainerExceptionInterface - */ public function testLoggingStringable(): void { - $test = new class { + $this->subject->addWriter($this->writer); + + $this->subject->log(Logger::INFO, new class implements Stringable { public function __toString(): string { return 'test'; } - }; - - $writer = new Mock(); - $this->subject->addWriter($writer); - $this->subject->log(Logger::INFO, $test); + }); - $this->assertEquals(1, count($writer->events)); - $this->assertStringContainsString('test', $writer->events[0]['message']); + $this->assertSame('test', $this->lastEvent()['message']); } - /** - * @throws ContainerExceptionInterface - */ public function testAddFilter(): void { - $writer = new Mock(); - $filter = new MockFilter(); - $writer->addFilter($filter); - $this->subject->addWriter($writer); + $filter = new RecordingFilter(); + $this->writer->addFilter($filter); + $this->subject->addWriter($this->writer); + $this->subject->log(Logger::INFO, 'test'); - $this->assertEquals(1, count($filter->events)); - $this->assertStringContainsString('test', $filter->events[0]['message']); + $this->assertCount(1, $filter->events); + $this->assertSame('test', $filter->events[0]['message']); } - public static function provideTestFilters(): array + /** + * @return iterable}> + */ + public static function provideTestFilters(): iterable { - return [ - ['level', ['level' => Logger::INFO]], - ['regex', ['regex' => '/[0-9]+/']], - ]; + yield 'level' => ['level', ['level' => Logger::INFO]]; + yield 'regex' => ['regex', ['regex' => '/[0-9]+/']]; } /** - * @dataProvider provideTestFilters - * @throws ContainerExceptionInterface + * @param array $options */ + #[DataProvider('provideTestFilters')] public function testAddFilterByNameWithParams(string $filter, array $options): void { - $writer = new Mock(); - $writer->addFilter($filter, $options); - $this->subject->addWriter($writer); + $this->writer->addFilter($filter, $options); + $this->subject->addWriter($this->writer); $this->subject->log(Logger::INFO, '123'); - $this->assertEquals(1, count($writer->events)); - $this->assertStringContainsString('123', $writer->events[0]['message']); + + $this->assertSame('123', $this->lastEvent()['message']); } - public static function provideAttributes(): array + /** + * @return iterable|ArrayObject}> + */ + public static function provideAttributes(): iterable { - return [ - [[]], - [['user' => 'foo', 'ip' => '127.0.0.1']], - [new ArrayObject(['id' => 42])], - ]; + yield 'empty' => [[]]; + yield 'array' => [['user' => 'foo', 'ip' => '127.0.0.1']]; + yield 'traversable' => [new ArrayObject(['id' => 42])]; } /** - * @dataProvider provideAttributes - * @throws ContainerExceptionInterface + * @param array|ArrayObject $context */ + #[DataProvider('provideAttributes')] public function testLoggingCustomAttributesForUserContext(array|ArrayObject $context): void { - $writer = new Mock(); - $this->subject->addWriter($writer); + $this->subject->addWriter($this->writer); + $this->subject->log(Logger::ERR, 'tottakai', $context); - $this->assertEquals(1, count($writer->events)); - $this->assertIsArray($writer->events[0]['context']); - $this->assertEquals(count($writer->events[0]['context']), count($context)); + $this->assertIsArray($this->lastEvent()['context']); + $this->assertCount(count($context), $this->lastEvent()['context']); } /** - * @throws ContainerExceptionInterface + * PHPUnit masks error_reporting() while a test runs, so it is raised to E_ALL around the trigger. */ public function testRegisterErrorHandler(): void { - $writer = new Mock(); - $this->subject->addWriter($writer); + $this->subject->addWriter($this->writer); + + $previousLevel = error_reporting(E_ALL); + try { + $previous = Logger::registerErrorHandler($this->subject); + $this->assertNotFalse($previous); + $this->assertFalse(Logger::registerErrorHandler($this->subject), 'registers once'); + + trigger_error('dot-log test warning', E_USER_WARNING); + } finally { + Logger::unregisterErrorHandler(); + error_reporting($previousLevel); + } + + $event = $this->lastEvent(); + $this->assertSame('dot-log test warning', $event['message']); + $this->assertSame(Logger::WARN, $event['level']); + $this->assertIsArray($event['context']); + $this->assertSame(E_USER_WARNING, $event['context']['errno'], 'errno is the PHP error number'); + $this->assertSame(__FILE__, $event['context']['file']); + } + + public function testErrorHandlerSkipsErrorsOutsideErrorReporting(): void + { + $this->subject->addWriter($this->writer); + $handler = Logger::createErrorHandler($this->subject, true); + + $previousLevel = error_reporting(E_ALL & ~E_USER_DEPRECATED); + try { + $this->assertFalse($handler(E_USER_DEPRECATED, 'ignored', __FILE__, __LINE__)); + $this->assertFalse($handler(E_USER_NOTICE, 'logged', __FILE__, __LINE__)); + } finally { + error_reporting($previousLevel); + } - $previous = Logger::registerErrorHandler($this->subject); - $this->assertNotNull($previous); - $this->assertNotFalse($previous); + $this->assertCount(1, $this->writer->events); + $this->assertSame(Logger::NOTICE, $this->lastEvent()['level']); + } - // check for single error handler instance - $this->assertFalse(Logger::registerErrorHandler($this->subject)); + public function testExceptionHandlerLogsTheChainInnermostFirst(): void + { + $this->subject->addWriter($this->writer); + $handler = Logger::createExceptionHandler($this->subject); - // generate a warning - echo $test; // $test is not defined + $handler(new Exception('error', 200, new Exception('previous', 100))); + $handler(new ErrorException('user notice', 1_000, E_USER_NOTICE, __FILE__, __LINE__)); - Logger::unregisterErrorHandler(); + $expectedEvents = [ + ['level' => Logger::ERR, 'message' => 'previous'], + ['level' => Logger::ERR, 'message' => 'error'], + ['level' => Logger::NOTICE, 'message' => 'user notice'], + ]; + $this->assertCount(3, $this->writer->events); + foreach ($expectedEvents as $i => $expected) { + $event = $this->writer->events[$i]; + $this->assertSame($expected['level'], $event['level']); + $this->assertSame($expected['message'], $event['message']); + $this->assertIsArray($event['context']); + $this->assertSame(__FILE__, $event['context']['file']); + } + } - $this->assertEquals('Undefined variable $test', $writer->events[0]['message']); + public function testRegisterExceptionHandlerOnlyOnce(): void + { + try { + $this->assertTrue(Logger::registerExceptionHandler($this->subject)); + $this->assertFalse(Logger::registerExceptionHandler($this->subject)); + } finally { + Logger::unregisterExceptionHandler(); + } } - /** - * @throws ContainerExceptionInterface - */ - public function testOptionsWithMock(): void + public function testOptionsWithWriter(): void { - $options = [ + $logger = new Logger([ 'writers' => [ - 'first_writer' => [ - 'name' => 'null', - 'level' => 1, - ], + 'first_writer' => ['name' => 'null', 'level' => 1], ], - ]; - $logger = new Logger($options); + ]); $writers = $logger->getWriters()->toArray(); $this->assertCount(1, $writers); @@ -308,133 +394,172 @@ public function testOptionsWithMock(): void } /** - * @throws ContainerExceptionInterface + * Regression test: "level" is documented as optional but omitting it threw a TypeError. + */ + public function testWriterAndProcessorLevelIsOptional(): void + { + $logger = new Logger([ + 'writers' => [['name' => 'noop']], + 'processors' => [['name' => 'requestid']], + ]); + + $this->assertCount(1, $logger->getWriters()); + $this->assertCount(1, $logger->getProcessors()); + } + + public function testPriorityIsAnAliasOfLevel(): void + { + $first = new MemoryWriter(); + $second = new MemoryWriter(); + $writers = new WriterPluginManager(null, [ + 'factories' => [ + 'first' => static fn (): MemoryWriter => $first, + 'second' => static fn (): MemoryWriter => $second, + ], + ]); + + $logger = new Logger([ + 'writer_plugin_manager' => $writers, + 'writers' => [['name' => 'second', 'priority' => 1], ['name' => 'first', 'priority' => 5]], + ]); + + $this->assertSame([$first, $second], $logger->getWriters()->toArray()); + } + + /** + * @return iterable, string}> + */ + public static function provideInvalidPluginSpecs(): iterable + { + yield 'writer without name' => [['writers' => [['level' => 1]]], 'Options must contain a name for the writer']; + yield 'writer not an array' => [['writers' => ['noop']], 'Options must contain a name for the writer']; + yield 'processor without name' => [ + ['processors' => [['level' => 1]]], + 'Options must contain a name for the processor', + ]; + yield 'non-numeric level' => [ + ['writers' => [['name' => 'noop', 'level' => 'high']]], + 'The writer "noop" level must be an integer; received string', + ]; + } + + /** + * @param array $options + */ + #[DataProvider('provideInvalidPluginSpecs')] + public function testInvalidPluginSpecs(array $options, string $message): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + + new Logger($options); + } + + /** + * Regression test: options given as a generator were dropped. */ + public function testOptionsAsGenerator(): void + { + $options = (static function (): iterable { + yield 'writers' => [['name' => 'noop', 'options' => new ArrayObject([])]]; + })(); + + $this->assertCount(1, (new Logger($options))->getWriters()); + } + public function testOptionsWithWriterOptions(): void { - $options = [ + $logger = new Logger([ 'writers' => [ [ 'name' => 'stream', - 'options' => [ - 'stream' => 'php://output', - 'log_separator' => 'foo', - ], + 'options' => ['stream' => 'php://memory', 'log_separator' => 'foo'], 'level' => 1, ], ], - ]; - $logger = new Logger($options); + ]); $writers = $logger->getWriters()->toArray(); $this->assertCount(1, $writers); $this->assertInstanceOf(Stream::class, $writers[0]); - $this->assertEquals('foo', $writers[0]->getLogSeparator()); + $this->assertSame('foo', $writers[0]->getLogSeparator()); } - /** - * @throws ContainerExceptionInterface - */ - public function testOptionsWithMockAndProcessor(): void + public function testOptionsWithWriterAndProcessor(): void { - $options = [ - 'writers' => [ - 'first_writer' => [ - 'name' => 'null', - 'level' => 1, - ], - ], - 'processors' => [ - 'first_processor' => [ - 'name' => 'requestid', - 'level' => 1, - ], - ], - ]; - $logger = new Logger($options); + $logger = new Logger([ + 'writers' => ['first_writer' => ['name' => 'null', 'level' => 1]], + 'processors' => ['first_processor' => ['name' => 'requestid', 'level' => 1]], + ]); + $processors = $logger->getProcessors()->toArray(); $this->assertCount(1, $processors); $this->assertInstanceOf(RequestId::class, $processors[0]); } - /** - * @throws ContainerExceptionInterface - */ public function testAddProcessor(): void { $processor = new Backtrace(); $this->subject->addProcessor($processor); - $processors = $this->subject->getProcessors()->toArray(); - $this->assertEquals($processor, $processors[0]); + $this->assertSame([$processor], $this->subject->getProcessors()->toArray()); } /** - * @throws ContainerExceptionInterface + * Regression test: Backtrace ignored "Laminas\Log" and reported Dot\Log\Logger::log as the origin. */ - public function testAddProcessorByName(): void + public function testBacktraceProcessorReportsTheCaller(): void { $this->subject->addProcessor('backtrace'); + $this->subject->addWriter($this->writer); - $processors = $this->subject->getProcessors()->toArray(); - $this->assertInstanceOf(Backtrace::class, $processors[0]); + $this->subject->error('foo'); + $line = __LINE__ - 1; - $writer = new Mock(); - $this->subject->addWriter($writer); - $this->subject->log(Logger::ERR, 'foo'); + $context = $this->lastEvent()['context']; + $this->assertIsArray($context); + $this->assertSame(self::class, $context['class']); + $this->assertSame(__FUNCTION__, $context['function']); + $this->assertSame(__FILE__, $context['file']); + $this->assertSame($line, $context['line']); } - /** - * @throws ContainerExceptionInterface - */ - public function testExceptionHandler(): void + public function testSetProcessorPluginManagerByClassName(): void { - $writer = new Mock(); - $this->subject->addWriter($writer); - - $this->assertTrue(Logger::registerExceptionHandler($this->subject)); - - // check for single error handler instance - $this->assertFalse(Logger::registerExceptionHandler($this->subject)); - - // get the internal exception handler - $exceptionHandler = set_exception_handler(static function ($e) { - }); - set_exception_handler($exceptionHandler); + $default = $this->subject->getProcessorPluginManager(); - // reset the exception handler - Logger::unregisterExceptionHandler(); + $this->subject->setProcessorPluginManager(ProcessorPluginManager::class); - // call the exception handler - $exceptionHandler(new Exception('error', 200, new Exception('previos', 100))); - $exceptionHandler(new ErrorException('user notice', 1_000, E_USER_NOTICE, __FILE__, __LINE__)); + $this->assertNotSame($default, $this->subject->getProcessorPluginManager()); + } - // check logged messages - $expectedEvents = [ - ['level' => Logger::ERR, 'message' => 'previos', 'file' => __FILE__], - ['level' => Logger::ERR, 'message' => 'error', 'file' => __FILE__], - ['level' => Logger::NOTICE, 'message' => 'user notice', 'file' => __FILE__], - ]; - for ($i = 0; $i < count($expectedEvents); $i++) { - $expectedEvent = $expectedEvents[$i]; - $event = $writer->events[$i]; + public function testSetProcessorPluginManagerRejectsOtherClasses(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Processor plugin manager must extend ' . ProcessorPluginManager::class); - $this->assertEquals($expectedEvent['level'], $event['level'], 'Unexpected level'); - $this->assertEquals($expectedEvent['message'], $event['message'], 'Unexpected message'); - $this->assertEquals($expectedEvent['file'], $event['context']['file'], 'Unexpected file'); - } + $this->subject->setProcessorPluginManager(stdClass::class); } /** - * @group Laminas-7238 - * @throws ContainerExceptionInterface + * Regression test: the destructor iterated the queue itself, which emptied the queue returned by getWriters(). */ - public function testCatchExceptionNotValidLevel(): void + public function testDestructorKeepsTheWritersQueue(): void { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('$level must be an integer >= 0 and < 8; received -1'); - $writer = new Mock(); - $this->subject->addWriter($writer); - $this->subject->log(-1, 'Foo'); + $logger = new Logger(); + $logger->addWriter($this->writer); + $writers = $logger->getWriters(); + unset($logger); + + $this->assertCount(1, $writers); + } + + public function testDestructorShutsWritersDown(): void + { + $logger = new Logger(); + $logger->addWriter($this->writer); + unset($logger); + + $this->assertTrue($this->writer->shutdown); } } diff --git a/test/Manager/FilterPluginManagerTest.php b/test/Manager/FilterPluginManagerTest.php deleted file mode 100644 index fc1bd43..0000000 --- a/test/Manager/FilterPluginManagerTest.php +++ /dev/null @@ -1,43 +0,0 @@ -createMock(ContainerInterface::class); - $this->subject = new FilterPluginManager($container); - } - - public function testValidate(): void - { - $this->expectNotToPerformAssertions(); - $this->subject->validate(new Level(47)); - } - - public function testWillNotValidate(): void - { - $this->expectExceptionMessage( - 'Dot\Log\Manager\FilterPluginManager can only create instances of' - . ' Dot\Log\Filter\FilterInterface; Dot\Log\Formatter\Json is invalid' - ); - $this->expectException(InvalidServiceException::class); - $this->subject->validate(new Json()); - } -} diff --git a/test/Manager/FormatterPluginManagerTest.php b/test/Manager/FormatterPluginManagerTest.php deleted file mode 100644 index bac7b3a..0000000 --- a/test/Manager/FormatterPluginManagerTest.php +++ /dev/null @@ -1,43 +0,0 @@ -createMock(ContainerInterface::class); - $this->subject = new FormatterPluginManager($container); - } - - public function testValidate(): void - { - $this->expectNotToPerformAssertions(); - $this->subject->validate(new Json()); - } - - public function testWillNotValidate(): void - { - $this->expectExceptionMessage( - 'Dot\Log\Manager\FormatterPluginManager can only create instances of' - . ' Dot\Log\Formatter\FormatterInterface; Dot\Log\Filter\Level is invalid' - ); - $this->expectException(InvalidServiceException::class); - $this->subject->validate(new Level(47)); - } -} diff --git a/test/Manager/PluginManagerTest.php b/test/Manager/PluginManagerTest.php new file mode 100644 index 0000000..a016bd5 --- /dev/null +++ b/test/Manager/PluginManagerTest.php @@ -0,0 +1,243 @@ +, string, class-string, array|null}> + */ + public static function provideBuiltInPlugins(): iterable + { + yield 'filter callback' => [ + new FilterPluginManager(), + 'callback', + Callback::class, + ['callback' => static fn (): bool => true], + ]; + yield 'filter level' => [new FilterPluginManager(), 'level', Level::class, ['level' => 3]]; + yield 'filter regex' => [new FilterPluginManager(), 'regex', Regex::class, ['regex' => '/a/']]; + yield 'filter suppress' => [new FilterPluginManager(), 'suppress', SuppressFilter::class, null]; + yield 'filter suppressfilter' => [new FilterPluginManager(), 'suppressfilter', SuppressFilter::class, null]; + yield 'formatter simple' => [new FormatterPluginManager(), 'simple', Simple::class, null]; + yield 'formatter json' => [new FormatterPluginManager(), 'json', Json::class, null]; + yield 'formatter class name' => [new FormatterPluginManager(), Json::class, Json::class, null]; + yield 'processor backtrace' => [new ProcessorPluginManager(), 'backtrace', Backtrace::class, null]; + yield 'processor psrplaceholder' => [ + new ProcessorPluginManager(), + 'psrplaceholder', + PsrPlaceholder::class, + null, + ]; + yield 'processor referenceid' => [new ProcessorPluginManager(), 'referenceid', ReferenceId::class, null]; + yield 'processor requestid' => [new ProcessorPluginManager(), 'requestid', RequestId::class, null]; + yield 'writer noop' => [new WriterPluginManager(), 'noop', Noop::class, null]; + yield 'writer null' => [new WriterPluginManager(), 'null', Noop::class, null]; + yield 'writer laminaslogwriternull' => [new WriterPluginManager(), 'laminaslogwriternull', Noop::class, null]; + yield 'writer stream' => [new WriterPluginManager(), 'stream', Stream::class, ['stream' => 'php://memory']]; + } + + /** + * @param AbstractPluginManager $manager + * @param class-string $expected + * @param array|null $options + */ + #[DataProvider('provideBuiltInPlugins')] + public function testBuildsBuiltInPlugins( + AbstractPluginManager $manager, + string $name, + string $expected, + ?array $options + ): void { + $this->assertTrue($manager->has($name)); + $this->assertInstanceOf($expected, $manager->build($name, $options)); + } + + public function testPluginsAreNotShared(): void + { + $manager = new FormatterPluginManager(); + + $this->assertNotSame($manager->get('simple'), $manager->get('simple')); + } + + public function testAliasesAreCaseInsensitiveFallback(): void + { + $this->assertInstanceOf(Json::class, (new FormatterPluginManager())->build('JSON')); + } + + public function testBuildPassesOptionsToTheConstructor(): void + { + $formatter = (new FormatterPluginManager())->build('simple', ['format' => '%message%']); + + $this->assertSame('hello', $formatter->format(['message' => 'hello'])); + } + + public function testConfiguredAliasesAndFactoriesAreUsed(): void + { + $manager = new FilterPluginManager(null, [ + 'aliases' => ['everything' => RecordingFilter::class, 'all' => 'everything'], + 'factories' => [ + 'custom' => static fn (ContainerInterface $container, string $name, ?array $options): FilterInterface + => new SuppressFilter((bool) ($options['suppress'] ?? false)), + ], + ]); + + $this->assertInstanceOf(RecordingFilter::class, $manager->build('all')); + $this->assertFalse($manager->build('custom', ['suppress' => true])->filter([])); + } + + public function testFactoryReceivesTheApplicationContainer(): void + { + $container = new InMemoryContainer(['greeting' => 'hello']); + $manager = new FormatterPluginManager($container, [ + 'factories' => [ + 'greeting' => static fn (ContainerInterface $c): FormatterInterface + => new Simple((string) $c->get('greeting')), + ], + ]); + + $this->assertSame($container, $manager->getCreationContext()); + $this->assertSame('hello', $manager->build('greeting')->format([])); + } + + public function testWithoutContainerTheManagerIsTheCreationContext(): void + { + $manager = new WriterPluginManager(); + + $this->assertSame($manager, $manager->getCreationContext()); + } + + public function testFallsBackToTheApplicationContainer(): void + { + $writer = new MemoryWriter(); + $manager = new WriterPluginManager(new InMemoryContainer(['app.writer' => $writer])); + + $this->assertTrue($manager->has('app.writer')); + $this->assertSame($writer, $manager->build('app.writer')); + } + + public function testUnknownPluginThrowsNotFound(): void + { + $this->expectException(ServiceNotFoundException::class); + $this->expectExceptionMessage('Unable to resolve plugin "FileWriter" in ' . WriterPluginManager::class); + + (new WriterPluginManager())->build('FileWriter'); + } + + public function testRejectsPluginsOfTheWrongType(): void + { + $manager = new WriterPluginManager(null, ['aliases' => ['json' => Json::class]]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + WriterPluginManager::class . ' can only create instances of ' + . 'Dot\Log\Writer\WriterInterface; Dot\Log\Formatter\Json is invalid' + ); + + $manager->build('json'); + } + + public function testCircularAliasesAreRejected(): void + { + $manager = new FilterPluginManager(null, ['aliases' => ['a' => 'b', 'b' => 'a']]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Circular plugin alias detected for "a"'); + + $manager->build('a'); + } + + public function testMissingFactoryClassIsReported(): void + { + $manager = new FilterPluginManager(null, ['factories' => ['x' => 'DotTest\Log\DoesNotExist']]); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Factory "DotTest\Log\DoesNotExist" for plugin "x" does not exist'); + + $manager->build('x'); + } + + public function testFactoryClassNameIsInstantiated(): void + { + $manager = new WriterPluginManager(null, [ + 'aliases' => ['memory' => MemoryWriter::class], + 'factories' => [MemoryWriter::class => WriterFactory::class], + ]); + + $this->assertInstanceOf(MemoryWriter::class, $manager->build('memory')); + } + + /** + * @return iterable, string}> + */ + public static function provideInvalidConfig(): iterable + { + yield 'aliases not an array' => [['aliases' => 'x'], 'Plugin manager "aliases" must be an array']; + yield 'alias target not a string' => [ + ['aliases' => ['x' => 1]], + 'Plugin manager aliases must map strings to strings', + ]; + yield 'factories not an array' => [['factories' => 'x'], 'Plugin manager "factories" must be an array']; + yield 'factory not callable' => [ + ['factories' => ['x' => new stdClass()]], + 'Plugin manager factories must map strings to a factory class name or a callable', + ]; + } + + /** + * @param array $config + */ + #[DataProvider('provideInvalidConfig')] + public function testRejectsInvalidConfig(array $config, string $message): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + + new FilterPluginManager(null, $config); + } + + public function testWriterManagerSharesItsFilterAndFormatterManagers(): void + { + $filters = new FilterPluginManager(null, ['aliases' => ['recording' => RecordingFilter::class]]); + $formatters = new FormatterPluginManager(null, ['aliases' => ['short' => Simple::class]]); + $manager = new WriterPluginManager(null, [], $filters, $formatters); + + $writer = $manager->build('noop'); + + $this->assertInstanceOf(Noop::class, $writer); + $this->assertSame($filters, $writer->getFilterPluginManager()); + $this->assertSame($formatters, $writer->getFormatterPluginManager()); + } +} diff --git a/test/Manager/ProcessorPluginManagerTest.php b/test/Manager/ProcessorPluginManagerTest.php deleted file mode 100644 index faa3f61..0000000 --- a/test/Manager/ProcessorPluginManagerTest.php +++ /dev/null @@ -1,43 +0,0 @@ -createMock(ContainerInterface::class); - $this->subject = new ProcessorPluginManager($container); - } - - public function testValidate(): void - { - $this->expectNotToPerformAssertions(); - $this->subject->validate(new Backtrace()); - } - - public function testWillNotValidate(): void - { - $this->expectExceptionMessage( - 'Dot\Log\Manager\ProcessorPluginManager can only create instances of ' - . 'Dot\Log\Processor\ProcessorInterface; Dot\Log\Formatter\Json is invalid' - ); - $this->expectException(InvalidServiceException::class); - $this->subject->validate(new Json()); - } -} diff --git a/test/Manager/WriterPluginManagerTest.php b/test/Manager/WriterPluginManagerTest.php deleted file mode 100644 index 117d155..0000000 --- a/test/Manager/WriterPluginManagerTest.php +++ /dev/null @@ -1,43 +0,0 @@ -createMock(ContainerInterface::class); - $this->subject = new WriterPluginManager($container); - } - - public function testValidate(): void - { - $this->expectNotToPerformAssertions(); - $this->subject->validate(new Noop()); - } - - public function testWillNotValidate(): void - { - $this->expectExceptionMessage( - 'Dot\Log\Manager\WriterPluginManager can only create instances of' - . ' Dot\Log\Writer\WriterInterface; Dot\Log\Formatter\Json is invalid' - ); - $this->expectException(InvalidServiceException::class); - $this->subject->validate(new Json()); - } -} diff --git a/test/Processor/BackTraceTest.php b/test/Processor/BackTraceTest.php index 4f2853a..0f9caa3 100644 --- a/test/Processor/BackTraceTest.php +++ b/test/Processor/BackTraceTest.php @@ -9,27 +9,37 @@ class BackTraceTest extends TestCase { - private Backtrace $subject; - - protected function setUp(): void + public function testProcessAddsTheOriginToTheContext(): void { - $this->subject = new Backtrace(); + $result = (new Backtrace())->process(['context' => ['user' => 'x']]); + + $this->assertIsArray($result['context']); + $this->assertSame('x', $result['context']['user']); + $this->assertArrayHasKey('file', $result['context']); + $this->assertArrayHasKey('line', $result['context']); + $this->assertArrayHasKey('class', $result['context']); + $this->assertArrayHasKey('function', $result['context']); } - public function testWillInstantiate(): void + public function testIgnoredNamespaces(): void { - $this->assertSame(Backtrace::class, $this->subject::class); + $this->assertSame(['Dot\\Log', 'Psr\\Log'], (new Backtrace())->getIgnoredNamespaces()); + $this->assertSame( + ['Dot\\Log', 'Psr\\Log', 'App\\Logging', 'Other'], + (new Backtrace(['ignoredNamespaces' => ['App\\Logging', '', 'Other']]))->getIgnoredNamespaces() + ); + $this->assertSame( + ['Dot\\Log', 'Psr\\Log', 'App'], + (new Backtrace(['ignoredNamespaces' => 'App']))->getIgnoredNamespaces() + ); } - public function testProcess(): void + public function testIgnoredNamespaceMatchesWholeSegments(): void { - $result = $this->subject->process([]); - $this->assertArrayHasKey('context', $result); - } + $result = (new Backtrace(['ignoredNamespaces' => ['DotTest\\Log\\Processor\\BackTrace']]))->process([]); - public function testGetIgnoredNamespaces(): void - { - $result = $this->subject->getIgnoredNamespaces(); - $this->assertIsArray($result); + // "BackTraceTest" is not inside the namespace "BackTrace", so this test is the origin. + $this->assertIsArray($result['context']); + $this->assertSame(self::class, $result['context']['class']); } } diff --git a/test/Processor/PsrPlaceholderTest.php b/test/Processor/PsrPlaceholderTest.php index 4a1dbab..a0e123c 100644 --- a/test/Processor/PsrPlaceholderTest.php +++ b/test/Processor/PsrPlaceholderTest.php @@ -6,36 +6,42 @@ use Dot\Log\Processor\PsrPlaceholder; use PHPUnit\Framework\TestCase; +use stdClass; class PsrPlaceholderTest extends TestCase { - private PsrPlaceholder $subject; - - protected function setUp(): void + public function testMessageWithoutPlaceholdersIsUnchanged(): void { - $this->subject = new PsrPlaceholder(); + $input = ['message' => 'this is a message', 'context' => ['a' => 1]]; + + $this->assertSame($input, (new PsrPlaceholder())->process($input)); } - public function testProcessMessageWithNoCurlyBrackets(): void + public function testEventWithoutContextIsUnchanged(): void { - $input = ["message" => "this is a message"]; + $input = ['message' => '{a}']; - $result = $this->subject->process($input); - $this->assertSame($input, $result); + $this->assertSame($input, (new PsrPlaceholder())->process($input)); } public function testProcess(): void { - $input = [ - "message" => '{nullvalue} of {objectvalue} is in fact a {stringvalue}', - "context" => [ - "nullvalue" => null, - "objectvalue" => $this->subject, - "stringvalue" => "this is a message", + $result = (new PsrPlaceholder())->process([ + 'message' => '{null}|{object}|{string}|{array}|{stringable}', + 'context' => [ + 'null' => null, + 'object' => new stdClass(), + 'string' => 'text', + 'array' => [1], + 'stringable' => new class { + public function __toString(): string + { + return 'cast'; + } + }, ], - ]; + ]); - $result = $this->subject->process($input); - $this->assertNotSame($input['message'], $result['message']); + $this->assertSame('|[object stdClass]|text|[array]|cast', $result['message']); } } diff --git a/test/Processor/ReferenceIdTest.php b/test/Processor/ReferenceIdTest.php index f3d4d82..3caa562 100644 --- a/test/Processor/ReferenceIdTest.php +++ b/test/Processor/ReferenceIdTest.php @@ -9,43 +9,23 @@ class ReferenceIdTest extends TestCase { - private ReferenceId $subject; - - protected function setUp(): void + public function testKeepsAnExistingReferenceId(): void { - $this->subject = new ReferenceId(); - } + $input = ['context' => ['referenceId' => 'something']]; - public function testProcessWithReferenceId(): void - { - $input = [ - "context" => [ - "referenceId" => "something", - ], - ]; - - $result = $this->subject->process($input); - $this->assertSame($input, $result); + $this->assertSame($input, (new ReferenceId())->process($input)); } - public function testProcess(): void + public function testAddsTheReferenceId(): void { - $input = []; + $processor = (new ReferenceId())->setReferenceId('ref-1'); - $result = $this->subject->process($input); - $this->assertArrayHasKey("context", $result); - } - - public function testGetReferenceId(): void - { - $result = $this->subject->getReferenceId(); - $this->assertIsString($result); + $this->assertSame('ref-1', $processor->getReferenceId()); + $this->assertSame(['context' => ['referenceId' => 'ref-1']], $processor->process([])); } - public function testSetReferenceId(): void + public function testGeneratesAReferenceId(): void { - $input = "something"; - $result = $this->subject->setReferenceId($input); - $this->assertSame($input, $result->getReferenceId()); + $this->assertMatchesRegularExpression('/^[a-f0-9]{32}$/', (new ReferenceId())->getReferenceId()); } } diff --git a/test/Processor/RequestIdTest.php b/test/Processor/RequestIdTest.php index 4f80447..913e499 100644 --- a/test/Processor/RequestIdTest.php +++ b/test/Processor/RequestIdTest.php @@ -9,30 +9,23 @@ class RequestIdTest extends TestCase { - private RequestId $subject; - - protected function setUp(): void + public function testKeepsAnExistingRequestId(): void { - $this->subject = new RequestId(); - } + $input = ['context' => ['requestId' => 'something']]; - public function testProcessWithRequestId(): void - { - $input = [ - "context" => [ - "requestId" => "something", - ], - ]; - - $result = $this->subject->process($input); - $this->assertSame($input, $result); + $this->assertSame($input, (new RequestId())->process($input)); } - public function testProcess(): void + public function testAddsTheSameIdToEveryEvent(): void { - $input = []; + $processor = new RequestId(); + + $first = $processor->process([]); + $second = $processor->process(['context' => 'not an array']); - $result = $this->subject->process($input); - $this->assertArrayHasKey("context", $result); + $this->assertIsArray($first['context']); + $this->assertIsArray($second['context']); + $this->assertMatchesRegularExpression('/^[a-f0-9]{32}$/', $first['context']['requestId']); + $this->assertSame($first['context']['requestId'], $second['context']['requestId']); } } diff --git a/test/Writer/AbstractWriterTest.php b/test/Writer/AbstractWriterTest.php new file mode 100644 index 0000000..cdc7951 --- /dev/null +++ b/test/Writer/AbstractWriterTest.php @@ -0,0 +1,189 @@ + ['name' => Simple::class, 'options' => ['format' => '%message%']]]; + $writer = new class ($options) extends MemoryWriter { + /** + * @param array $event + */ + public function line(array $event): string + { + return (string) $this->getFormatter()?->format($event); + } + }; + + $this->assertSame('hello', $writer->line(['message' => 'hello'])); + } + + public function testFiltersFromOptions(): void + { + $recording = new RecordingFilter(); + $writer = new MemoryWriter(new ArrayObject([ + 'filters' => [ + Logger::ERR, + $recording, + ['name' => 'regex', 'options' => ['regex' => '/x/']], + ['name' => 'suppress', 'options' => ['suppress' => true]], + ], + ])); + + $writer->write(['level' => Logger::ERR, 'message' => 'x']); + + $this->assertSame([], $writer->events, 'the suppress filter blocks the event'); + $this->assertCount(1, $recording->events); + } + + public function testSingleFilterOption(): void + { + $writer = new MemoryWriter(['filters' => Logger::ERR]); + + $writer->write(['level' => Logger::INFO]); + $writer->write(['level' => Logger::ERR]); + + $this->assertCount(1, $writer->events); + } + + /** + * @return iterable, string}> + */ + public static function provideInvalidOptions(): iterable + { + yield 'filter without name' => [ + ['filters' => [['options' => []]]], + 'Options must contain a name for the filter', + ]; + yield 'formatter without name' => [ + ['formatter' => ['options' => []]], + 'Options must contain a name for the formatter', + ]; + yield 'filter manager' => [ + ['filter_manager' => new stdClass()], + 'Option "filter_manager" must be a plugin manager instance or class name; received stdClass', + ]; + yield 'formatter manager' => [ + ['formatter_manager' => 1], + 'Option "formatter_manager" must be a plugin manager instance or class name; received int', + ]; + yield 'filter manager class' => [ + ['filter_manager' => stdClass::class], + 'Filter plugin manager must extend ' . FilterPluginManager::class . '; received stdClass', + ]; + yield 'formatter manager class' => [ + ['formatter_manager' => stdClass::class], + 'Formatter plugin manager must extend ' . FormatterPluginManager::class . '; received stdClass', + ]; + } + + /** + * @param array $options + */ + #[DataProvider('provideInvalidOptions')] + public function testInvalidOptions(array $options, string $message): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage($message); + + new MemoryWriter($options); + } + + public function testManagersByClassName(): void + { + $writer = new MemoryWriter([ + 'filter_manager' => FilterPluginManager::class, + 'formatter_manager' => FormatterPluginManager::class, + ]); + + $this->assertInstanceOf(Level::class, $writer->filterPlugin('level', ['level' => 1])); + $this->assertInstanceOf(Simple::class, $writer->formatterPlugin('simple')); + } + + public function testWarningsDuringWriteBecomeExceptions(): void + { + $writer = new class extends AbstractWriter { + /** + * @param array $event + */ + protected function doWrite(array $event): void + { + file_get_contents('/dot-log-test/does-not-exist'); + } + }; + + try { + $writer->write([]); + $this->fail('Expected RuntimeException'); + } catch (RuntimeException $exception) { + $this->assertSame('Unable to write', $exception->getMessage()); + $this->assertStringContainsString( + 'Failed to open stream', + (string) $exception->getPrevious()?->getMessage() + ); + } + + $this->assertFalse(ErrorHandler::started()); + } + + /** + * Regression test: an Error thrown by doWrite() left the error handler started. + */ + public function testErrorHandlerIsStoppedWhenWriteThrowsAnError(): void + { + $writer = new class extends AbstractWriter { + /** + * @param array $event + */ + protected function doWrite(array $event): void + { + throw new TypeError('broken writer'); + } + }; + + try { + $writer->write([]); + $this->fail('Expected TypeError'); + } catch (TypeError $error) { + $this->assertSame('broken writer', $error->getMessage()); + } + + $this->assertFalse(ErrorHandler::started()); + } + + public function testErrorConversionCanBeDisabled(): void + { + $writer = new MemoryWriter(); + $writer->setConvertWriteErrorsToExceptions(false); + + $writer->write(['message' => 'x']); + + $this->assertCount(1, $writer->events); + } +} diff --git a/test/Writer/StreamTest.php b/test/Writer/StreamTest.php index 9f1374d..b9d1b00 100644 --- a/test/Writer/StreamTest.php +++ b/test/Writer/StreamTest.php @@ -4,95 +4,250 @@ namespace DotTest\Log\Writer; +use DateTimeImmutable; use Dot\Log\Exception\InvalidArgumentException; +use Dot\Log\Exception\RuntimeException; use Dot\Log\Formatter\Json; use Dot\Log\Logger; use Dot\Log\Writer\Stream; -use ErrorException; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use stdClass; +use function array_map; +use function decoct; +use function fclose; +use function file_get_contents; +use function fileperms; use function fopen; +use function glob; +use function is_dir; +use function mkdir; +use function rewind; +use function rmdir; +use function stream_get_contents; +use function sys_get_temp_dir; +use function time; +use function touch; +use function uniqid; +use function unlink; + +use const PHP_EOL; class StreamTest extends TestCase { - private Stream $subject; - - private array $options = [ - 'stream' => __DIR__ . '/../../log/error-log-{Y}-{m}-{d}.log', - 'filters' => [ - 'allMessages' => [ - 'name' => 'level', - 'options' => [ - 'operator' => '>=', - 'level' => Logger::EMERG, - ], - ], - ], - 'formatter' => [ - 'name' => Json::class, - ], - ]; + private string $directory; - /** - * @throws ErrorException - */ protected function setUp(): void { - $this->subject = new Stream($this->options); + $this->directory = sys_get_temp_dir() . '/dot-log-stream-' . uniqid(); + mkdir($this->directory); + } + + protected function tearDown(): void + { + array_map(unlink(...), glob($this->directory . '/*') ?: []); + if (is_dir($this->directory)) { + rmdir($this->directory); + } } /** - * @throws ErrorException + * @return array */ - public function testWillNotInstantiateWithInt(): void + private function event(string $message = 'hello'): array { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Resource is not a stream nor a string; received "integer"'); - new Stream(47); + return [ + 'timestamp' => new DateTimeImmutable('2026-01-02 03:04:05+00:00'), + 'level' => Logger::INFO, + 'levelName' => 'info', + 'message' => $message, + 'context' => [], + ]; } /** - * @throws ErrorException + * Regression test: a Stream without a formatter crashed on the first write. */ - public function testWillNotInstantiateWithWrongResource(): void + public function testWritesWithTheDefaultFormatter(): void { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Resource is not a stream nor a string; received "object"'); - new Stream(['stream' => new stdClass()]); + $file = $this->directory . '/default.log'; + $writer = new Stream($file); + + $writer->write($this->event()); + $writer->shutdown(); + + $this->assertSame( + '2026-01-02T03:04:05+00:00 info (6): hello' . PHP_EOL, + file_get_contents($file) + ); + } + + public function testWritesToAnExistingResource(): void + { + $resource = fopen('php://memory', 'a+'); + $this->assertNotFalse($resource); + $writer = new Stream(['stream' => $resource, 'formatter' => ['name' => 'json'], 'log_separator' => "\n"]); + + $writer->write($this->event()); + + rewind($resource); + $this->assertSame( + '{"timestamp":"2026-01-02T03:04:05+00:00","level":6,"levelName":"info","message":"hello","context":[]}' + . "\n", + stream_get_contents($resource) + ); + fclose($resource); + } + + public function testFiltersAreApplied(): void + { + $file = $this->directory . '/filtered.log'; + $writer = new Stream([ + 'stream' => $file, + 'filters' => [['name' => 'level', 'options' => ['level' => Logger::ERR]]], + ]); + + $writer->write($this->event()); + + $this->assertSame('', file_get_contents($file)); + } + + public function testCreatesTheFileWithTheConfiguredPermissions(): void + { + $file = $this->directory . '/perm.log'; + new Stream(['stream' => $file, 'chmod' => 0640]); + + $this->assertSame('640', decoct(fileperms($file) & 0777)); + } + + public function testWritingToAClosedStreamFails(): void + { + $writer = new Stream($this->directory . '/closed.log'); + $writer->shutdown(); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('The log stream is closed'); + + $writer->write($this->event()); } /** - * @throws ErrorException + * @return iterable */ + public static function provideInvalidStreams(): iterable + { + yield 'integer' => [47, 'integer']; + yield 'object option' => [['stream' => new stdClass()], 'object']; + yield 'missing option' => [[], 'NULL']; + } + + #[DataProvider('provideInvalidStreams')] + public function testWillNotInstantiateWithAnInvalidStream(mixed $stream, string $type): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Resource is not a stream nor a string; received "' . $type . '"'); + + new Stream($stream); + } + public function testWillNotInstantiateWithWrongMode(): void { + $resource = fopen('php://memory', 'r'); + $this->assertNotFalse($resource); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Mode must be "a" on existing streams; received "r"'); - new Stream( - [ - 'stream' => fopen(__DIR__ . '/../../log/error-log-{Y}-{m}-{d}.log', 'r'), - 'mode' => 'r', - ] - ); + + new Stream(['stream' => $resource, 'mode' => 'r']); } - public function testSetLogSeparator(): void + public function testWillNotOpenAMissingDirectory(): void { - $input = "separator"; + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('cannot be opened with mode "a"'); - $result = $this->subject->setLogSeparator($input); - $this->assertSame($this->subject, $result); + new Stream($this->directory . '/missing/dir/file.log'); } - public function testGetLogSeparator(): void + public function testLogSeparator(): void { - $this->assertIsString($this->subject->getLogSeparator()); + $writer = new Stream('php://memory'); + + $this->assertSame(PHP_EOL, $writer->getLogSeparator()); + $this->assertSame($writer, $writer->setLogSeparator('separator')); + $this->assertSame('separator', $writer->getLogSeparator()); + } + + public function testFormatterGivenAsClassName(): void + { + $resource = fopen('php://memory', 'a+'); + $this->assertNotFalse($resource); + $writer = new Stream(['stream' => $resource, 'formatter' => ['name' => Json::class]]); + + $writer->write(['message' => 'json']); + + rewind($resource); + $this->assertSame('{"message":"json"}' . PHP_EOL, stream_get_contents($resource)); } - public function testShutDown(): void + /** + * @return iterable + */ + public static function provideOldLogsPatterns(): iterable { - $this->expectNotToPerformAssertions(); - $this->subject->shutdown(); + yield 'no placeholder' => ['app.log', null]; + yield 'daily' => ['app-{Y}-{m}-{d}.log', '/^app\-[A-Za-z0-9]+\-[A-Za-z0-9]+\-[A-Za-z0-9]+\.log$/']; + yield 'special characters' => ['app+{Y}.log', '/^app\+[A-Za-z0-9]+\.log$/']; + } + + #[DataProvider('provideOldLogsPatterns')] + public function testOldLogsPattern(string $streamFormat, ?string $expected): void + { + $writer = new Stream([ + 'stream' => $this->directory . '/current.log', + 'stream_format' => $streamFormat, + 'log_lifetime' => 1, + ]); + + $this->assertSame($expected, $writer->getOldLogsPattern()); + } + + /** + * Regression test: only "." was escaped, so unrelated files could match the deletion pattern. + */ + public function testShutdownDeletesOnlyOldFilesOfThisWriter(): void + { + $old = time() - 5 * 86400; + $oldLog = $this->directory . '/app+2020-01.log'; + $recentLog = $this->directory . '/app+2026-11.log'; + $unrelated = $this->directory . '/appX2020-01Xlog'; + $otherWriter = $this->directory . '/other-2020-01.log'; + foreach ([$oldLog, $unrelated, $otherWriter] as $file) { + touch($file, $old); + } + touch($recentLog); + + $writer = new Stream([ + 'stream' => $recentLog, + 'stream_format' => 'app+{Y}-{m}.log', + 'log_lifetime' => 2, + ]); + $writer->shutdown(); + + $this->assertFileDoesNotExist($oldLog); + $this->assertFileExists($recentLog); + $this->assertFileExists($unrelated); + $this->assertFileExists($otherWriter); + } + + public function testNoCleanupWithoutLifetime(): void + { + $oldLog = $this->directory . '/app-2020.log'; + touch($oldLog, time() - 5 * 86400); + + (new Stream(['stream' => $this->directory . '/app-2026.log', 'stream_format' => 'app-{Y}.log']))->shutdown(); + + $this->assertFileExists($oldLog); } }