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

Add the Monolog hook functionality #573

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
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
35 changes: 35 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ parameters:
count: 1
path: src/DependencyInjection/SentryExtension.php

-
message: "#^Cannot access offset 'enabled' on mixed\\.$#"
count: 1
path: src/DependencyInjection/SentryExtension.php

-
message: "#^Cannot access offset 'excluded_commands' on mixed\\.$#"
count: 1
Expand Down Expand Up @@ -85,6 +90,11 @@ parameters:
count: 1
path: src/DependencyInjection/SentryExtension.php

-
message: "#^Parameter \\#1 \\$level of static method Monolog\\\\Logger\\:\\:toMonologLevel\\(\\) expects 100\\|200\\|250\\|300\\|400\\|500\\|550\\|600\\|'ALERT'\\|'alert'\\|'CRITICAL'\\|'critical'\\|'DEBUG'\\|'debug'\\|'EMERGENCY'\\|'emergency'\\|'ERROR'\\|'error'\\|'INFO'\\|'info'\\|'NOTICE'\\|'notice'\\|'WARNING'\\|'warning', mixed given\\.$#"
count: 1
path: src/DependencyInjection/SentryExtension.php

-
message: "#^Parameter \\#2 \\$array of function array_map expects array, mixed given\\.$#"
count: 1
Expand All @@ -110,6 +120,11 @@ parameters:
count: 1
path: src/DependencyInjection/SentryExtension.php

-
message: "#^Parameter \\#2 \\$config of method Sentry\\\\SentryBundle\\\\DependencyInjection\\\\SentryExtension\\:\\:registerMonologHandlerConfiguration\\(\\) expects array\\<string, mixed\\>, mixed given\\.$#"
count: 1
path: src/DependencyInjection/SentryExtension.php

-
message: "#^Parameter \\#2 \\$config of method Sentry\\\\SentryBundle\\\\DependencyInjection\\\\SentryExtension\\:\\:registerTracingConfiguration\\(\\) expects array\\<string, mixed\\>, mixed given\\.$#"
count: 1
Expand Down Expand Up @@ -175,6 +190,26 @@ parameters:
count: 1
path: src/EventListener/SubRequestListener.php

-
message: "#^Cannot call method getType\\(\\) on Sentry\\\\ExceptionDataBag\\|null\\.$#"
count: 1
path: src/Integration/IgnoreFatalErrorExceptionsIntegration.php

-
message: "#^Cannot call method getValue\\(\\) on Sentry\\\\ExceptionDataBag\\|null\\.$#"
count: 1
path: src/Integration/IgnoreFatalErrorExceptionsIntegration.php

-
message: "#^Instanceof between null and Symfony\\\\Component\\\\ErrorHandler\\\\Error\\\\FatalError will always evaluate to false\\.$#"
count: 1
path: src/Monolog/SymfonyHandler.php

-
message: "#^Offset 'exception' on array\\{message\\: string, context\\: array, level\\: 100\\|200\\|250\\|300\\|400\\|500\\|550\\|600, level_name\\: 'ALERT'\\|'CRITICAL'\\|'DEBUG'\\|'EMERGENCY'\\|'ERROR'\\|'INFO'\\|'NOTICE'\\|'WARNING', channel\\: string, datetime\\: DateTimeImmutable, extra\\: array\\} on left side of \\?\\? does not exist\\.$#"
count: 1
path: src/Monolog/SymfonyHandler.php

-
message: "#^Parameter \\#1 \\$driver of method Sentry\\\\SentryBundle\\\\Tracing\\\\Doctrine\\\\DBAL\\\\TracingDriverMiddleware\\:\\:wrap\\(\\) expects Doctrine\\\\DBAL\\\\Driver, mixed given\\.$#"
count: 1
Expand Down
35 changes: 35 additions & 0 deletions src/DependencyInjection/Compiler/RegisterMonologHandlerPass.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace Sentry\SentryBundle\DependencyInjection\Compiler;

use Sentry\Monolog\Handler;
use Sentry\SentryBundle\Monolog\SymfonyHandler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class RegisterMonologHandlerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container): void
{
if (!$container->hasDefinition(Handler::class)) {
return;
}

$this->registerMainHandler($container);
}

private function registerMainHandler(ContainerBuilder $container): void
{
foreach ($container->getServiceIds() as $serviceName) {
if (!str_starts_with($serviceName, 'monolog.logger.')) {
continue;
}

$logger = $container->getDefinition($serviceName);
$logger->addMethodCall('pushHandler', [new Reference(SymfonyHandler::class)]);
}
}
}
22 changes: 22 additions & 0 deletions src/DependencyInjection/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Jean85\PrettyVersions;
use Monolog\Logger;
use Sentry\Options;
use Sentry\SentryBundle\ErrorTypesParser;
use Sentry\Transport\TransportFactoryInterface;
Expand Down Expand Up @@ -143,6 +144,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->end();

$this->addMessengerSection($rootNode);
$this->addMonologSection($rootNode);
$this->addDistributedTracingSection($rootNode);

return $treeBuilder;
Expand All @@ -161,6 +163,26 @@ private function addMessengerSection(ArrayNodeDefinition $rootNode): void
->end();
}

private function addMonologSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
->children()
->arrayNode('monolog')
->addDefaultsIfNotSet()
->children()
->arrayNode('error_handler')
->{class_exists(Logger::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->end()
->scalarNode('level')
->defaultValue(Logger::DEBUG)
->cannotBeEmpty()
->end()
->booleanNode('bubble')->defaultTrue()->end()
->end()
->end()
->end();
}

private function addDistributedTracingSection(ArrayNodeDefinition $rootNode): void
{
$rootNode
Expand Down
33 changes: 32 additions & 1 deletion src/DependencyInjection/SentryExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,38 @@

use Doctrine\Bundle\DoctrineBundle\DoctrineBundle;
use Jean85\PrettyVersions;
use LogicException;
use Monolog\Logger as MonologLogger;
use Psr\Log\NullLogger;
use Sentry\Client;
use Sentry\ClientBuilder;
use Sentry\Integration\IgnoreErrorsIntegration;
use Sentry\Integration\IntegrationInterface;
use Sentry\Integration\RequestFetcherInterface;
use Sentry\Integration\RequestIntegration;
use Sentry\Monolog\Handler as SentryHandler;
use Sentry\Options;
use Sentry\SentryBundle\EventListener\ConsoleListener;
use Sentry\SentryBundle\EventListener\ErrorListener;
use Sentry\SentryBundle\EventListener\MessengerListener;
use Sentry\SentryBundle\EventListener\TracingConsoleListener;
use Sentry\SentryBundle\EventListener\TracingRequestListener;
use Sentry\SentryBundle\EventListener\TracingSubRequestListener;
use Sentry\SentryBundle\Monolog\SymfonyHandler;
use Sentry\SentryBundle\SentryBundle;
use Sentry\SentryBundle\Tracing\Doctrine\DBAL\ConnectionConfigurator;
use Sentry\SentryBundle\Tracing\Doctrine\DBAL\TracingDriverMiddleware;
use Sentry\SentryBundle\Tracing\Twig\TwigTracingExtension;
use Sentry\Serializer\RepresentationSerializer;
use Sentry\Serializer\Serializer;
use Sentry\State\HubInterface;
use Sentry\Transport\TransportFactoryInterface;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Debug\Exception\FatalErrorException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\ErrorHandler\Error\FatalError;
Expand Down Expand Up @@ -74,6 +78,7 @@ protected function loadInternal(array $mergedConfig, ContainerBuilder $container
$this->registerDbalTracingConfiguration($container, $mergedConfig['tracing']);
$this->registerTwigTracingConfiguration($container, $mergedConfig['tracing']);
$this->registerCacheTracingConfiguration($container, $mergedConfig['tracing']);
$this->registerMonologHandlerConfiguration($container, $mergedConfig['monolog']);
}

/**
Expand Down Expand Up @@ -247,6 +252,32 @@ private function registerCacheTracingConfiguration(ContainerBuilder $container,
$container->setParameter('sentry.tracing.cache.enabled', $isConfigEnabled);
}

/**
* @param array<string, mixed> $config
*/
private function registerMonologHandlerConfiguration(ContainerBuilder $container, array $config): void
{
$errorHandlerConfig = $config['error_handler'];

if (!$errorHandlerConfig['enabled']) {
$container->removeDefinition(SymfonyHandler::class);
$container->removeDefinition(SentryHandler::class);

return;
}

if (!class_exists(MonologLogger::class)) {
throw new LogicException(sprintf('To use the "%s" class you need to require the "symfony/monolog-bundle" package.', SymfonyHandler::class));
}

$definition = $container->getDefinition(SymfonyHandler::class);
$definition->setArguments([
new Reference(HubInterface::class),
MonologLogger::toMonologLevel($config['level']),
$config['bubble'],
]);
}

/**
* @param string[] $integrations
* @param array<string, mixed> $config
Expand Down
41 changes: 41 additions & 0 deletions src/Integration/IgnoreFatalErrorExceptionsIntegration.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace Sentry\SentryBundle\Integration;

use Sentry\Event;
use Sentry\ExceptionDataBag;
use Sentry\Integration\IntegrationInterface;
use Sentry\State\Scope;
use Symfony\Component\ErrorHandler\Error\FatalError;

/**
* This integration skips the current {@see Event} if it is a {@see FatalError}
* generated by Symfony that wraps an unhandled exception
* (which should be already captured by Sentry).
*/
final class IgnoreFatalErrorExceptionsIntegration implements IntegrationInterface
{
/**
* @var ExceptionDataBag|null
*/
private static $previousExceptionDataBag = null;

public function setupOnce(): void
{
Scope::addGlobalEventProcessor(static function (Event $event): ?Event {
$exceptionDataBag = $event->getExceptions()[0] ?? null;

if (
$exceptionDataBag instanceof ExceptionDataBag
&& $exceptionDataBag->getType() === self::$previousExceptionDataBag->getType()
&& $exceptionDataBag->getValue() === self::$previousExceptionDataBag->getValue()
) {
return null;
}

return $event;
});
}
}
77 changes: 77 additions & 0 deletions src/Monolog/SymfonyHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

declare(strict_types=1);

namespace Sentry\SentryBundle\Monolog;

use Monolog\Formatter\FormatterInterface;
use Monolog\Handler\FormattableHandlerInterface;
use Monolog\Handler\HandlerInterface;
use Monolog\Handler\ProcessableHandlerInterface;
use Monolog\ResettableInterface;
use Sentry\Monolog\Handler;
use Symfony\Component\ErrorHandler\Error\FatalError;

class SymfonyHandler implements HandlerInterface, ProcessableHandlerInterface, FormattableHandlerInterface, ResettableInterface
{
/**
* @var Handler
*/
private $decoratedHandler;

public function __construct(Handler $decoratedHandler)
{
$this->decoratedHandler = $decoratedHandler;
}

public function setFormatter(FormatterInterface $formatter): HandlerInterface
{
return $this->decoratedHandler->setFormatter($formatter);
}

public function getFormatter(): FormatterInterface
{
return $this->decoratedHandler->getFormatter();
}

public function isHandling(array $record): bool
{
return $this->decoratedHandler->isHandling($record);
}

public function handleBatch(array $records): void
{
$this->decoratedHandler->handleBatch($records);
}

public function close(): void
{
$this->decoratedHandler->close();
}

public function pushProcessor(callable $callback): HandlerInterface
{
return $this->decoratedHandler->pushProcessor($callback);
}

public function popProcessor(): callable
{
return $this->decoratedHandler->popProcessor();
}

public function reset(): void
{
$this->decoratedHandler->reset();
}

public function handle(array $record): bool
{
$exception = $record['exception'] ?? null;

if ($exception instanceof FatalError) {
return false;
}

return $this->decoratedHandler->handle($record);
}
}
45 changes: 45 additions & 0 deletions src/Resources/config/schema/sentry-1.0.xsd
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
<xsd:element name="options" type="options" minOccurs="0" maxOccurs="1" />
<xsd:element name="messenger" type="messenger" minOccurs="0" maxOccurs="1" />
<xsd:element name="tracing" type="tracing" minOccurs="0" maxOccurs="1" />
<xsd:element name="monolog" type="monolog" minOccurs="0" maxOccurs="1" />
</xsd:choice>

<xsd:attribute name="register-error-listener" type="xsd:boolean" />
Expand Down Expand Up @@ -117,4 +118,48 @@
<xsd:element name="excluded-command" type="xsd:string" minOccurs="0" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>

<xsd:complexType name="monolog">
<xsd:choice maxOccurs="unbounded">
<xsd:element name="error-handler" type="monolog-error-handler" minOccurs="0" maxOccurs="1" />
</xsd:choice>

<xsd:attribute name="level" type="monolog-level" />
<xsd:attribute name="bubble" type="xsd:boolean" />
</xsd:complexType>

<xsd:complexType name="monolog-error-handler">
<xsd:attribute name="enabled" type="xsd:boolean" />
</xsd:complexType>

<xsd:simpleType name="monolog-level">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="debug" />
<xsd:enumeration value="info" />
<xsd:enumeration value="notice" />
<xsd:enumeration value="warning" />
<xsd:enumeration value="error" />
<xsd:enumeration value="critical" />
<xsd:enumeration value="alert" />
<xsd:enumeration value="emergency" />

<xsd:enumeration value="DEBUG" />
<xsd:enumeration value="INFO" />
<xsd:enumeration value="NOTICE" />
<xsd:enumeration value="WARNING" />
<xsd:enumeration value="ERROR" />
<xsd:enumeration value="CRITICAL" />
<xsd:enumeration value="ALERT" />
<xsd:enumeration value="EMERGENCY" />

<xsd:enumeration value="100" />
<xsd:enumeration value="200" />
<xsd:enumeration value="250" />
<xsd:enumeration value="300" />
<xsd:enumeration value="400" />
<xsd:enumeration value="500" />
<xsd:enumeration value="550" />
<xsd:enumeration value="600" />
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
Loading