php-pm-httpkernel icon indicating copy to clipboard operation
php-pm-httpkernel copied to clipboard

Exception in Symfony event listener does not clear request stack

Open mathieudz opened this issue 4 years ago • 0 comments

It seems that when an exception happens in a Symfony event listener (e.g. kernel response), the request stack is not reset (and possibly other things too). What I typically notice, is that when such an exception happens, all subsequent requests have the same master request as the one that had the exception. I know this because I log it:

class LogEnricher
{
    private $requestStack;
    private $tokenStorage;

    public function __construct(RequestStack $requestStack, TokenStorageInterface $tokenStorage)
    {
        $this->requestStack = $requestStack;
        $this->tokenStorage = $tokenStorage;
    }

    public function __invoke(array $record)
    {
        if (isset($record['context']['extra']) && \is_array($record['context']['extra'])) {
            foreach ($record['context']['extra'] as $key => $value) {
                $record['extra'][$key] = $value;
            }
        }
        $request = $this->requestStack->getMasterRequest();
        if ($request) {
            $record['extra']['ip_address'] = $request->getClientIp();
            $record['extra']['url'] = $request->getRequestUri();
            $token = $this->tokenStorage->getToken();
            if ($token) {
                $user = $token->getUser();
                if ($user instanceof User) {
                    $record['extra']['user_name'] = $user->getUsername();
                }
            }
        }
        return $record;
    }
}
    App\Util\LogEnricher:
        tags:
            - { name: monolog.processor }

The log files show the same URL for all subsequent requests, until the process worker is stopped.

Maybe PHP PM should clear the request stack each time?

mathieudz avatar Dec 25 '20 09:12 mathieudz