Skip to content

[FrameworkBundle][HttpKernel] Allow configuring the logging channel per type of exceptions #57309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ CHANGELOG
* Auto-exclude DI extensions, test cases, entities and messenger messages
* Add DI alias from `ServicesResetterInterface` to `services_resetter`
* Add `methods` argument in `#[IsCsrfTokenValid]` attribute
* Allow configuring the logging channel per type of exceptions

7.2
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1458,6 +1458,10 @@ private function addExceptionsSection(ArrayNodeDefinition $rootNode): void
->end()
->defaultNull()
->end()
->scalarNode('log_channel')
->info('The channel of log message. Null to let Symfony decide.')
->defaultNull()
->end()
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,20 @@ public function load(array $configs, ContainerBuilder $container): void
$this->registerPropertyAccessConfiguration($config['property_access'], $container, $loader);
$this->registerSecretsConfiguration($config['secrets'], $container, $loader, $config['secret'] ?? null);

$container->getDefinition('exception_listener')->replaceArgument(3, $config['exceptions']);
$exceptionListener = $container->getDefinition('exception_listener');

$loggers = [];
foreach ($config['exceptions'] as $exception) {
if (!isset($exception['log_channel'])) {
continue;
}
$loggers[$exception['log_channel']] = new Reference('monolog.logger.'.$exception['log_channel'], ContainerInterface::NULL_ON_INVALID_REFERENCE);
}

$exceptionListener
->replaceArgument(3, $config['exceptions'])
->setArgument(4, $loggers)
;

if ($this->readConfigEnabled('serializer', $container, $config['serializer'])) {
if (!class_exists(Serializer::class)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@
service('logger')->nullOnInvalid(),
param('kernel.debug'),
abstract_arg('an exceptions to log & status code mapping'),
abstract_arg('list of loggers by log_channel'),
])
->tag('kernel.event_subscriber')
->tag('monolog.logger', ['channel' => 'request'])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -615,21 +615,25 @@ public function testExceptionsConfig()
], array_keys($configuration));

$this->assertEqualsCanonicalizing([
'log_channel' => null,
'log_level' => 'info',
'status_code' => 422,
], $configuration[\Symfony\Component\HttpKernel\Exception\BadRequestHttpException::class]);

$this->assertEqualsCanonicalizing([
'log_channel' => null,
'log_level' => 'info',
'status_code' => null,
], $configuration[\Symfony\Component\HttpKernel\Exception\NotFoundHttpException::class]);

$this->assertEqualsCanonicalizing([
'log_channel' => null,
'log_level' => 'info',
'status_code' => null,
], $configuration[\Symfony\Component\HttpKernel\Exception\ConflictHttpException::class]);

$this->assertEqualsCanonicalizing([
'log_channel' => null,
'log_level' => null,
'status_code' => 500,
], $configuration[\Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException::class]);
Expand Down
3 changes: 2 additions & 1 deletion src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ CHANGELOG
* Add `$key` argument to `#[MapQueryString]` that allows using a specific key for argument resolving
* Support `Uid` in `#[MapQueryParameter]`
* Add `ServicesResetterInterface`, implemented by `ServicesResetter`

* Allow configuring the logging channel per type of exceptions in ErrorListener

7.2
---

Expand Down
38 changes: 30 additions & 8 deletions src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,22 @@
class ErrorListener implements EventSubscriberInterface
{
/**
* @param array<class-string, array{log_level: string|null, status_code: int<100,599>|null}> $exceptionsMapping
* @param array<class-string, array{log_level: string|null, status_code: int<100,599>|null, log_channel: string|null}> $exceptionsMapping
*/
public function __construct(
protected string|object|array|null $controller,
protected ?LoggerInterface $logger = null,
protected bool $debug = false,
protected array $exceptionsMapping = [],
protected array $loggers = [],
) {
}

public function logKernelException(ExceptionEvent $event): void
{
$throwable = $event->getThrowable();
$logLevel = $this->resolveLogLevel($throwable);
$logChannel = $this->resolveLogChannel($throwable);

foreach ($this->exceptionsMapping as $class => $config) {
if (!$throwable instanceof $class || !$config['status_code']) {
Expand All @@ -69,7 +71,7 @@ public function logKernelException(ExceptionEvent $event): void

$e = FlattenException::createFromThrowable($throwable);

$this->logException($throwable, \sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', $e->getClass(), $e->getMessage(), basename($e->getFile()), $e->getLine()), $logLevel);
$this->logException($throwable, \sprintf('Uncaught PHP Exception %s: "%s" at %s line %s', $e->getClass(), $e->getMessage(), basename($e->getFile()), $e->getLine()), $logLevel, $logChannel);
}

public function onKernelException(ExceptionEvent $event): void
Expand Down Expand Up @@ -159,16 +161,20 @@ public static function getSubscribedEvents(): array

/**
* Logs an exception.
*
* @param ?string $logChannel
*/
protected function logException(\Throwable $exception, string $message, ?string $logLevel = null): void
protected function logException(\Throwable $exception, string $message, ?string $logLevel = null, /* ?string $logChannel = null */): void
{
if (null === $this->logger) {
$logChannel = (3 < \func_num_args() ? \func_get_arg(3) : null) ?? $this->resolveLogChannel($exception);

$logLevel ??= $this->resolveLogLevel($exception);

if(!$logger = $this->getLogger($logChannel)) {
return;
}

$logLevel ??= $this->resolveLogLevel($exception);

$this->logger->log($logLevel, $message, ['exception' => $exception]);
$logger->log($logLevel, $message, ['exception' => $exception]);
}

/**
Expand All @@ -193,6 +199,17 @@ private function resolveLogLevel(\Throwable $throwable): string
return LogLevel::ERROR;
}

private function resolveLogChannel(\Throwable $throwable): ?string
{
foreach ($this->exceptionsMapping as $class => $config) {
if ($throwable instanceof $class && isset($config['log_channel'])) {
return $config['log_channel'];
}
}

return null;
}

/**
* Clones the request for the exception.
*/
Expand All @@ -201,7 +218,7 @@ protected function duplicateRequest(\Throwable $exception, Request $request): Re
$attributes = [
'_controller' => $this->controller,
'exception' => $exception,
'logger' => DebugLoggerConfigurator::getDebugLogger($this->logger),
'logger' => DebugLoggerConfigurator::getDebugLogger($this->getLogger($exception)),
];
$request = $request->duplicate(null, null, $attributes);
$request->setMethod('GET');
Expand Down Expand Up @@ -249,4 +266,9 @@ private function getInheritedAttribute(string $class, string $attribute): ?objec

return $attributeReflector?->newInstance();
}

private function getLogger(?string $logChannel): ?LoggerInterface
{
return $logChannel ? $this->loggers[$logChannel] ?? $this->logger : $this->logger;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,63 @@ public function testHandleWithLogLevelAttribute()
$this->assertCount(1, $logger->getLogsForLevel('warning'));
}

public function testHandleWithLogChannel()
{
$request = new Request();
$event = new ExceptionEvent(new TestKernel(), $request, HttpKernelInterface::MAIN_REQUEST, new \RuntimeException('bar'));

$defaultLogger = new TestLogger();
$channelLoger = new TestLogger();

$l = new ErrorListener('not used', $defaultLogger, false, [
\RuntimeException::class => [
'log_level' => 'warning',
'status_code' => 401,
'log_channel' => 'channel',
],
\Exception::class => [
'log_level' => 'error',
'status_code' => 402,
],
], ['channel' => $channelLoger]);

$l->logKernelException($event);
$l->onKernelException($event);

$this->assertCount(0, $defaultLogger->getLogsForLevel('error'));
$this->assertCount(0, $defaultLogger->getLogsForLevel('warning'));
$this->assertCount(0, $channelLoger->getLogsForLevel('error'));
$this->assertCount(1, $channelLoger->getLogsForLevel('warning'));
}

public function testHandleWithLoggerChannelNotUsed()
{
$request = new Request();
$event = new ExceptionEvent(new TestKernel(), $request, HttpKernelInterface::MAIN_REQUEST, new \RuntimeException('bar'));
$defaultLogger = new TestLogger();
$channelLoger = new TestLogger();
$l = new ErrorListener('not used', $defaultLogger, false, [
\RuntimeException::class => [
'log_level' => 'warning',
'status_code' => 401,
],
\ErrorException::class => [
'log_level' => 'error',
'status_code' => 402,
'log_channel' => 'channel',
],
], ['channel' => $channelLoger]);
$l->logKernelException($event);
$l->onKernelException($event);

$this->assertSame(0, $defaultLogger->countErrors());
$this->assertCount(0, $defaultLogger->getLogsForLevel('critical'));
$this->assertCount(1, $defaultLogger->getLogsForLevel('warning'));
$this->assertCount(0, $channelLoger->getLogsForLevel('warning'));
$this->assertCount(0, $channelLoger->getLogsForLevel('error'));
$this->assertCount(0, $channelLoger->getLogsForLevel('critical'));
}

public function testHandleClassImplementingInterfaceWithLogLevelAttribute()
{
$request = new Request();
Expand Down
Loading