PHPackages                             pekopt/yii2-sentry - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. pekopt/yii2-sentry

ActiveYii2-extension[Logging &amp; Monitoring](/categories/logging)

pekopt/yii2-sentry
==================

Sentry integration for Yii2 framework with performance monitoring and error tracking

v1.0.2(6mo ago)193—0%MITPHPPHP &gt;=7.4

Since Nov 4Pushed 6mo agoCompare

[ Source](https://github.com/PekopT/yii2-sentry)[ Packagist](https://packagist.org/packages/pekopt/yii2-sentry)[ RSS](/packages/pekopt-yii2-sentry/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (4)Versions (5)Used By (0)

Yii2 Sentry
===========

[](#yii2-sentry)

[![Latest Stable Version](https://camo.githubusercontent.com/844989ff8e9c257cf53de9c82f85831e73b979139e4b9302bc56bacd2fc00efb/687474703a2f2f706f7365722e707567782e6f72672f70656b6f70742f796969322d73656e7472792f76)](https://packagist.org/packages/pekopt/yii2-sentry)[![License](https://camo.githubusercontent.com/fcf2863995bb63ab4c7f6d4ea4deddeac5af7db0055becdf5e5a136e0e629c2b/687474703a2f2f706f7365722e707567782e6f72672f70656b6f70742f796969322d73656e7472792f6c6963656e7365)](https://packagist.org/packages/pekopt/yii2-sentry) [![PHP Version Require](https://camo.githubusercontent.com/5e45547e80357642f662e9db524c95fbb811e880c2ff7e9b8bde454ec0549de5/687474703a2f2f706f7365722e707567782e6f72672f70656b6f70742f796969322d73656e7472792f726571756972652f706870)](https://packagist.org/packages/pekopt/yii2-sentry)

*Read this in other languages: [English](README.md), [Русский](README.ru.md)*

Complete [Sentry](https://sentry.io) integration for Yii2 framework: logging, tracing and profiling.

Features
--------

[](#features)

- Tracking errors and exceptions through Yii2 logs
- Database performance monitoring (slow queries, transactions)
- HTTP request tracing (incoming and outgoing)
- Manual spans for tracking performance of critical operations
- Flexible data collection configuration through collector system
- Sanitization of sensitive data (passwords, tokens, API keys)

Installation
------------

[](#installation)

Install the package via composer:

```
composer require pekopt/yii2-sentry
```

For using performance profiling features, you need to install the PHP [Excimer extension](https://github.com/wikimedia/mediawiki-php-excimer).

Configuration
-------------

[](#configuration)

### Basic Configuration

[](#basic-configuration)

Add to your application configuration (not `common`):

```
'bootstrap' => ['sentry'],
'log'          => [
    'logger'  => 'pekopt\yii2sentry\Logger',
]
'components' => [
    'sentry' => [
        'class' => 'pekopt\yii2sentry\SentryComponent',
        'dsn' => 'https://your-sentry-dsn@sentry.io/project',
        'environment' => YII_ENV,
        // Sampling rate (percentage of requests for performance metrics collection)
        'tracesSampleRatePercent' => YII_ENV_PROD ? 5 : 100,
        // Additional tags for all events
        'tags' => [
            'application' => 'app-api',
            'app_version' => '1.0.0',
        ],
    ],
]
```

Built-in Collectors
-------------------

[](#built-in-collectors)

The package includes four main collectors, each responsible for its own monitoring area:

### 1. LogCollector

[](#1-logcollector)

Collects and sends Yii2 logs with error and warning levels to Sentry. Allows configuring which logs should be sent and which should be ignored.

### 2. DbCollector

[](#2-dbcollector)

Tracks SQL queries, measures their performance, and creates spans in Sentry for analysis. Automatically marks slow queries. Also tracks database transactions.

### 3. HttpClientCollector

[](#3-httpclientcollector)

Tracks outgoing HTTP requests made through Yii2 HttpClient. Measures response time, records response status, and creates spans for visualizing HTTP dependencies.

### 4. RequestCollector

[](#4-requestcollector)

Tracks incoming HTTP requests to your application. Creates the main transaction for each request and collects information about the controller, action, processing time, and response status.

Usage
-----

[](#usage)

### Manual Spans for Custom Operations

[](#manual-spans-for-custom-operations)

To create spans manually, use the `trace` method:

```
// Simple span
Yii::$app->sentry->trace('Operation name', function() {
    // Your code here
    heavyOperation();
});

// With additional data
Yii::$app->sentry->trace(
    'Data import',
    function() {
        // Import data
        return $result;
    },
    'custom.import', // Operation type
    [
        'source' => 'api',
        'records_count' => $count
    ]
);

// Span with exception handling
try {
    Yii::$app->sentry->trace('Critical operation', function() {
        // In case of an exception, the span will be marked as failed
        throw new \Exception('Error!');
    });
} catch (\Exception $e) {
    // The exception will be caught here
    // The span is already marked as failed in Sentry
}
```

### Collector Configuration

[](#collector-configuration)

You can configure each collector separately through the `collectorsConfig` parameter:

```
'sentry' => [
    'class' => 'pekopt\yii2sentry\SentryComponent',
    'dsn' => env('SENTRY_DSN', ''),
    'environment' => YII_ENV,
    'tracesSampleRatePercent' => YII_ENV_PROD ? 20 : 100,
    'collectorsConfig' => [
        // LogCollector configuration
        'logCollector' => [
            'targetOptions' => [
                'levels' => ['error', 'warning'], // Log levels to send
                'except' => ['yii\web\HttpException:404'], // Exceptions
                'exceptMessages' => [
                    '/^Informational message/' => true, // Exclude by pattern
                ],
            ],
        ],

        // DbCollector configuration
        'dbCollector' => [
            'slowQueryThreshold' => 100, // Threshold in ms for slow queries
        ],

        // HttpClientCollector with sensitive URL masking
        'httpClientCollector' => [
            'urlMaskPatterns' => [
                '|https://api\.telegram\.org/bot([^/]+)/|' => 'https://api.telegram.org/bot[HIDDEN]/',
            ],
        ],

        // RequestCollector configuration
        'requestCollector' => [
            'captureUser' => true, // Capture user ID
        ],
    ],
]
```

### Disabling Collectors

[](#disabling-collectors)

To disable a specific collector, set its configuration to `false`:

```
'collectorsConfig' => [
    'dbCollector' => false, // Disables the database collector
    'httpClientCollector' => false, // Disables the HTTP client collector
],
```

How Collectors Work
-------------------

[](#how-collectors-work)

### LogCollector

[](#logcollector)

Connects a special LogTarget that intercepts logs with specified levels and sends them to Sentry. Processes exceptions as a separate type of event. Also supports filtering by categories and message patterns.

### DbCollector

[](#dbcollector)

Overrides the standard Yii2 DbCommand and connects to query profiling events. Measures the execution time of each SQL query, determines the query type (SELECT, INSERT, etc.), and creates spans for visualization in Sentry. Tracks transactions through Connection events.

### HttpClientCollector

[](#httpclientcollector)

Subscribes to request sending events through HttpClient. For each request, it creates a span with details of URL, method, headers, and request body (with sanitization of sensitive data). Measures response time and adds information about the response status.

### RequestCollector

[](#requestcollector)

Creates the main transaction for each incoming HTTP request. Collects information about the route, controller, action, request parameters, and response. Measures the total request processing time and peak memory usage.

Creating a Custom Collector
---------------------------

[](#creating-a-custom-collector)

You can create your own collector by implementing the `CollectorInterface` or extending the `BaseCollector` class:

```
namespace app\components\sentry;

use pekopt\yii2sentry\collectors\BaseCollector;
use pekopt\yii2sentry\SentryComponent;
use Sentry\Breadcrumb;
use Sentry\State\Scope;
use Yii;

class MyCustomCollector extends BaseCollector
{
    // Collector configuration
    public $someOption = 'default';

    /**
     * Attaches the collector to Sentry
     */
    public function attach(SentryComponent $sentryComponent): bool
    {
        parent::attach($sentryComponent);

        // Connect to Yii2 events
        \yii\base\Event::on(SomeClass::class, SomeClass::EVENT_NAME, function($event) {
            $this->handleEvent($event);
        });

        return true;
    }

    /**
     * Sets additional tags
     */
    public function setTags(Scope $scope): void
    {
        $scope->setTag('custom_tag', 'value');
    }

    /**
     * Handles a custom event
     */
    protected function handleEvent($event)
    {
        // Create a span for tracking
        $span = $this->sentryComponent->startSpan(
            'My Custom Operation',
            'custom.operation',
            [
                'key' => 'value',
                'event_type' => get_class($event)
            ]
        );

        // Add a breadcrumb to the timeline
        $this->addBreadcrumb(
            'My Event Happened',
            ['data' => 'value'],
            Breadcrumb::LEVEL_INFO,
            'custom'
        );

        // Finish the span
        if ($span) {
            $this->sentryComponent->finishSpan($span, [
                'result' => 'success',
                'additional_data' => $someValue
            ]);
        }
    }
}
```

Then add your collector to the configuration:

```
'sentry' => [
    // ...
    'collectorsConfig' => [
        'myCustomCollector' => [
            'class' => 'app\components\sentry\MyCustomCollector',
            'someOption' => 'custom value',
        ],
    ],
],
```

### Contributing

[](#contributing)

If you found a bug or have suggestions for improvement, feel free to:

- Create an issue with a description of the problem or suggestion
- Propose pull requests with fixes or new features

License
-------

[](#license)

MIT

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance68

Regular maintenance activity

Popularity14

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity38

Early-stage or recently created project

 Bus Factor1

Top contributor holds 58.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

3

Last Release

187d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f227d1efc0ee19e02bfc00560e9a271ff75e671c301e3ada052cdff858e76920?d=identicon)[PekopT](/maintainers/PekopT)

---

Top Contributors

[![tzabzlat](https://avatars.githubusercontent.com/u/19708426?v=4)](https://github.com/tzabzlat "tzabzlat (10 commits)")[![PekopT](https://avatars.githubusercontent.com/u/1135374?v=4)](https://github.com/PekopT "PekopT (7 commits)")

---

Tags

monitoringapmsentryyii2error-tracking

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/pekopt-yii2-sentry/health.svg)

```
[![Health](https://phpackages.com/badges/pekopt-yii2-sentry/health.svg)](https://phpackages.com/packages/pekopt-yii2-sentry)
```

###  Alternatives

[mito/yii2-sentry

Yii 2 extension for Sentry

92377.7k](/packages/mito-yii2-sentry)[lordsimal/cakephp-sentry

Sentry plugin for CakePHP

12270.3k](/packages/lordsimal-cakephp-sentry)[e96/yii2-sentry

A Yii2 client for Sentry (http://getsentry.com)

2960.4k](/packages/e96-yii2-sentry)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
