symfony / monolog-bundle

Symfony Monolog Bundle
symfony.com
MIT License
2.9k stars 232 forks source link

WithMonologChannel on argument instead of the class #475

Open lyrixx opened 9 months ago

lyrixx commented 9 months ago

Hello,

I was playing with #[WithMonologChannel] attribute. Without reading the doc, I put it on the constructor parameter, because I thought it would work like #[Target], #[Autowire], ... attributes

class HomepageController extends AbstractController
{
    public function __construct(
        #[WithMonologChannel('homepage')]
        private readonly LoggerInterface $logger,
        private readonly MessageBusInterface $bus,
    ) {
    }

But, what a surprise, it didn't work.

Instead it must be set on the class

#[WithMonologChannel('homepage')]
class HomepageController extends AbstractController
{
    public function __construct(
        private readonly LoggerInterface $logger,
        private readonly MessageBusInterface $bus,
    ) {
    }

What about allowing it on the parameter instead ? It feels more natural. And it allows having N different logger

class HomepageController extends AbstractController
{
    public function __construct(
        #[WithMonologChannel('homepage')]
        private readonly LoggerInterface $logger,
        #[WithMonologChannel('billing')]
        private readonly LoggerInterface $billingLogger,
        private readonly MessageBusInterface $bus,
    ) {
    }

WDYT ?

Seldaek commented 9 months ago

Makes sense but it'll require a tweak in monolog I guess.. as that only has target_class

stof commented 3 months ago

it also require changing entirely the way the processing is implemented. Right now, this attribute only applies the tag on the service definition, which then defines a binding.

To support separate channels in different arguments, it would require hooking directly in the autowiring logic instead. Can you try using the Target attribute of the DI component instead ? I think it might work already for known channels thanks to the registration done in https://github.com/symfony/monolog-bundle/blob/b2b5f9a515011b93e2bfeb814cf69613e7b7e8eb/DependencyInjection/Compiler/LoggerChannelPass.php#L151 (channels become known either because of a monolog.channel tag asking them to be created or because of the dedicated channels setting in the bundle configuration)

lyrixx commented 3 months ago

I used Target indeed 👍🏼