diff --git a/README.md b/README.md index 9beeb78..4cb389e 100644 --- a/README.md +++ b/README.md @@ -136,3 +136,23 @@ $logger->alert('Db connect error', [ ]); ``` + +## Using LogChannel with `stefna/di` + +This will add the channel to the logger context. + +This is useful to filter logs + +```php +has(ManagerInterface::class)) { + return $container->get(ManagerInterface::class)->getLogger($this->channel); + } + $object = $container->get($type); + if ($object instanceof LoggerInterface && class_exists(ChannelWrapper::class)) { + return new ChannelWrapper($object, $this->channel); + } + + // don't know how to add the channel just return the incoming logger + return $object; + } +} diff --git a/src/Wrapper/ChannelWrapper.php b/src/Wrapper/ChannelWrapper.php index 7ca00f3..b25dece 100644 --- a/src/Wrapper/ChannelWrapper.php +++ b/src/Wrapper/ChannelWrapper.php @@ -17,7 +17,9 @@ public function __construct( */ public function log($level, string|\Stringable $message, array $context = []): void { - $context['channel'] = $this->channel; + if (!isset($context['channel'])) { + $context['channel'] = $this->channel; + } $this->logger->log($level, $message, $context); } } diff --git a/tests/Di/LogChannelTest.php b/tests/Di/LogChannelTest.php new file mode 100644 index 0000000..afb699b --- /dev/null +++ b/tests/Di/LogChannelTest.php @@ -0,0 +1,48 @@ + fn () => $logger, + CustomDomain::class => Autowire::cls(), + ])); + + $domain = $container->get(CustomDomain::class); + $domain->logger->info('test'); + + $logEntry = $logger->getLogAt(0); + $this->assertArrayHasKey('channel', $logEntry['context']); + $this->assertSame('test-channel', $logEntry['context']['channel']); + } + + public function testLogChannelDontOverrideManuallySetChannel(): void + { + $logger = new TestLogger(); + $container = new Container(new DefinitionArray([ + LoggerInterface::class => fn () => $logger, + CustomDomain::class => Autowire::cls(), + ])); + + $domain = $container->get(CustomDomain::class); + $domain->logger->info('test', [ + 'channel' => 'manual-channel', + ]); + + $logEntry = $logger->getLogAt(0); + $this->assertArrayHasKey('channel', $logEntry['context']); + $this->assertSame('manual-channel', $logEntry['context']['channel']); + } +} diff --git a/tests/Di/Stub/CustomDomain.php b/tests/Di/Stub/CustomDomain.php new file mode 100644 index 0000000..3ff90e2 --- /dev/null +++ b/tests/Di/Stub/CustomDomain.php @@ -0,0 +1,14 @@ +