Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updates to logger component #214

Merged
merged 2 commits into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ To get the diff between two versions, go to https://github.com/SonsOfPHP/sonsofp

## [Unreleased]

* [PR #214](https://github.com/SonsOfPHP/sonsofphp/pull/214) [Logger] Bug fixes and updates
* [PR #51](https://github.com/SonsOfPHP/sonsofphp/pull/51) Added new Filesystem component
* [PR #59](https://github.com/SonsOfPHP/sonsofphp/pull/59) Added new HttpMessage component
* [PR #59](https://github.com/SonsOfPHP/sonsofphp/pull/59) Added new HttpFactory component
Expand Down
2 changes: 1 addition & 1 deletion docs/components/logger/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ Simple Usage Example
use SonsOfPHP\Component\Logger\Logger;

// Logger is PSR-3 Logger
$logger = new Logger('app');
$logger = new Logger();
$logger->debug('Debug Log Message');
```

Expand Down
22 changes: 22 additions & 0 deletions src/SonsOfPHP/Component/Logger/Enricher/HostnameEnricher.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace SonsOfPHP\Component\Logger\Enricher;

use SonsOfPHP\Contract\Logger\EnricherInterface;
use SonsOfPHP\Contract\Logger\RecordInterface;

/**
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class HostnameEnricher implements EnricherInterface
{
public function __invoke(RecordInterface $record): RecordInterface
{
$context = $record->getContext();
$context['hostname'] = gethostname();

return $record->withContext($context);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ class SimpleFormatter implements FormatterInterface
{
public function formatMessage(RecordInterface $record): string
{
$output = "[%datetime%] %channel%.%level_name%: %message% %context%\n";
$message = '[' . $record->getDatetime()->format('c') . '] ' . $record->getChannel() . '.' . $record->getLevel()->getName() . ' ' . $record->getMessage();

$output = "[%datetime%] %channel%.%level_name%: %message% %context%\n";
$message = $record->getMessage();
foreach ($record->getContext() as $key => $value) {
if (!is_array($value) && (!is_object($value) || method_exists($value, '__toString'))) {
Expand Down
7 changes: 4 additions & 3 deletions src/SonsOfPHP/Component/Logger/Handler/AbstractHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace SonsOfPHP\Component\Logger\Handler;

use SonsOfPHP\Component\Logger\Formatter\SimpleFormatter;
use SonsOfPHP\Contract\Logger\FilterInterface;
use SonsOfPHP\Contract\Logger\FormatterInterface;
use SonsOfPHP\Contract\Logger\HandlerInterface;
Expand All @@ -20,7 +21,7 @@ public function __construct(
protected ?FormatterInterface $formatter = null,
) {}

//abstract public function doHandle(RecordInterface $record, string $message): void;
abstract public function doHandle(RecordInterface $record, string $message): void;

public function getFilter(): ?FilterInterface
{
Expand All @@ -34,7 +35,7 @@ public function setFilter(FilterInterface $filter): void

public function getFormatter(): ?FormatterInterface
{
return $this->formatter ?? null;
return $this->formatter ?? new SimpleFormatter();
}

public function setFormatter(FormatterInterface $formatter): void
Expand All @@ -50,7 +51,7 @@ public function handle(RecordInterface $record): void

$message = $record->getMessage();
if ($this->getFormatter() instanceof FormatterInterface) {
$message = $record->withMessage($this->formatter->formatMessage($record));
$message = $this->getFormatter()->formatMessage($record);
}

$this->doHandle($record, $message);
Expand Down
3 changes: 1 addition & 2 deletions src/SonsOfPHP/Component/Logger/Handler/FileHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@
namespace SonsOfPHP\Component\Logger\Handler;

use RuntimeException;
use SonsOfPHP\Contract\Logger\HandlerInterface;
use SonsOfPHP\Contract\Logger\RecordInterface;

/**
* Logs messages to a file
*
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class FileHandler extends AbstractHandler implements HandlerInterface
class FileHandler extends AbstractHandler
{
private bool $isOpen = false;
private $handle;
Expand Down
5 changes: 2 additions & 3 deletions src/SonsOfPHP/Component/Logger/Handler/NullHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,14 @@

namespace SonsOfPHP\Component\Logger\Handler;

use SonsOfPHP\Contract\Logger\HandlerInterface;
use SonsOfPHP\Contract\Logger\RecordInterface;

/**
* The handler that says, "fuck your message"
*
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class NullHandler extends AbstractHandler implements HandlerInterface
class NullHandler extends AbstractHandler
{
public function handle(RecordInterface $record): void {}
public function doHandle(RecordInterface $record, string $message): void {}
}
3 changes: 1 addition & 2 deletions src/SonsOfPHP/Component/Logger/Handler/StreamHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@
namespace SonsOfPHP\Component\Logger\Handler;

use RuntimeException;
use SonsOfPHP\Contract\Logger\HandlerInterface;
use SonsOfPHP\Contract\Logger\RecordInterface;

/**
* @author Joshua Estes <joshua@sonsofphp.com>
*/
class StreamHandler extends AbstractHandler implements HandlerInterface
class StreamHandler extends AbstractHandler
{
private bool $isOpen = false;

Expand Down
6 changes: 5 additions & 1 deletion src/SonsOfPHP/Component/Logger/Record.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,12 @@ public function getDatetime(): DateTimeImmutable

public function withDatetime(DateTimeImmutable $datetime): static
{
if ($this->datetime === $datetime) {
return $this;
}

$that = clone $this;
$that->datatime = $datatime;
$that->datetime = $datetime;

return $that;
}
Expand Down
45 changes: 41 additions & 4 deletions src/SonsOfPHP/Component/Logger/Tests/ContextTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,8 @@
use PHPUnit\Framework\TestCase;
use SonsOfPHP\Component\Logger\Context;
use SonsOfPHP\Contract\Logger\ContextInterface;
use stdClass;

/**
* @uses \SonsOfPHP\Component\Logger\Context
* @coversNothing
*/
#[CoversClass(Context::class)]
final class ContextTest extends TestCase
{
Expand Down Expand Up @@ -88,4 +85,44 @@ public function testOffsetSet(): void
$this->assertTrue(isset($context['key']));
$this->assertNotEmpty($context['key']);
}

public function testItWillThrowExceptionDuringOffsetExistsWithInvalidOffset(): void
{
$context = new Context();

$this->expectException('InvalidArgumentException');
isset($context[new stdClass()]);
}

public function testItWillThrowExceptionDuringOffsetGetWithInvalidOffset(): void
{
$context = new Context();

$this->expectException('InvalidArgumentException');
$context[new stdClass()];
}

public function testItWillThrowExceptionDuringOffsetSetWithInvalidOffset(): void
{
$context = new Context();

$this->expectException('InvalidArgumentException');
$context[new stdClass()] = 'test';
}

public function testItWillThrowExceptionDuringOffsetSetWithInvalidOffsetValue(): void
{
$context = new Context();

$this->expectException('InvalidArgumentException');
$context['test'] = new stdClass();
}

public function testItWillThrowExceptionDuringOffsetUnsetWithInvalidOffset(): void
{
$context = new Context();

$this->expectException('InvalidArgumentException');
unset($context[new stdClass()]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace SonsOfPHP\Component\Logger\Tests\Enricher;

use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
use SonsOfPHP\Component\Logger\Context;
use SonsOfPHP\Component\Logger\Enricher\HostnameEnricher;
use SonsOfPHP\Component\Logger\Level;
use SonsOfPHP\Component\Logger\Record;
use SonsOfPHP\Contract\Logger\EnricherInterface;

#[CoversClass(HostnameEnricher::class)]
#[UsesClass(Context::class)]
#[UsesClass(Record::class)]
final class HostnameEnricherTest extends TestCase
{
/**
* @coversNothing
*/
public function testItHasTheCorrectInterface(): void
{
$enricher = new HostnameEnricher();

$this->assertInstanceOf(EnricherInterface::class, $enricher);
}

public function testInvoke(): void
{
$enricher = new HostnameEnricher();
$record = $enricher(new Record(
channel: 'test',
level: Level::Debug,
message: '',
context: new Context(),
));

$this->assertArrayHasKey('hostname', $record->getContext());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
use SonsOfPHP\Component\Logger\Context;
use SonsOfPHP\Component\Logger\Formatter\SimpleFormatter;
use SonsOfPHP\Component\Logger\Handler\AbstractHandler;
use SonsOfPHP\Component\Logger\Handler\FileHandler;
use SonsOfPHP\Component\Logger\Level;
Expand All @@ -19,6 +20,8 @@
#[UsesClass(Context::class)]
#[UsesClass(AbstractHandler::class)]
#[UsesClass(Record::class)]
#[UsesClass(SimpleFormatter::class)]
#[UsesClass(Level::class)]
final class FileHandlerTest extends TestCase
{
public function setUp(): void
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
use SonsOfPHP\Component\Logger\Context;
use SonsOfPHP\Component\Logger\Formatter\SimpleFormatter;
use SonsOfPHP\Component\Logger\Handler\AbstractHandler;
use SonsOfPHP\Component\Logger\Handler\StreamHandler;
use SonsOfPHP\Component\Logger\Level;
Expand All @@ -19,6 +20,8 @@
#[UsesClass(Context::class)]
#[UsesClass(AbstractHandler::class)]
#[UsesClass(Record::class)]
#[UsesClass(SimpleFormatter::class)]
#[UsesClass(Level::class)]
final class StreamHandlerTest extends TestCase
{
public function setUp(): void
Expand Down
7 changes: 7 additions & 0 deletions src/SonsOfPHP/Component/Logger/Tests/LevelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ public function testFromNameWithInvalidName(): void

public function testFromName(): void
{
$this->assertSame(Level::Emergency, Level::fromName('emergency'));
$this->assertSame(Level::Alert, Level::fromName('alert'));
$this->assertSame(Level::Critical, Level::fromName('critical'));
$this->assertSame(Level::Error, Level::fromName('error'));
$this->assertSame(Level::Warning, Level::fromName('warning'));
$this->assertSame(Level::Notice, Level::fromName('notice'));
$this->assertSame(Level::Info, Level::fromName('info'));
$this->assertSame(Level::Debug, Level::fromName('debug'));
}

Expand Down
7 changes: 7 additions & 0 deletions src/SonsOfPHP/Component/Logger/Tests/LoggerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,11 @@ public function testaddHandler(): void
$logger->addHandler(new NullHandler());
$this->assertCount(2, $handlers->getValue($logger));
}

public function testLogWillThrowExceptionWhenLevelIsInvalid(): void
{
$logger = new Logger();
$this->expectException('InvalidArgumentException');
$logger->log('test level', 'message');
}
}
17 changes: 17 additions & 0 deletions src/SonsOfPHP/Component/Logger/Tests/RecordTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace SonsOfPHP\Component\Logger\Tests;

use DateTimeImmutable;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
Expand Down Expand Up @@ -100,4 +101,20 @@ public function testWithContextWhenArgumentIsArray(): void
$this->assertArrayHasKey('key', $record->getContext());
$this->assertSame('value', $record->getContext()['key']);
}

public function testDatetime(): void
{
$ts = new DateTimeImmutable();
$record = new Record(
channel: 'app',
level: Level::Debug,
message: 'testing',
context: new Context(),
datetime: $ts,
);

$this->assertSame($ts, $record->getDatetime());
$this->assertSame($record, $record->withDatetime($ts));
$this->assertNotSame($record, $record->withDatetime(new DateTimeImmutable()));
}
}
4 changes: 2 additions & 2 deletions src/SonsOfPHP/Component/Logger/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"prefer-stable": true,
"require": {
"php": ">=8.2",
"psr/log": "^1.0 || ^2.0 || ^3.0",
"psr/log": "^2.0 || ^3.0",
"sonsofphp/logger-contract": "0.3.x-dev"
},
"provide": {
Expand All @@ -55,4 +55,4 @@
"url": "https://tidelift.com/subscription/pkg/packagist-sonsofphp-sonsofphp"
}
]
}
}
Loading