Skip to content
Open
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
6 changes: 6 additions & 0 deletions analysis-baseline.toml
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,12 @@ code = "mixed-assignment"
message = "Assigning `mixed` type to a variable may lead to unexpected behavior."
count = 2

[[issues]]
file = "src/Monolog/Handler.php"
code = "possibly-invalid-argument"
message = 'Possible argument type mismatch for argument #1 of `Monolog\Handler\AbstractProcessingHandler::handle`: expected `Monolog\LogRecord`, but possibly received `Monolog\LogRecord|array<string, mixed>`.'
count = 1

[[issues]]
file = "src/Monolog/LogToSentryIssueHandler.php"
code = "deprecated-class-constant"
Expand Down
3 changes: 2 additions & 1 deletion src/Monolog/ExceptionToSentryIssueHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
class ExceptionToSentryIssueHandler extends AbstractProcessingHandler
{
use CompatibilityProcessingHandlerTrait;
use SentryContextFlagTrait;

/**
* @var HubInterface
Expand All @@ -42,7 +43,7 @@ public function handle($record): bool
$exception = $this->getExceptionFromRecord($record);

/** @phpstan-ignore-next-line */
if ($exception === null || !$this->isHandling($record)) {
if ($exception === null || !$this->isHandling($record) || self::isSentryIssueDisabled($this->getContextFromRecord($record))) {
return false;
}

Expand Down
28 changes: 28 additions & 0 deletions src/Monolog/Handler.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
final class Handler extends AbstractProcessingHandler
{
use CompatibilityProcessingHandlerTrait;
use SentryContextFlagTrait;

private const CONTEXT_EXCEPTION_KEY = 'exception';

Expand All @@ -52,6 +53,19 @@ public function __construct(HubInterface $hub, $level = Logger::DEBUG, bool $bub
$this->fillExtraContext = $fillExtraContext;
}

/**
* @param array<string, mixed>|LogRecord $record
*/
public function handle($record): bool
{
if (self::isSentryIssueDisabled($this->getArrayFieldFromRecord($record, 'context'))) {
return false;
}

/** @phpstan-ignore-next-line */
return parent::handle($record);
}

/**
* @param array<string, mixed>|LogRecord $record
*/
Expand Down Expand Up @@ -88,6 +102,20 @@ protected function doWrite($record): void
});
}

/**
* @param array<string, mixed>|LogRecord $record
*
* @return mixed[]
*/
private function getArrayFieldFromRecord($record, string $field): array
{
if (isset($record[$field]) && \is_array($record[$field])) {
return $record[$field];
}

return [];
}

/**
* @param mixed[] $context
*
Expand Down
5 changes: 5 additions & 0 deletions src/Monolog/LogToSentryIssueHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
class LogToSentryIssueHandler extends AbstractProcessingHandler
{
use CompatibilityProcessingHandlerTrait;
use SentryContextFlagTrait;

private const CONTEXT_EXCEPTION_KEY = 'exception';

Expand Down Expand Up @@ -49,6 +50,10 @@ public function __construct(HubInterface $hub, $level = Logger::DEBUG, bool $bub
*/
public function handle($record): bool
{
if (self::isSentryIssueDisabled($this->getArrayFieldFromRecord($record, 'context'))) {
return false;
}

/** @phpstan-ignore-next-line */
if (!$this->isHandling($record) || $this->hasThrowable($record)) {
return false;
Expand Down
28 changes: 28 additions & 0 deletions src/Monolog/SentryContextFlagTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<?php

declare(strict_types=1);

namespace Sentry\Monolog;

/**
* Allows a single log record to opt out of being reported as a Sentry issue
* by setting the `sentry` key of its context to `false`, e.g.:
*
* $logger->warning('Invalid CSV row', ['sentry' => false]);
*
* The record is still handled by every other handler (including the
* {@see BreadcrumbHandler} and the {@see LogsHandler}), so it remains
* available as context should another record trigger an issue.
*
* @internal
*/
trait SentryContextFlagTrait
{
/**
* @param mixed[] $context The context of the log record
*/
private static function isSentryIssueDisabled(array $context): bool
{
return ($context['sentry'] ?? null) === false;
}
}
23 changes: 23 additions & 0 deletions tests/Monolog/ExceptionToSentryIssueHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,29 @@ public function testHandleIgnoresRecordsWithoutThrowable($record): void
$this->assertFalse($handler->handle($record));
}

public function testHandleIgnoresRecordsWithSentryDisabledInContext(): void
{
/** @var ClientInterface&MockObject $client */
$client = $this->createMock(ClientInterface::class);
$client->expects($this->never())
->method('captureException');

$handler = new ExceptionToSentryIssueHandler(new Hub($client, new Scope()), Logger::DEBUG, false);
$record = RecordFactory::create(
'foo bar',
Logger::ERROR,
'channel.foo',
[
'exception' => new \RuntimeException('boom'),
'sentry' => false,
],
[]
);

$this->assertTrue($handler->isHandling($record));
$this->assertFalse($handler->handle($record));
}

public function testHandleIgnoresRecordsBelowThreshold(): void
{
$exception = new \RuntimeException('boom');
Expand Down
13 changes: 13 additions & 0 deletions tests/Monolog/HandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ public function testHandle(bool $fillExtraContext, $record, Event $expectedEvent
$handler->handle($record);
}

public function testHandleIgnoresRecordsWithSentryDisabledInContext(): void
{
/** @var ClientInterface&MockObject $client */
$client = $this->createMock(ClientInterface::class);
$client->expects($this->never())
->method('captureEvent');

$handler = new Handler(new Hub($client, new Scope()), Logger::DEBUG, false);

$this->assertFalse($handler->handle(RecordFactory::create('foo bar', Logger::WARNING, 'channel.foo', ['sentry' => false], [])));
$this->assertFalse($handler->handle(RecordFactory::create('foo bar', Logger::ERROR, 'channel.foo', ['exception' => new \RuntimeException('boom'), 'sentry' => false], [])));
}

public static function handleDataProvider(): iterable
{
$event = Event::createEvent();
Expand Down
78 changes: 78 additions & 0 deletions tests/Monolog/LogToSentryIssueHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,12 @@
use Monolog\LogRecord;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Sentry\Breadcrumb;
use Sentry\ClientBuilder;
use Sentry\ClientInterface;
use Sentry\Event;
use Sentry\EventHint;
use Sentry\Monolog\BreadcrumbHandler;
use Sentry\Monolog\ExceptionToSentryIssueHandler;
use Sentry\Monolog\LogToSentryIssueHandler;
use Sentry\Severity;
Expand Down Expand Up @@ -142,6 +144,82 @@ public function testHandleCapturesRecordsWithNonThrowableExceptionContext(): voi
$this->assertTrue($handler->handle($record));
}

public function testHandleIgnoresRecordsWithSentryDisabledInContext(): void
{
/** @var ClientInterface&MockObject $client */
$client = $this->createMock(ClientInterface::class);
$client->expects($this->never())
->method('captureEvent');

$handler = new LogToSentryIssueHandler(new Hub($client, new Scope()), Logger::DEBUG, false);
$record = RecordFactory::create('foo bar', Logger::WARNING, 'channel.foo', ['sentry' => false], []);

$this->assertTrue($handler->isHandling($record));
$this->assertFalse($handler->handle($record));
}

/**
* @dataProvider nonFalseSentryContextValueDataProvider
*
* @param mixed $value
*/
public function testHandleCapturesRecordsWhenSentryContextIsNotFalse($value): void
{
/** @var ClientInterface&MockObject $client */
$client = $this->createMock(ClientInterface::class);
$client->expects($this->once())
->method('captureEvent');

$handler = new LogToSentryIssueHandler(new Hub($client, new Scope()), Logger::DEBUG, false);
$record = RecordFactory::create('foo bar', Logger::WARNING, 'channel.foo', ['sentry' => $value], []);

$this->assertTrue($handler->handle($record));
}

/**
* @return iterable<array{mixed}>
*/
public static function nonFalseSentryContextValueDataProvider(): iterable
{
yield [true];
yield [null];
yield [0];
yield [''];
yield ['false'];
}

public function testRecordWithSentryDisabledIsStillRecordedAsBreadcrumb(): void
{
$client = ClientBuilder::create()
->setTransport(StubTransport::getInstance())
->getClient();
$hub = new Hub($client, new Scope());

$logger = new Logger('channel.foo', [
new LogToSentryIssueHandler($hub, Logger::WARNING),
new ExceptionToSentryIssueHandler($hub, Logger::WARNING),
new BreadcrumbHandler($hub),
]);

$logger->warning('ignored warning', ['sentry' => false]);
$logger->error('ignored exception', ['exception' => new \RuntimeException('boom'), 'sentry' => false]);

$this->assertCount(0, StubTransport::$events);

$logger->warning('reported warning');

$this->assertCount(1, StubTransport::$events);

$event = StubTransport::$events[0];
$this->assertSame('reported warning', $event->getMessage());

$breadcrumbMessages = array_map(static function (Breadcrumb $breadcrumb): ?string {
return $breadcrumb->getMessage();
}, $event->getBreadcrumbs());

$this->assertSame(['ignored warning', 'ignored exception'], $breadcrumbMessages);
}

public function testHandleIgnoresRecordsBelowThreshold(): void
{
/** @var ClientInterface&MockObject $client */
Expand Down