Skip to content
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

[HttpKernel] Allow using #[WithLogLevel] for setting custom log level for exceptions #48747

Merged
merged 1 commit into from
Jan 5, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/Symfony/Component/HttpKernel/Attribute/WithLogLevel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\Attribute;

use Psr\Log\LogLevel;

/**
* @author Dejan Angelov <angelovdejan@protonmail.com>
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
final class WithLogLevel
{
/**
* @param LogLevel::* $level
*/
public function __construct(public readonly string $level)
{
if (!\defined('Psr\Log\LogLevel::'.strtoupper($this->level))) {
throw new \InvalidArgumentException(sprintf('Invalid log level "%s".', $this->level));
}
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpKernel/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ CHANGELOG
* `FileProfilerStorage` removes profiles automatically after two days
* Add `#[HttpStatus]` for defining status codes for exceptions
* Use an instance of `Psr\Clock\ClockInterface` to generate the current date time in `DateTimeValueResolver`
* Add `#[WithLogLevel]` for defining log levels for exceptions

6.2
---
Expand Down
50 changes: 35 additions & 15 deletions src/Symfony/Component/HttpKernel/EventListener/ErrorListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@
namespace Symfony\Component\HttpKernel\EventListener;

use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\HttpStatus;
use Symfony\Component\HttpKernel\Attribute\WithLogLevel;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
Expand Down Expand Up @@ -52,14 +54,7 @@ public function __construct(string|object|array|null $controller, LoggerInterfac
public function logKernelException(ExceptionEvent $event)
{
$throwable = $event->getThrowable();
$logLevel = null;

foreach ($this->exceptionsMapping as $class => $config) {
if ($throwable instanceof $class && $config['log_level']) {
$logLevel = $config['log_level'];
break;
}
}
$logLevel = $this->resolveLogLevel($throwable);

foreach ($this->exceptionsMapping as $class => $config) {
if (!$throwable instanceof $class || !$config['status_code']) {
Expand Down Expand Up @@ -170,15 +165,40 @@ public static function getSubscribedEvents(): array
*/
protected function logException(\Throwable $exception, string $message, string $logLevel = null): void
{
if (null !== $this->logger) {
if (null !== $logLevel) {
$this->logger->log($logLevel, $message, ['exception' => $exception]);
} elseif (!$exception instanceof HttpExceptionInterface || $exception->getStatusCode() >= 500) {
$this->logger->critical($message, ['exception' => $exception]);
} else {
$this->logger->error($message, ['exception' => $exception]);
if (null === $this->logger) {
return;
}

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

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

/**
* Resolves the level to be used when logging the exception.
*/
private function resolveLogLevel(\Throwable $throwable): string
{
foreach ($this->exceptionsMapping as $class => $config) {
if ($throwable instanceof $class && $config['log_level']) {
return $config['log_level'];
}
}

$attributes = (new \ReflectionClass($throwable))->getAttributes(WithLogLevel::class);

if ($attributes) {
/** @var WithLogLevel $instance */
$instance = $attributes[0]->newInstance();

return $instance->level;
}

if (!$throwable instanceof HttpExceptionInterface || $throwable->getStatusCode() >= 500) {
return LogLevel::CRITICAL;
}

return LogLevel::ERROR;
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpKernel\Tests\Attribute;

use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;
use Symfony\Component\HttpKernel\Attribute\WithLogLevel;

/**
* @author Dejan Angelov <angelovdejan@protonmail.com>
*/
class WithLogLevelTest extends TestCase
{
public function testWithValidLogLevel()
{
$logLevel = LogLevel::NOTICE;

$attribute = new WithLogLevel($logLevel);

$this->assertSame($logLevel, $attribute->level);
}

public function testWithInvalidLogLevel()
{
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid log level "invalid".');

new WithLogLevel('invalid');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,13 @@

use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\HttpStatus;
use Symfony\Component\HttpKernel\Attribute\WithLogLevel;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
Expand Down Expand Up @@ -118,6 +120,40 @@ public function testHandleWithLoggerAndCustomConfiguration()
$this->assertCount(1, $logger->getLogs('warning'));
}

public function testHandleWithLogLevelAttribute()
{
$request = new Request();
$event = new ExceptionEvent(new TestKernel(), $request, HttpKernelInterface::MAIN_REQUEST, new WarningWithLogLevelAttribute());
$logger = new TestLogger();
$l = new ErrorListener('not used', $logger);

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

$this->assertEquals(0, $logger->countErrors());
$this->assertCount(0, $logger->getLogs('critical'));
$this->assertCount(1, $logger->getLogs('warning'));
}

public function testHandleWithLogLevelAttributeAndCustomConfiguration()
{
$request = new Request();
$event = new ExceptionEvent(new TestKernel(), $request, HttpKernelInterface::MAIN_REQUEST, new WarningWithLogLevelAttribute());
$logger = new TestLogger();
$l = new ErrorListener('not used', $logger, false, [
WarningWithLogLevelAttribute::class => [
'log_level' => 'info',
'status_code' => 401,
],
]);
$l->logKernelException($event);
$l->onKernelException($event);

$this->assertEquals(0, $logger->countErrors());
$this->assertCount(0, $logger->getLogs('warning'));
$this->assertCount(1, $logger->getLogs('info'));
}

/**
* @dataProvider exceptionWithAttributeProvider
*/
Expand Down Expand Up @@ -312,3 +348,8 @@ class WithCustomUserProvidedAttribute extends \Exception
class WithGeneralAttribute extends \Exception
{
}

#[WithLogLevel(LogLevel::WARNING)]
class WarningWithLogLevelAttribute extends \Exception
{
}