Skip to content

Commit

Permalink
feature #48747 [HttpKernel] Allow using #[WithLogLevel] for setting…
Browse files Browse the repository at this point in the history
… custom log level for exceptions (angelov)

This PR was squashed before being merged into the 6.3 branch.

Discussion
----------

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

| Q             | A
| ------------- | ---
| Branch?       | 6.3
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       |
| License       | MIT
| Doc PR        | TODO

With these changes, we're extending the functionality for setting a custom log level for a given exception by introducing a new `WithLogLevel` attribute.

Example:
```php
#[WithLogLevel(\Psr\Log\LogLevel::CRITICAL)]
class AccountBalanceIsNegative extends \Exception
{
}
```

This will have a lower priority compared to the log level set using the option in the configuration files.
(Meaning that if we have both an attribute declared on an exception class, and another level set for the same class in the configuration, the one from the configuration will be used.)

Commits
-------

0a2563d [HttpKernel] Allow using `#[WithLogLevel]` for setting custom log level for exceptions
  • Loading branch information
fabpot committed Jan 5, 2023
2 parents 6b6c67a + 0a2563d commit 5c09985
Show file tree
Hide file tree
Showing 5 changed files with 147 additions and 15 deletions.
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
{
}

0 comments on commit 5c09985

Please sign in to comment.