Skip to content

Add Sentry logs #1000

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 19 commits into from
Jun 12, 2025
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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"require": {
"php": "^7.2 | ^8.0",
"illuminate/support": "^6.0 | ^7.0 | ^8.0 | ^9.0 | ^10.0 | ^11.0 | ^12.0",
"sentry/sentry": "^4.10",
"sentry/sentry": "^4.13",
"symfony/psr-http-message-bridge": "^1.0 | ^2.0 | ^6.0 | ^7.0",
"nyholm/psr7": "^1.0"
},
Expand Down
5 changes: 5 additions & 0 deletions src/Sentry/Laravel/Features/LogIntegration.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Illuminate\Support\Facades\Log;
use Sentry\Laravel\LogChannel;
use Sentry\Laravel\Logs\LogChannel as LogsLogChannel;

class LogIntegration extends Feature
{
Expand All @@ -17,5 +18,9 @@ public function register(): void
Log::extend('sentry', function ($app, array $config) {
return (new LogChannel($app))($config);
});

Log::extend('sentry_logs', function ($app, array $config) {
return (new LogsLogChannel($app))($config);
});
}
}
3 changes: 3 additions & 0 deletions src/Sentry/Laravel/Integration.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Sentry\EventId;
use Sentry\ExceptionMechanism;
use Sentry\Laravel\Integration\ModelViolations as ModelViolationReports;
use Sentry\Logs\Logs;
use Sentry\SentrySdk;
use Sentry\Tracing\TransactionSource;
use Throwable;
Expand Down Expand Up @@ -120,6 +121,8 @@ public static function flushEvents(): void

if ($client !== null) {
$client->flush();

Logs::getInstance()->flush();
}
}

Expand Down
5 changes: 0 additions & 5 deletions src/Sentry/Laravel/LogChannel.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,6 @@

class LogChannel extends LogManager
{
/**
* @param array $config
*
* @return Logger
*/
public function __invoke(array $config = []): Logger
{
$handler = new SentryHandler(
Expand Down
34 changes: 34 additions & 0 deletions src/Sentry/Laravel/Logs/LogChannel.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

namespace Sentry\Laravel\Logs;

use Monolog\Handler\FingersCrossedHandler;
use Monolog\Logger;
use Illuminate\Log\LogManager;

class LogChannel extends LogManager
{
public function __invoke(array $config = []): Logger
{
$handler = new LogsHandler(
$config['level'] ?? Logger::DEBUG,
$config['bubble'] ?? true
);

if (isset($config['action_level'])) {
$handler = new FingersCrossedHandler($handler, $config['action_level']);

// Consume the `action_level` config option since newer Laravel versions also support this option
// and will wrap the handler again in another `FingersCrossedHandler` if we leave the option set
// See: https://github.com/laravel/framework/pull/40305 (release v8.79.0)
unset($config['action_level']);
}

return new Logger(
$this->parseChannel($config),
[
$this->prepareHandler($handler, $config),
]
);
}
}
130 changes: 130 additions & 0 deletions src/Sentry/Laravel/Logs/LogsHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
<?php

namespace Sentry\Laravel\Logs;

use Sentry\Logs\LogLevel;
use Monolog\Formatter\LineFormatter;
use Monolog\Formatter\FormatterInterface;
use Monolog\Handler\AbstractProcessingHandler;
use Sentry\Monolog\CompatibilityProcessingHandlerTrait;
use Sentry\Severity;
use Throwable;

class LogsHandler extends AbstractProcessingHandler
{
use CompatibilityProcessingHandlerTrait;

/**
* @var FormatterInterface The formatter to use for the logs generated via handleBatch()
*/
protected $batchFormatter;

/**
* {@inheritdoc}
*/
public function handleBatch(array $records): void
{
$level = $this->level;

// filter records based on their level
$records = array_filter(
$records,
function ($record) use ($level) {
return $record['level'] >= $level;
}
);

if (!$records) {
return;
}

// the record with the highest severity is the "main" one
$record = array_reduce(
$records,
function ($highest, $record) {
if ($highest === null || $record['level'] > $highest['level']) {
return $record;
}

return $highest;
}
);

// the other ones are added as a context item
$logs = [];
foreach ($records as $r) {
$logs[] = $this->processRecord($r);
}

if ($logs) {
$record['context']['logs'] = (string)$this->getBatchFormatter()->formatBatch($logs);
}

$this->handle($record);
}

/**
* Sets the formatter for the logs generated by handleBatch().
*
* @param FormatterInterface $formatter
*
* @return \Sentry\Laravel\SentryHandler
*/
public function setBatchFormatter(FormatterInterface $formatter): self
{
$this->batchFormatter = $formatter;

return $this;
}

/**
* Gets the formatter for the logs generated by handleBatch().
*/
public function getBatchFormatter(): FormatterInterface
{
if (!$this->batchFormatter) {
$this->batchFormatter = new LineFormatter();
}

return $this->batchFormatter;
}

/**
* {@inheritdoc}
* @suppress PhanTypeMismatchArgument
*/
protected function doWrite($record): void
{
$exception = $record['context']['exception'] ?? null;

if ($exception instanceof Throwable) {
return;
}

\Sentry\logger()->aggregator()->add(
// This seems a little bit of a roundabout way to get the log level, but this is done for compatibility
self::getLogLevelFromSeverity(
self::getSeverityFromLevel($record['level'])
),
$record['message'],
[],
array_merge($record['context'], $record['extra'])
);
}

private static function getLogLevelFromSeverity(Severity $severity): LogLevel
{
switch ($severity) {
case Severity::debug():
return LogLevel::debug();
case Severity::warning():
return LogLevel::warn();
case Severity::error():
return LogLevel::error();
case Severity::fatal():
return LogLevel::fatal();
default:
return LogLevel::info();
}
}
}
14 changes: 0 additions & 14 deletions test/Sentry/Features/ConsoleSchedulingIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,20 +142,6 @@ public function testScheduleMacroIsRegisteredWithoutDsnSet(): void
$this->assertTrue(Event::hasMacro('sentryMonitor'));
}

/** @define-env envSamplingAllTransactions */
public function testScheduledCommandCreatesTransaction(): void
{
$this->getScheduler()->command('inspire')->everyMinute();

$this->artisan('schedule:run');

$this->assertSentryTransactionCount(1);

$transaction = $this->getLastSentryEvent();

$this->assertEquals('inspire', $transaction->getTransaction());
}

Comment on lines -145 to -158
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is a little redundant and laravel/framework#55624 broke this test (as it should have before probably), will try to fix at a later point because I can't find a good workaround for now.

/** @define-env envSamplingAllTransactions */
public function testScheduledClosureCreatesTransaction(): void
{
Expand Down
117 changes: 117 additions & 0 deletions test/Sentry/Features/LogLogsIntegrationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
<?php

namespace Sentry\Features;

use Illuminate\Config\Repository;
use Illuminate\Support\Facades\Log;
use Sentry\Laravel\Tests\TestCase;
use Sentry\Logs\LogLevel;
use function Sentry\logger;

class LogLogsIntegrationTest extends TestCase
{
protected function defineEnvironment($app): void
{
parent::defineEnvironment($app);

tap($app['config'], static function (Repository $config) {
$config->set('sentry.enable_logs', true);

$config->set('logging.channels.sentry_logs', [
'driver' => 'sentry_logs',
]);

$config->set('logging.channels.sentry_logs_error_level', [
'driver' => 'sentry_logs',
'level' => 'error',
]);
});
}

public function testLogChannelIsRegistered(): void
{
$this->expectNotToPerformAssertions();

Log::channel('sentry_logs');
}

/** @define-env envWithoutDsnSet */
public function testLogChannelIsRegisteredWithoutDsn(): void
{
$this->expectNotToPerformAssertions();

Log::channel('sentry_logs');
}

public function testLogChannelGeneratesLogs(): void
{
$logger = Log::channel('sentry_logs');

$logger->info('Sentry Laravel info log message');

$logs = $this->getAndFlushCapturedLogs();

$this->assertCount(1, $logs);

$log = $logs[0];

$this->assertEquals(LogLevel::info(), $log->getLevel());
$this->assertEquals('Sentry Laravel info log message', $log->getBody());
}

public function testLogChannelGeneratesLogsOnlyForConfiguredLevel(): void
{
$logger = Log::channel('sentry_logs_error_level');

$logger->info('Sentry Laravel info log message');
$logger->warning('Sentry Laravel warning log message');
$logger->error('Sentry Laravel error log message');

$logs = $this->getAndFlushCapturedLogs();

$this->assertCount(1, $logs);

$log = $logs[0];

$this->assertEquals(LogLevel::error(), $log->getLevel());
$this->assertEquals('Sentry Laravel error log message', $log->getBody());
}

public function testLogChannelDoesntCaptureExceptions(): void
{
$logger = Log::channel('sentry_logs');

$logger->error('Sentry Laravel error log message', ['exception' => new \Exception('Test exception')]);

$logs = $this->getAndFlushCapturedLogs();

$this->assertCount(0, $logs);
}

public function testLogChannelAddsContextAsAttributes(): void
{
$logger = Log::channel('sentry_logs');

$logger->info('Sentry Laravel info log message', [
'foo' => 'bar',
]);

$logs = $this->getAndFlushCapturedLogs();

$this->assertCount(1, $logs);

$log = $logs[0];

$this->assertEquals('bar', $log->attributes()->get('foo')->getValue());
}

/** @return \Sentry\Logs\Log[] */
private function getAndFlushCapturedLogs(): array
{
$logs = logger()->aggregator()->all();

logger()->aggregator()->flush();

return $logs;
}
}