### Install Project Dependencies with Composer Source: https://github.com/getsentry/sentry-symfony/blob/master/CONTRIBUTING.md Install all necessary project dependencies using Composer. This command should be run after cloning the repository. ```bash composer install ``` -------------------------------- ### Install Sentry SDK and HTTP Adapters Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-3.0.md When using a custom HTTP client and message factory instead of the metapackage, manually require the Sentry SDK and the desired HTTPlug adapters. This example uses Guzzle components. ```bash composer require sentry/sentry:^2.0 php-http/guzzle6-adapter guzzlehttp/psr7 ``` -------------------------------- ### Install Sentry Symfony SDK Source: https://github.com/getsentry/sentry-symfony/blob/master/README.md Install the SDK using Composer. This command adds the Sentry SDK package to your project dependencies. ```bash composer require sentry/sentry-symfony ``` -------------------------------- ### Clone the Sentry SDK for Symfony Repository Source: https://github.com/getsentry/sentry-symfony/blob/master/CONTRIBUTING.md Use this command to clone the repository locally. Ensure you have Git installed. ```bash git clone git@github.com:getsentry/sentry-symfony.git ``` -------------------------------- ### Configure cURL HTTP Client Options Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Example configuration for the default cURL HTTP client in Symfony, showing options for proxy authentication, SSL verification, and HTTP compression. ```yaml // config/packages/sentry.yaml sentry: options: - http_proxy_authentication: 'username:password' // user name and password to use for proxy authentication - http_ssl_verify_peer: false // default true, verify the peer's SSL certificate - http_compression: false // default true, http request body compression ``` -------------------------------- ### Configure Sentry Logger Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Configure a custom logger for Sentry via the `sentry.yaml` configuration file. This example sets up a debug file logger. ```yaml sentry: dsn: "%env(SENTRY_DSN)%" options: logger: "sentry.logger" services: sentry.logger: class: 'Sentry\Logger\DebugFileLogger' arguments: $filePath: '../../var/log/sentry.log' ``` -------------------------------- ### Verify Sentry SDK Configuration with `sentry:test` Command Source: https://context7.com/getsentry/sentry-symfony/llms.txt Use the `sentry:test` CLI command to validate your Sentry DSN configuration and send a test event. This is crucial for confirming connectivity during deployment or initial setup. ```bash # Run the test command php bin/console sentry:test # Expected output when correctly configured: # [INFO] DSN correctly configured in the current client # Sending test message... # [INFO] Message sent successfully with ID # Output when DSN is missing: # [ERROR] No client found # [INFO] Your DSN is probably missing, check your configuration ``` -------------------------------- ### Configure Sentry Ignore Exceptions Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Configure Sentry to ignore specific exceptions by updating the `ignore_exceptions` option in `sentry.yaml`. This example shows how to ignore fatal errors. ```yaml // config/packages/sentry.yaml sentry: options: ignore_exceptions: - 'Symfony\Component\ErrorHandler\Error\FatalError' - 'Symfony\Component\Debug\Exception\FatalErrorException' ``` -------------------------------- ### Configure Sentry Bundle Source: https://context7.com/getsentry/sentry-symfony/llms.txt Configure the Sentry SDK using the `sentry.yaml` file. All Sentry PHP SDK options are available under the `options` key. ```yaml # config/packages/sentry.yaml sentry: dsn: '%env(SENTRY_DSN)%' register_error_listener: true # capture kernel exceptions automatically register_error_handler: true # replace PHP error/exception handlers options: environment: '%kernel.environment%' release: '%env(default::SENTRY_RELEASE)%' sample_rate: 1.0 # 0.0–1.0: fraction of errors to send traces_sample_rate: 0.2 # 0.0–1.0: fraction of requests to trace profiles_sample_rate: 0.1 # relative to traces_sample_rate enable_tracing: true enable_logs: true send_default_pii: true # attach user IP and username max_breadcrumbs: 50 in_app_exclude: - '%kernel.cache_dir%' - '%kernel.project_dir%/vendor' ignore_exceptions: - Symfony\Component\HttpKernel\Exception\NotFoundHttpException ignore_transactions: - 'GET /health' tags: app_version: '1.2.0' before_send: App\Sentry\BeforeSendCallback # service ID messenger: enabled: true capture_soft_fails: true # capture errors that will be retried isolate_breadcrumbs_by_message: true isolate_context_by_message: true # isolate full runtime context per message tracing: enabled: true dbal: enabled: true ignore_prepare_spans: true # suppress db.sql.prepare spans connections: [default] cache: enabled: true http_client: enabled: true twig: enabled: true console: excluded_commands: - 'messenger:consume' - 'doctrine:migrations:migrate' ``` -------------------------------- ### Run Project Tests with PHPUnit Source: https://github.com/getsentry/sentry-symfony/blob/master/CONTRIBUTING.md Execute all project tests using PHPUnit. This is a crucial step to ensure your changes do not break existing functionality. ```bash vendor/bin/phpunit ``` -------------------------------- ### Recommended Version Pinning Source: https://github.com/getsentry/sentry-symfony/blob/master/CONTRIBUTING.md When specifying version requirements, it is recommended to pin against `1.x.*` or `1.x.y`. This ensures stability while allowing for patch updates. ```json "sentry/sentry": "^1.0" ``` ```json "sentry/sentry": "^1" ``` -------------------------------- ### Configure SDK Integrations with Callbacks in Symfony Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Allow passing callbacks to configure Sentry SDK integrations. Define a service with a factory and reference it in the Sentry configuration. ```yaml services: App\IntegrationCallback: factory: ['App\IntegrationCallback', 'factory'] sentry: options: integrations: 'App\IntegrationCallback' ``` -------------------------------- ### Replace sentry.monolog configuration with service definition Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-4.0.md The `sentry.monolog` configuration option has been removed. Instead, you should define the `Sentry Monolog\Handler` service directly in your services configuration, providing the necessary arguments. ```yaml sentry: monolog: level: !php/const Monolog\Logger::ERROR bubble: false error_handler: enabled: true ``` ```yaml services: Sentry\Monolog\Handler: arguments: $hub: '@Sentry\State\HubInterface' $level: !php/const Monolog\Logger::ERROR $bubble: false ``` -------------------------------- ### Use New Fluent APIs for TransactionContext Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Demonstrates the improved fluent API for setting transaction context properties, making code more readable and concise. ```php // Before $transactionContext = new TransactionContext(); $transactionContext->setName('GET /example'); $transactionContext->setOp('http.server'); // After $transactionContext = (new TransactionContext()) ->setName('GET /example'); ->setOp('http.server'); ``` -------------------------------- ### Enable Tracing in Sentry Configuration Source: https://context7.com/getsentry/sentry-symfony/llms.txt Enable Sentry tracing and set a sample rate for capturing traces. This configuration is typically placed in `config/packages/sentry.yaml`. ```yaml sentry: options: traces_sample_rate: 0.5 tracing: enabled: true ``` -------------------------------- ### Log Sentry Metrics in PHP Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Use `trace_metrics()` to log counter, gauge, and distribution metrics. Specify the metric name, value, and optional attributes. For gauge and distribution metrics, a unit can also be provided. ```php // Counter metric \Sentry\trace_metrics()->count('test-counter', 10, ['my-attribute' => 'foo']); // Gauge metric \Sentry\trace_metrics()->gauge('test-gauge', 50.0, ['my-attribute' => 'foo'], \Sentry\Unit::millisecond()); // Distribution metric \Sentry\trace_metrics()->distribution('test-distribution', 20.0, ['my-attribute' => 'foo'], \Sentry\Unit::kilobyte()); ``` -------------------------------- ### Configure Sentry Structured Logging Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Enable structured logging for Sentry by configuring the SDK and Monolog handler. Ensure the logger level is set appropriately. ```yaml sentry: options: enable_logs: true services: Sentry\SentryBundle\Monolog\LogsHandler: arguments: - !php/const Monolog\Logger::INFO monolog: handlers: sentry_logs: type: service id: Sentry\SentryBundle\Monolog\LogsHandler ``` -------------------------------- ### Update Sentry Before Send Callback Configuration (Service Name) Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-4.0.md Shows the updated configuration for the `before_send` callback. The value must now be the service name without the `@` prefix. ```yaml sentry: options: before_send: '@app.sentry.before_send' ``` ```yaml sentry: options: before_send: 'App\Sentry\BeforeSend::__invoke' ``` ```yaml sentry: options: before_send: ['App\Sentry\BeforeSend', '__invoke'] ``` ```yaml sentry: options: before_send: 'app.sentry.before_send' ``` -------------------------------- ### Configure Sentry DSN Source: https://github.com/getsentry/sentry-symfony/blob/master/README.md Add the Sentry DSN to your .env file for SDK configuration. Ensure the DSN is correctly set to connect to your Sentry project. ```dotenv ###> sentry/sentry-symfony ### SENTRY_DSN="https://public@sentry.example.com/1" ###< sentry/sentry-symfony ### ``` -------------------------------- ### Manually Capture Exception Event in PHP Source: https://context7.com/getsentry/sentry-symfony/llms.txt This code demonstrates how to manually capture an exception event using the Sentry SDK. It requires importing necessary Sentry classes and creating an EventHint with the exception and mechanism. ```php use Sentry\Event; use Sentry\EventHint; use Sentry\ExceptionMechanism; use Sentry\SentrySdk; $hub = SentrySdk::getCurrentHub(); $hint = EventHint::fromArray([ 'exception' => $throwable, 'mechanism' => new ExceptionMechanism(ExceptionMechanism::TYPE_GENERIC, false), ]); $hub->captureEvent(Event::createEvent(), $hint); ``` -------------------------------- ### Configure Monolog Log Level in PHP Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Configure the Monolog LogsHandler for Sentry using PHP configuration, passing a Monolog Level enum. ```php # or via PHP config $container->services() ->set(\Sentry\SentryBundle\Monolog\LogsHandler::class) ->args([\Monolog\Level::Info]); ``` -------------------------------- ### Automatic DBAL Query Tracing with Sentry Source: https://context7.com/getsentry/sentry-symfony/llms.txt Demonstrates how Sentry automatically traces all queries executed through Doctrine's EntityManager. Each query generates a Sentry child span with `db.sql.query` operation. ```php // All queries through EntityManager/DBAL are traced automatically. // Example — every query below creates a Sentry child span: use Doctrine\ORM\EntityManagerInterface; class OrderRepository { public function __construct(private readonly EntityManagerInterface $em) {} public function findPendingOrders(): array { // Traced as span: op="db.sql.query", description="SELECT o FROM App\Entity\Order o WHERE o.status = ?" return $this->em->createQuery( 'SELECT o FROM App\Entity\Order o WHERE o.status = :status' )->setParameter('status', 'pending')->getResult(); } } // Expected: "db.sql.query" span appears under the active HTTP transaction in Sentry ``` -------------------------------- ### Manually Serialize Console Input with Sentry Source: https://context7.com/getsentry/sentry-symfony/llms.txt Demonstrates how to manually serialize a Symfony Console InputInterface object using Sentry's ConsoleInputSerializer. This is equivalent to the automatic serialization configured in `sentry.yaml`. ```php // When a console command throws, the input is serialized automatically. // Equivalent manual usage: use Sentry\SentryBundle\Serializer\ConsoleInputSerializer; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputDefinition; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; $definition = new InputDefinition([ new InputArgument('env', InputArgument::REQUIRED), new InputOption('dry-run', null, InputOption::VALUE_NONE), ]); $input = new ArrayInput(['env' => 'production', '--dry-run' => true], $definition); $serializer = new ConsoleInputSerializer(); $result = $serializer($input); // $result = [ // 'arguments' => ['env' => 'production'], // 'options' => ['dry-run' => true, 'help' => false, ...], // ] ``` -------------------------------- ### Generate Sentry Trace Meta Tags in PHP Source: https://context7.com/getsentry/sentry-symfony/llms.txt Programmatically generate the HTML meta tags for Sentry trace propagation using `getTraceparent()` and `getBaggage()` functions. This is an alternative to using the Twig extension. ```php use function Sentry\getTraceparent; use function Sentry\getBaggage; $traceMeta = sprintf('', getTraceparent()); $baggageMeta = sprintf('', getBaggage()); ``` -------------------------------- ### Serialize Console Command Arguments for Sentry Source: https://context7.com/getsentry/sentry-symfony/llms.txt Configure Sentry to capture arguments and options from Symfony console commands. This typically involves setting up a serializer service, as shown in the `sentry.yaml` configuration. ```yaml sentry: # ... other options ... console: # Enable serialization of command arguments and options input_serializer: Sentry\SentryBundle\EventListener\ConsoleInputSerializer ``` -------------------------------- ### Update Sentry Before Breadcrumb Callback Configuration (Service Name) Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-4.0.md Illustrates the updated configuration for the `before_breadcrumb` callback. The value must now be the service name without the `@` prefix. ```yaml sentry: options: before_breadcrumb: '@app.sentry.before_breadcrumb' ``` ```yaml sentry: options: before_breadcrumb: 'App\Sentry\BeforeBreadcrumb::__invoke' ``` ```yaml sentry: options: before_breadcrumb: ['App\Sentry\BeforeBreadcrumb', '__invoke'] ``` ```yaml sentry: options: before_breadcrumb: 'app.sentry.before_breadcrumb' ``` -------------------------------- ### Simplify Breadcrumb API Usage Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Shows the simplified syntax for adding breadcrumbs with optional parameters like message, metadata, level, and type. ```php // Before \Sentry\addBreadcrumb( new \Sentry\Breadcrumb( \Sentry\Breadcrumb::LEVEL_INFO, \Sentry\Breadcrumb::TYPE_DEFAULT, 'auth', // category 'User authenticated', // message (optional) ['user_id' => $userId] // data (optional) ) ); // After \Sentry\addBreadcrumb( category: 'auth', message: 'User authenticated', // optional metadata: ['user_id' => $userId], // optional level: Breadcrumb::LEVEL_INFO, // set by default type: Breadcrumb::TYPE_DEFAULT, // set by default ); ``` -------------------------------- ### Enable DBAL Tracing in Sentry Source: https://context7.com/getsentry/sentry-symfony/llms.txt Configure Sentry to automatically trace Doctrine DBAL queries. When enabled, the bundle wraps Doctrine connections, creating spans for each SQL query. ```yaml # config/packages/sentry.yaml sentry: tracing: dbal: enabled: true ignore_prepare_spans: true # skip db.sql.prepare spans for cleaner traces connections: [default, readonly] ``` -------------------------------- ### Configure Monolog Log Level with PSR Constants in YAML Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Configure the Monolog LogsHandler for Sentry using PSR log level constants within a YAML configuration. ```yaml # or using PSR constants services: Sentry\SentryBundle\Monolog\LogsHandler: arguments: - !php/const Psr\Log\LogLevel::INFO ``` -------------------------------- ### Register Sentry Bundle Source: https://context7.com/getsentry/sentry-symfony/llms.txt Register the SentryBundle in your Symfony kernel's `config/bundles.php` file. ```php // config/bundles.php return [ // ... Sentry\SentryBundle\SentryBundle::class => ['all' => true], ]; ``` -------------------------------- ### Update integrations configuration Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-4.0.md The `sentry.options.integrations` configuration option now expects an array of strings, where each string is the container service name without the '@' prefix. Previously, it accepted service names prefixed with '@'. ```yaml sentry: options: integrations: - '@app.sentry.foo_integration' ``` ```yaml sentry: options: integrations: - 'app.sentry.foo_integration' ``` -------------------------------- ### Manually Set User Context in PHP Source: https://context7.com/getsentry/sentry-symfony/llms.txt This code demonstrates how to manually set the Sentry user context, including ID, email, and username. This is typically used for authenticated users or API token authentication. ```php use Sentry\SentrySdk; use Sentry\State\Scope; use Sentry\UserDataBag; SentrySdk::getCurrentHub()->configureScope(function (Scope $scope): void { $user = new UserDataBag(); $user->setId('usr_789'); $user->setEmail('alice@example.com'); $user->setUsername('alice'); $scope->setUser($user); }); ``` -------------------------------- ### Capture Exceptions with Sentry Source: https://github.com/getsentry/sentry-symfony/blob/master/README.md Use the captureException function to send caught exceptions to Sentry. This is typically done within a try-catch block. ```php use function Sentry\captureException; try { $this->functionThatMayFail(); } catch (\Throwable $exception) { captureException($exception); } ``` -------------------------------- ### Configure Monolog Log Level in YAML Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Configure the Monolog LogsHandler for Sentry to accept a string representation of the log level, such as 'info'. ```yaml services: Sentry\SentryBundle\Monolog\LogsHandler: arguments: - 'info' ``` -------------------------------- ### Update Sentry Excluded Exceptions Configuration Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-4.0.md Illustrates the change in configuring ignored exceptions. Previously, `excluded_exceptions` was used; now, `IgnoreErrorsIntegration` with `ignore_exceptions` should be configured. ```yaml sentry: options: excluded_exceptions: - RuntimeException ``` ```yaml sentry: options: integrations: - 'Sentry\Integration\IgnoreErrorsIntegration' services: Sentry\Integration\IgnoreErrorsIntegration: arguments: $options: ignore_exceptions: - RuntimeException ``` -------------------------------- ### Configure Monolog Handler for Sentry Logs Source: https://context7.com/getsentry/sentry-symfony/llms.txt Configure Monolog to use Sentry's `LogsHandler` to forward log records to Sentry. Specify the desired minimum logging level and whether logs should bubble up to other handlers. ```yaml # config/packages/monolog.yaml monolog: handlers: sentry_logs: type: service id: Sentry\SentryBundle\Monolog\LogsHandler services: Sentry\SentryBundle\Monolog\LogsHandler: arguments: $level: !php/const Monolog\Logger::WARNING $bubble: true ``` -------------------------------- ### Configure Console Input Serialization for Sentry Source: https://context7.com/getsentry/sentry-symfony/llms.txt Configure Sentry to serialize Symfony Console InputInterface objects. This is useful when console commands throw exceptions, ensuring that input details are captured in Sentry events. ```yaml sentry: options: class_serializers: Symfony\Component\Console\Input\InputInterface: Sentry\SentryBundle\Serializer\ConsoleInputSerializer ``` -------------------------------- ### Configure Sentry Messenger Options in YAML Source: https://context7.com/getsentry/sentry-symfony/llms.txt This YAML configuration snippet shows how to enable specific features for the Sentry Messenger listener. It controls whether soft fails are captured and if breadcrumbs/context are isolated per message. ```yaml # config/packages/sentry.yaml sentry: messenger: capture_soft_fails: true # report errors even if message will retry isolate_breadcrumbs_by_message: true isolate_context_by_message: true ``` -------------------------------- ### Add Sentry Developer Metrics Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Use the metrics API to increment counters, record distributions, set gauges, and add to sets. Metrics are automatically sent to Sentry at the end of a request. ```php use function Sentry\metrics; // Add 4 to a counter named hits metrics()->increment(key: 'hits', value: 4); // Add 25 to a distribution named response_time with unit milliseconds metrics()->distribution(key: 'response_time', value: 25, unit: MetricsUnit::millisecond()); // Add 2 to gauge named parallel_requests, tagged with type: "a" metrics()->gauge(key: 'parallel_requests', value: 2, tags: ['type': 'a']); // Add a user's email to a set named users.sessions, tagged with role: "admin" metrics()->set('users.sessions', 'jane.doe@example.com', null, ['role' => User::admin()]); ``` -------------------------------- ### Log Messages to Sentry via Monolog Source: https://context7.com/getsentry/sentry-symfony/llms.txt Use the standard Monolog logger interface in your services to send log messages to Sentry. Messages at or above the configured level (e.g., WARNING) will be captured. ```php // Usage in a service — logs at WARNING and above are forwarded to Sentry: use Psr\Log\LoggerInterface; class OrderService { public function __construct(private readonly LoggerInterface $logger) {} public function cancel(int $orderId): void { // This will be sent to Sentry as a structured log entry $this->logger->warning('Order cancellation requested', [ 'order_id' => $orderId, 'reason' => 'customer_request', ]); } } // Expected: Sentry receives a log entry at level "warning" with context data ``` -------------------------------- ### Update class_serializers configuration Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-4.0.md The `sentry.options.class_serializers` configuration option now expects an array of strings, where each string is the container service name without the '@' prefix. Previously, it accepted scalar values or service names prefixed with '@'. ```yaml sentry: options: class_serializers: App\FooClass: '@app.sentry.foo_class_serializer' ``` ```yaml sentry: options: class_serializers: App\FooClass: 'App\Sentry\FooClassSerializer::__invoke' ``` ```yaml sentry: options: class_serializers: App\FooClass: ['App\Sentry\FooClassSerializer', 'invoke'] ``` ```yaml sentry: options: class_serializers: App\FooClass: 'app.sentry.foo_class_serializer' ``` -------------------------------- ### Manually Configure Request Scope in PHP Source: https://context7.com/getsentry/sentry-symfony/llms.txt This snippet shows how to manually configure the Sentry scope for a request to add tags and extra data. This is useful for adding request-specific context like tenant or route information. ```php use Sentry\SentrySdk; use Sentry\State\Scope; $hub = SentrySdk::getCurrentHub(); $hub->configureScope(function (Scope $scope): void { $scope->setTag('tenant', 'acme-corp'); $scope->setTag('route', 'api_order_create'); $scope->setExtra('request_id', 'req_abc123'); }); ``` -------------------------------- ### Manually Capture Exception in Console Command Source: https://context7.com/getsentry/sentry-symfony/llms.txt This PHP code shows how to manually capture an exception within a Symfony console command's execute method. It ensures that errors are reported to Sentry and provides user feedback. ```php use Sentry\SentrySdk; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ImportOrdersCommand extends Command { protected function execute(InputInterface $input, OutputInterface $output): int { try { $this->importService->run(); } catch (\Throwable $e) { \Sentry\captureException($e); $output->writeln('Import failed: ' . $e->getMessage() . ''); return Command::FAILURE; } return Command::SUCCESS; } } ``` -------------------------------- ### Configure Ignored Exceptions in sentry.yaml Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-5.0.md Update your `config/packages/sentry.yaml` to ignore specific exceptions, such as `Symfony\Component\ErrorHandler\Error\FatalError` and `Symfony\Component\Debug\Exception\FatalErrorException`, by using the `ignore_exceptions` option. This option performs an `is_a` check, allowing for more generic exception ignoring. ```yaml sentry: options: ignore_exceptions: - 'Symfony\Component\ErrorHandler\Error\FatalError' - 'Symfony\Component\Debug\Exception\FatalErrorException' ``` -------------------------------- ### Enable Cache Tracing in Sentry Source: https://context7.com/getsentry/sentry-symfony/llms.txt Configure Sentry to automatically trace Symfony Cache operations. When enabled, cache adapters are decorated to wrap PSR-6 operations in Sentry spans. ```php // All Symfony Cache operations are traced automatically. // Example showing what spans are generated: use Symfony\Contracts\Cache\CacheInterface; use Symfony\Contracts\Cache\ItemInterface; class ProductService { public function __construct(private readonly CacheInterface $cache) {} public function getProduct(int $id): array { // On cache MISS → generates: cache.get span (cache.hit=false) + cache.put span // On cache HIT → generates: cache.get span (cache.hit=true) return $this->cache->get("product_{$id}", function (ItemInterface $item): array { $item->expiresAfter(3600); return $this->fetchFromDatabase($id); }); } } // Span data example: // op="cache.get", description="product_42", data={cache.hit: false, cache.item_size: 248} // op="cache.put", description="product_42", data={cache.item_size: 248} ``` -------------------------------- ### Capture Exceptions Manually Source: https://context7.com/getsentry/sentry-symfony/llms.txt Use the global `captureException()` helper to report exceptions that Symfony would not catch automatically. You can also capture messages with severity or add extra context using `withScope`. ```php use function Sentry\captureException; use function Sentry\captureMessage; use function Sentry\withScope; use Sentry\Severity; use Sentry\State\Scope; // Basic exception capture try { $payment->charge($amount); } catch (PaymentGatewayException $e) { captureException($e); // handle gracefully } // Capture a plain message with severity captureMessage('Payment gateway degraded', Severity::warning()); // Capture with extra context using a local scope withScope(function (Scope $scope): void { $scope->setTag('payment.provider', 'stripe'); $scope->setExtra('order_id', 42); $scope->setUser(['id' => 99, 'email' => 'user@example.com']); captureException(new \RuntimeException('Charge failed')); }); ``` -------------------------------- ### Change Sentry Listener Priority with CompilerPass Source: https://github.com/getsentry/sentry-symfony/blob/master/UPGRADE-4.0.md This compiler pass demonstrates how to programmatically change the priority of Sentry event listeners, specifically for the Kernel Request event, after the removal of the `sentry.listener_priorities` configuration option. ```php use Sentry\SentryBundle\EventListener\RequestListener; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\KernelEvents; final class ChangeSentryListenerPriorityPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $definition = $container->getDefinition(RequestListener::class); $definitionTags = $definition->getTags(); foreach ($definitionTags['kernel.event_listener'] as &$tags) { if (KernelEvents::REQUEST === $tags['event']) { $tags['priority'] = 10; } } $definition->setTags($definitionTags); } } ``` -------------------------------- ### Embed Sentry Trace Propagation Meta Tags in Twig Source: https://context7.com/getsentry/sentry-symfony/llms.txt Use the `sentry_trace_meta()` and `sentry_baggage_meta()` Twig functions to render `` tags for frontend distributed tracing. These tags help propagate trace information from the browser to backend services. ```twig {# templates/base.html.twig #} {{ sentry_trace_meta() }} {{ sentry_baggage_meta() }} {# Renders: #} ``` -------------------------------- ### Isolate Sentry Context in Persistent Workers Source: https://context7.com/getsentry/sentry-symfony/llms.txt Use `SentrySdk::startContext()` and `SentrySdk::endContext()` to manually manage Sentry's context in long-running processes, preventing data leakage between operations. For Messenger workers, consider `isolate_context_by_message: true` in `sentry.yaml`. ```php use Sentry\SentrySdk; SentrySdk::startContext(); try { processJob($job); } finally { SentrySdk::endContext(); } ``` -------------------------------- ### Add Custom Child Spans to Sentry Transactions Source: https://context7.com/getsentry/sentry-symfony/llms.txt Manually add custom child spans within an existing Sentry transaction to capture specific operations like database queries. Ensure the span is finished and the hub's span is reset. ```php use Sentry\SentrySdk; use Sentry\Tracing\SpanContext; $hub = SentrySdk::getCurrentHub(); $parentSpan = $hub->getSpan(); if (null !== $parentSpan) { $spanContext = SpanContext::make() ->setOp('db.query') ->setDescription('SELECT * FROM orders WHERE status = ?'); $childSpan = $parentSpan->startChild($spanContext); $hub->setSpan($childSpan); try { $results = $this->orderRepository->findPending(); } finally { $childSpan->finish(); $hub->setSpan($parentSpan); } } // Expected: "db.query" span nested under the "http.server" transaction ``` -------------------------------- ### Handler that Fails in Symfony Messenger Source: https://context7.com/getsentry/sentry-symfony/llms.txt This PHP code defines a Symfony Messenger message handler that intentionally throws an exception. The Sentry MessengerListener will automatically capture this exception, tagging it with relevant messenger details. ```php use Symfony\Component\Messenger\Attribute\AsMessageHandler; #[AsMessageHandler] final class SendEmailHandler { public function __invoke(SendEmailMessage $message): void { // If this throws, MessengerListener will capture it with tags: // messenger.receiver_name, messenger.message_class, messenger.message_bus throw new \RuntimeException('SMTP server unreachable'); } } ``` -------------------------------- ### Isolate Breadcrumbs by Message in Symfony Source: https://github.com/getsentry/sentry-symfony/blob/master/CHANGELOG.md Configure Sentry to reset breadcrumbs between Symfony Messenger messages by setting `messenger.isolate_breadcrumbs_by_message` to true. ```yaml sentry: messenger: isolate_breadcrumbs_by_message: true ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.