How to access route parameters from a service tagged monolog.processor?

Viewed 123

Using Symfony 4.4, I'd like to add on the fly to all my a route parameter if it's found in the on request. E.g. for the user Id:

PUT | DELETE | POST mywebsite.com/users/{userid}/some-action

I could add my users ids each time I log but it's kind of cumbersome.

So I created a service:

//src/
// |__Services/
//         |___UserProcessor.php

use Monolog\Processor\ProcessorInterface;
use Symfony\Component\HttpFoundation\RequestStack;

// In my config.yaml this monolog.processor
final class UserProcessor implements ProcessorInterface
{
    private RequestStack $requestStack;
    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }

    public function __invoke(array $record): array
    {
        dd($this->requestStack->getMasterRequest()->attributes);
    }
}

When I run my postman on POST /users/{userid}/some-action I get this output:

[
      "media_type" => "application/json"
]

From my understanding, symfony route parameters request attributes are not built yet at the moment my processor runs.

What should I do to make my processor access the attribute userid?

1 Answers

Check how the Symfony\Bridge\Monolog\Processor\RouteProcessor does it:

It's implemented as an EventSubscriber

class RouteProcessor implements EventSubscriberInterface, ResetInterface
{
    private $routeData;
    private $includeParams;

    public function __construct(bool $includeParams = true)
    {
        $this->includeParams = $includeParams;
        $this->reset();
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => ['addRouteData', 1],
            KernelEvents::FINISH_REQUEST => ['removeRouteData', 1],
        ];
    }
// rest of the implementation
}

During KernelEvents::REQUEST it adds the required request data (including request parameters, if so desired) to the internal state of the object, so when the processor is run it can access the data from the internal RouteProcessor::$routeData, and not from the request directly.

 public function addRouteData(RequestEvent $event)
    {
        if ($event->isMainRequest()) {
            $this->reset();
        }

        $request = $event->getRequest();
        if (!$request->attributes->has('_controller')) {
            return;
        }

        $currentRequestData = [
            'controller' => $request->attributes->get('_controller'),
            'route' => $request->attributes->get('_route'),
        ];

        if ($this->includeParams) {
            $currentRequestData['route_params'] = $request->attributes->get('_route_params');
        }

        $this->routeData[spl_object_id($request)] = $currentRequestData;
    }

You could modify this approach to suit yourself, or even just use this processor directly (although it adds more data than what you are looking for in your question).

Related