spiral / framework

High-Performance PHP Framework
https://spiral.dev
MIT License
1.82k stars 89 forks source link

Channel attribute for LoggerInterface #1108

Closed iGrog closed 6 months ago

iGrog commented 6 months ago

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 6 months ago

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

roxblnfk commented 6 months ago

Hi. Have you seen this PR https://github.com/spiral/framework/pull/1102? It will be able in the next minor release

iGrog commented 6 months ago

No, I hadn't noticed this PR :) Thanks! I'll wait for the next minor release!