diff --git a/src/Sentry/Laravel/Features/CacheIntegration.php b/src/Sentry/Laravel/Features/CacheIntegration.php index 2ed2b357..d6075d80 100644 --- a/src/Sentry/Laravel/Features/CacheIntegration.php +++ b/src/Sentry/Laravel/Features/CacheIntegration.php @@ -3,6 +3,7 @@ namespace Sentry\Laravel\Features; use Illuminate\Cache\Events; +use Illuminate\Foundation\Application; use Illuminate\Contracts\Events\Dispatcher; use Illuminate\Contracts\Session\Session; use Illuminate\Redis\Events as RedisEvents; @@ -22,6 +23,15 @@ class CacheIntegration extends Feature { use WorksWithSpans, TracksPushedScopesAndSpans, ResolvesEventOrigin; + /** + * Indicates whether to attempt to detect the session key when running in the console. + * + * @internal this is mainly intended for testing purposes. + * + * @var bool + */ + public static $detectSessionKeyOnConsole = false; + public function isApplicable(): bool { return $this->isTracingFeatureEnabled('redis_commands', false) @@ -259,7 +269,17 @@ private function maybeHandleCacheEventAsEndOfSpan(Events\CacheEvent $event): boo */ private function getSessionKey(): ?string { + $container = $this->container(); + try { + // A session key is highly unusal to be available when running in the console + // So we skip trying to get the session key in that case to prevent booting up the session store unnecessarily + // Doing this anyway can result in unnecessary database connections for example + // See: https://github.com/getsentry/sentry-laravel/issues/1057 + if (!self::$detectSessionKeyOnConsole && $container instanceof Application && $container->runningInConsole()) { + return null; + } + /** @var Session $sessionStore */ $sessionStore = $this->container()->make('session.store'); diff --git a/test/Sentry/Features/CacheIntegrationTest.php b/test/Sentry/Features/CacheIntegrationTest.php index 6aae519e..903d93f9 100644 --- a/test/Sentry/Features/CacheIntegrationTest.php +++ b/test/Sentry/Features/CacheIntegrationTest.php @@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Cache; use Sentry\Laravel\Tests\TestCase; use Sentry\Tracing\Span; +use Sentry\Laravel\Features\CacheIntegration; class CacheIntegrationTest extends TestCase { @@ -13,6 +14,14 @@ class CacheIntegrationTest extends TestCase 'session.driver' => 'array', ]; + protected function setUp(): void + { + parent::setUp(); + + // Ensure that session keys can be detected in the tests that are running from the console + CacheIntegration::$detectSessionKeyOnConsole = true; + } + public function testCacheBreadcrumbForWriteAndHitIsRecorded(): void { Cache::put($key = 'foo', 'bar');