Sentry PHP SDK

repository·master·Indexed 23 days ago

https://github.com/getsentry/sentry-php

An error reporter for PHP applications that tracks exceptions and errors. It provides tools for manual exception capturing via captureException(), message reporting, and distributed tracing using transactions and spans. The SDK includes official integrations for Symfony and Laravel, as well as support for Monolog via ExceptionToSentryIssueHandler and LogToSentryIssueHandler. It features a Hub and Scope system for managing contextual data such as tags, user information, breadcrumbs, and feature flags.

Tokens
4.7K
Snippets
8
Records
37
Agent score
84%

What's inside sentry-php

  1. Available Sentry integrations

    master

    Sentry provides several integrations for popular PHP frameworks and CMS platforms:

    Official Integrations (Maintained by Sentry)

    • Symfony
    • Laravel

    3rd Party Integrations (SDK 4.x)

    • Drupal
    • WordPress
    • Magento 2 (via JustBetter or Mygento)
    • Joomla!
    • Neos Flow / Neos CMS
    • TYPO3

    Legacy Integrations

    • SDK 3.x: ZendFramework, Yii2, Silverstripe, CakePHP 3.0 - 4.3, October CMS
    • SDK 2.x: OXID eShop, CakePHP
    • SDK 1.x: OpenCart, TYPO3
  2. Quickstart with the Sentry Static API

    master

    The preferred way to use the Sentry PHP SDK is through the Static API (global functions). This approach handles the initialization of global exception/error handlers automatically. Use ext{Sentry} extbackslash ext{init}() to set up the SDK and ext{Sentry} extbackslash ext{configureScope}() to manage contextual data like tags, user information, and extra data.

    \Sentry\init(['dsn' => '___PUBLIC_DSN___' ]);
    
    \Sentry\configureScope(function (\Sentry\State\Scope $scope): void {
         $scope->setTag('page_locale', 'de-at');
         $scope->setUser(['email' => 'john.doe@example.com']);
         $scope->setLevel(\Sentry\Severity::warning());
         $scope->setExtra('character_name', 'Mighty Fighter');
    });
    
    // The following capture call will contain the data from the previous configured Scope
    try {
        thisFunctionThrows(); // -> throw new \Exception('foo bar');
    } catch (\Exception $exception) {
        \Sentry\captureException($exception);
    }
    
    \Sentry\addBreadcrumb(new Breadcrumb(Breadcrumb::LEVEL_ERROR, Breadcrumb::TYPE_ERROR, 'error_reporting', 'Message'));
  3. Set User, Tag, and Extra Context in version 2.0+

    master

    Methods like user_context, tags_context, and extra_context have been removed from the client. You should now use the current active Scope via the Hub to set this data.

    use Sentry\State\Hub;
    use Sentry\State\Scope;
    
    Hub::getCurrent()->configureScope(function (Scope $scope): void {
        $scope->setUser(['email' => 'foo@example.com']);
        $scope->setTag('tag_name', 'tag_value');
        $scope->setExtra('extra_key', 'extra_value');
    });
  4. Configure Client Serializers using ClientBuilder

    master

    Instead of calling setSerializer or setReprSerializer directly on a client instance, use the ClientBuilder to configure these dependencies during client creation.

    use Sentry\ClientBuilder;
    
    $clientBuilder = ClientBuilder::create();
    $clientBuilder->setSerializer(...);
    $clientBuilder->setRepresentationSerializer(...);
  5. Access and modify Client Options via Hub

    master

    In version 2.0+, many methods previously available on the Raven_Client (like getRelease, setEnvironment, getPrefixes, etc.) have been moved to the Options class. To access these, you must retrieve the options from the current Hub.

    use Sentry\State\Hub;
    
    $options = Hub::getCurrent()->getClient()->getOptions();
    
    $options->getRelease();
    $options->setRelease(...);
    $options->getEnvironment();
    $options->setEnvironment(...);
    $options->getPrefixes();
    $options->setPrefixes(...);
    $options->getProjectRoot();
    $options->setProjectRoot(...);
    $options->getInAppExcludedPaths();
    $options->setInAppExcludedPaths(...);
    $options->getBeforeSendCallback();
    $options->setBeforeSendCallback(...);
    $options->getDsn();
  6. Configure the Sentry PHP SDK

    master

    To begin reporting errors, initialize the SDK as early as possible in your application lifecycle using the ext{Sentry}\\init method. You must provide your project's DSN (Data Source Name) in the configuration array.

    \Sentry\init(['dsn' => '___PUBLIC_DSN___' ]);
  7. Use the Span class for distributed tracing

    master

    The Sentry\Tracing\Span class represents a single unit of work within a distributed trace. It allows you to capture metadata, tags, and status information for specific operations. You can create new spans, start child spans to build a hierarchy, and finish them to record the duration of the work.

    Key capabilities include:

    • Hierarchy: Use startChild() to create a child span that automatically inherits the parent's traceId and sampled decision.
    • Metadata: Attach arbitrary data via setData(), tags via setTags(), and feature flags via setFlag().
    • Status: Set the completion status using setStatus() or automatically via setHttpStatus().
    • Propagation: Generate trace headers using toTraceparent() for Sentry-specific propagation or toBaggage() for transaction context.
  8. Manage scope with pushScope, popScope, and withScope

    master

    Sentry uses a stack of scopes to manage contextual data (like tags, user info, or breadcrumbs). This allows you to isolate context for specific parts of your execution.

    • pushScope(): Scope: Clones the current scope and pushes it onto the stack. All subsequent captures will use this new scope until it is popped.
    • popScope(): bool: Removes the topmost scope from the stack.
    • withScope(callable $callback): A helper that pushes a new scope, executes the provided callback, and automatically pops the scope when the callback finishes (even if an exception is thrown). This is the recommended way to handle temporary context.
    • configureScope(callable $callback): void: Applies changes directly to the current topmost scope.
  9. Configure exception and transaction ignoring

    master

    The Client uses patterns defined in your Options to decide whether to discard certain exceptions or transactions.

    • Exceptions: Supports class hierarchy matching (e.g., passing a class name) or regex patterns. Regex patterns must be enclosed in forward slashes (e.g., /^My\Exception$/).
    • Transactions: Supports exact string matching or regex patterns (e.g., /^\/api\/v1\/.*/).

    If an exception or transaction matches an ignore pattern, the Client will log the discard action and return null instead of sending the event.

  10. Manage contextual data with Scope

    master
    The Scope class holds data that should implicitly be sent with Sentry events. This includes tags, user information, breadcrumbs, extra data, and context. You can use a scope to enrich events with metadata that helps in debugging, such as the current user's ID or specific feature flags.
  11. Capture exceptions with captureException()

    master

    To manually report an exception to Sentry, catch the exception in a try-catch block and pass the exception object to \text{Sentry}\\captureException().

    try {
        thisFunctionThrows(); // -> throw new \Exception('foo bar');
    } catch (\Exception $exception) {
        \Sentry\captureException($exception);
    }