This commit is contained in:
Daniel Seifert 2025-02-05 21:57:47 +01:00
commit 6e330d85b6
8 changed files with 475 additions and 0 deletions

35
README.md Normal file
View File

@ -0,0 +1,35 @@
![stability mature](https://img.shields.io/badge/stability-mature-008000.svg)
[![latest tag](https://img.shields.io/packagist/v/d3/logger-factory?label=release)](https://packagist.org/packages/d3/logger-factory)
[![MIT License](https://img.shields.io/packagist/l/d3/logger-factory)](https://git.d3data.de/D3Public/loggerFactory/src/branch/main/LICENSE.md)
# Logger Factory
Logger factory for everyday simple configuration
## Installation
```
composer require d3/logger-factory
```
## Usage
```
$loggerFactory = loggerFactory::create();
$logger = $loggerFactory->getFileLogger('myPluginLogger', 'plugin_requests.log', Logger::DEBUG, 5);
```
## Licence of this software (Logger factory) [MIT]
(05.02.2025)
```
Copyright (c) D3 Data Development (Inh. Thomas Dartsch)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
```

45
composer.json Normal file
View File

@ -0,0 +1,45 @@
{
"name": "d3/logger-factory",
"type": "library",
"description": "Logger factory",
"keywords": [
"PSR-3",
"logger",
"Monolog",
"factory"
],
"homepage": "https://www.d3data.de",
"license": "MIT",
"authors": [
{
"name": "Daniel Seifert",
"email": "git@daniel-seifert.com"
}
],
"require": {
"monolog/monolog": "^1.20",
"d3/sensitive-message-formatter": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^10.5",
"friendsofphp/php-cs-fixer": "^3.65",
"phpstan/phpstan": "^2.0"
},
"autoload": {
"psr-4": {
"D3\\LoggerFactory\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"D3\\LoggerFactory\\tests\\": "tests/"
}
},
"scripts": {
"test": "./vendor/bin/phpunit --no-coverage",
"test-coverage": "XDEBUG_MODE=coverage ./vendor/bin/phpunit --coverage-html=coverage",
"check-style": "./vendor/bin/php-cs-fixer fix --verbose --dry-run",
"fix-style": "./vendor/bin/php-cs-fixer fix --verbose",
"check-code": "./vendor/bin/phpstan analyse -c phpstan.neon --no-progress --ansi"
}
}

20
phpunit.xml Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
bootstrap="vendor/autoload.php"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd">
<coverage>
<include>
<directory suffix=".php">src</directory>
</include>
<report>
<clover outputFile="build/logs/clover.xml"/>
</report>
</coverage>
<testsuite name="LoggerFactory">
<directory>./tests</directory>
</testsuite>
<logging/>
</phpunit>

113
src/LoggerFactory.php Normal file
View File

@ -0,0 +1,113 @@
<?php
/**
* Copyright (c) D3 Data Development (Inh. Thomas Dartsch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <info@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\LoggerFactory;
use Exception;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use OxidEsales\Eshop\Core\Registry;
use RuntimeException;
class LoggerFactory
{
public static function create(): LoggerFactory
{
return new LoggerFactory();
}
/**
* @param string $loggerName
* @param string $filePath
* @param int $logLevel
* @param int|null $maxFiles
* @return Logger
* @throws Exception
*/
public function getFileLogger(
string $loggerName,
string $filePath,
int $logLevel = Logger::INFO,
?int $maxFiles = null
): Logger
{
$logger = new Logger($loggerName);
$stream_handler = $this->getFileLoggerStreamHandler($filePath, $logLevel, $maxFiles);
$logger->pushHandler($stream_handler);
return $logger;
}
/**
* @param string $filePath
* @param int $logLevel
* @param int|null $maxFiles
* @return AbstractProcessingHandler
* @throws Exception
*/
protected function getFileLoggerStreamHandler(
string $filePath,
int $logLevel = Logger::INFO,
?int $maxFiles = null
): AbstractProcessingHandler
{
return is_null($maxFiles) ?
new StreamHandler($filePath, $logLevel) :
new RotatingFileHandler($filePath, $maxFiles, $logLevel);
}
/**
* @param string $loggerName
* @param string $filePath
* @param int $logLevel
* @param int|null $maxFiles
* @return Logger
* @throws Exception
*/
public function getCombinedOxidAndFileLogger(
string $loggerName,
string $filePath,
int $logLevel = Logger::INFO,
?int $maxFiles = null
): Logger
{
if (!class_exists(Registry::class)) {
throw new RuntimeException(__METHOD__.' can executed in OXID eShop installations only');
}
$logger = new Logger($loggerName);
$stream_handler = $this->getFileLoggerStreamHandler($filePath, $logLevel, $maxFiles);
$logger->pushHandler($stream_handler);
$oxidLogFilePath = $this->getOxidLogPath('oxideshop.log');
$oxidStreamHandler = new StreamHandler($oxidLogFilePath, Logger::ERROR);
$logger->pushHandler($oxidStreamHandler);
return $logger;
}
protected function getOxidLogPath(string $fileName): string
{
if (!class_exists(Registry::class)) {
throw new RuntimeException(__METHOD__.' can executed in OXID eShop installations only');
}
return OX_BASE_PATH . '/log' . DIRECTORY_SEPARATOR . $fileName;
}
}

75
tests/ApiTestCase.php Normal file
View File

@ -0,0 +1,75 @@
<?php
/**
* Copyright (c) D3 Data Development (Inh. Thomas Dartsch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <info@shopmodule.com>
* @link https://www.oxidmodule.com
*/
declare(strict_types=1);
namespace D3\LoggerFactory\tests;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionException;
abstract class ApiTestCase extends TestCase
{
/**
* Calls a private or protected object method.
*
* @param object $object
* @param string $methodName
* @param array $arguments
*
* @return mixed
* @throws ReflectionException
*/
public function callMethod(object $object, string $methodName, array $arguments = [])
{
$class = new ReflectionClass($object);
$method = $class->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $arguments);
}
/**
* Sets a private or protected property in defined class instance
*
* @param object $object
* @param string $valueName
* @param $value
* @throws ReflectionException
*/
public function setValue(object $object, string $valueName, $value): void
{
$reflection = new ReflectionClass($object);
$property = $reflection->getProperty($valueName);
$property->setAccessible(true);
$property->setValue($object, $value);
}
/**
* get a private or protected property from defined class instance
*
* @param object $object
* @param string $valueName
* @return mixed
* @throws ReflectionException
*/
public function getValue(object $object, string $valueName)
{
$reflection = new ReflectionClass($object);
$property = $reflection->getProperty($valueName);
$property->setAccessible(true);
return $property->getValue($object);
}
}

View File

@ -0,0 +1,26 @@
<?php
/**
* Copyright (c) D3 Data Development (Inh. Thomas Dartsch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <info@shopmodule.com>
* @link https://www.oxidmodule.com
*/
namespace D3\GuzzleFactory\tests\Helpers;
use Monolog\Logger;
class OxidRegistryStub
{
public static function getLogger(): Logger
{
return new Logger('loggerFixture');
}
}

View File

@ -0,0 +1,20 @@
<?php
/**
* Copyright (c) D3 Data Development (Inh. Thomas Dartsch)
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*
* https://www.d3data.de
*
* @copyright (C) D3 Data Development (Inh. Thomas Dartsch)
* @author D3 Data Development - Daniel Seifert <info@shopmodule.com>
* @link https://www.oxidmodule.com
*/
use D3\GuzzleFactory\tests\Helpers\OxidRegistryStub;
const OX_BASE_PATH = __DIR__;
class_alias(OxidRegistryStub::class, '\OxidEsales\Eshop\Core\Registry');

141
tests/LoggerFactoryTest.php Normal file
View File

@ -0,0 +1,141 @@
<?php
namespace D3\LoggerFactory\tests;
use D3\LoggerFactory\LoggerFactory;
use Generator;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use PHPUnit\Framework\MockObject\MockObject;
use ReflectionException;
use RuntimeException;
class LoggerFactoryTest extends ApiTestCase
{
/**
* @test
* @return void
* @covers \D3\LoggerFactory\LoggerFactory::create
*/
public function testCreate(): void
{
$instance = LoggerFactory::create();
$this->assertInstanceOf(LoggerFactory::class, $instance);
}
/**
* @test
* @throws ReflectionException
* @covers \D3\LoggerFactory\LoggerFactory::getFileLogger
* @covers \D3\LoggerFactory\LoggerFactory::getFileLoggerStreamHandler
* @dataProvider getFileLoggerDataProvider
*/
public function testGetFileLogger(int $logLevel, ?int $maxFiles, string $expectedHandlerClass): void
{
$sut = LoggerFactory::create();
/** @var Logger|MockObject $logger */
$logger = $this->callMethod(
$sut,
'getFileLogger',
['nameFixture', 'file/path.log', $logLevel, $maxFiles]
);
$this->assertInstanceOf(Logger::class, $logger);
$this->assertInstanceOf($expectedHandlerClass, $logger->getHandlers()[0]);
$this->assertSame($logLevel, $logger->getHandlers()[0]->getLevel());
}
public static function getFileLoggerDataProvider(): Generator
{
yield 'no rotation' => [Logger::INFO, null, StreamHandler::class];
yield 'rotation 1' => [Logger::ERROR, 1, RotatingFileHandler::class];
yield 'rotation 20' => [Logger::DEBUG, 20, RotatingFileHandler::class];
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\LoggerFactory\LoggerFactory::getCombinedOxidAndFileLogger
*/
public function testGetCombinedOxidAndFileLoggerWithoutOxid(): void
{
$sut = LoggerFactory::create();
$this->expectException(RuntimeException::class);
$this->callMethod(
$sut,
'getCombinedOxidAndFileLogger',
['nameFixture', 'file/path.log', 1, 5]
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\LoggerFactory\LoggerFactory::getOxidLogPath
*/
public function testGetOxidLogPathWithoutOxid(): void
{
$sut = LoggerFactory::create();
$this->expectException(RuntimeException::class);
$this->assertSame(
'foo',
$this->callMethod(
$sut,
'getOxidLogPath',
['fixture.log']
)
);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\LoggerFactory\LoggerFactory::getCombinedOxidAndFileLogger
*/
public function testAddCombinedOxidAndFileLoggerInOxid(): void
{
require_once __DIR__.'/Helpers/classAliases.php';
$sut = LoggerFactory::create();
$logger = $this->callMethod(
$sut,
'getCombinedOxidAndFileLogger',
['nameFixture', 'file/path.log', 1, 5]
);
$this->assertInstanceOf(Logger::class, $logger);
}
/**
* @test
* @return void
* @throws ReflectionException
* @covers \D3\LoggerFactory\LoggerFactory::getOxidLogPath
*/
public function testGetOxidLogPathInOxid(): void
{
require_once __DIR__.'/Helpers/classAliases.php';
$sut = LoggerFactory::create();
$this->assertStringEndsWith(
'tests/Helpers/log/fixture.log',
$this->callMethod(
$sut,
'getOxidLogPath',
['fixture.log']
)
);
}
}