Channel attribute for LoggerInterface
iGrog opened this issue · 3 comments
iGrog commented
Description
Currently, we need to use LogsInterface
to send logs to the desired channel.
https://spiral.dev/docs/basics-logging/current#send-logs-to-a-specific-channel
How about having a Channel
attribute to make this simpler?
Before:
final class UserService
{
private readonly LoggerInterface $logger;
public function __construct(LogsInterface $logs)
{
$this->logger = $logs->channel('my-channel');
}
}
After:
final class UserService
{
public function __construct(
#[Channel('my-channel')] // <-- channel name here
LoggerInterface $logger)
{
}
}
iGrog commented
I tried to use Injector for this like:
/** @implements InjectorInterface<\Psr\Log\LoggerInterface> */
final readonly class LoggerInjector implements InjectorInterface
{
public function __construct(private LogsInterface $logs) {
}
public function createInjection(ReflectionClass $class, null|ReflectionParameter|string $context = null): object
{
$channel = $context?->getAttributes(Channel::class)[0]?->newInstance()?->channelName ?? 'default';
return $this->logs->getLogger($channel);
}
}
But it seems that this doesn't work so straightforwardly
iGrog commented
No, I hadn't noticed this PR :)
Thanks! I'll wait for the next minor release!