Code Monkey home page Code Monkey logo

sentry-php-client's Introduction

Объектная реализация Sentry клиента

Поддерживает:

  • установку тегов
  • установку пользователя/клиента затронутого проблемой
  • добавление breadcrumbs - событий, которые привели к проблеме
  • захват и передачу в Sentry исключения или сообщения
  • включение/отключение автоматичекой обработки ошибок
  • 2 способа транспортировки: http и fluentd/td-agent

Несмотря на объектный подход, инициализация нескольких одновременных Sentry клиентов недопустима.

Диаграмма классов клиентов Sentry:

classDiagram
direction BT
class SentryAbstract
class SentryFluentd
class SentryHttp
class SentryInterface
SentryAbstract  ..>  SentryInterface
SentryFluentd  -->  SentryAbstract
SentryHttp  -->  SentryAbstract

Транспортировка событий в Sentry

Доступно 2 вида транспортировки событий:

  • через HTTP - стандартный способ (поддерживается из коробки sentry/sdk):
use Leads\Sentry\Implementations\SentryHttp;
use Leads\Sentry\Entities\IntegrationsOptions;

$dsn = '';
$environment = 'production';
$release = '[email protected]';

$sentryClient = new SentryHttp(
    $dsn,
    new IntegrationsOptions(),
    $environment,
    $release,
);
  • через fluentd/td-agent - реализован через пакет fluent/logger в данном проекте как более быстрое для клиентского кода и более устойчивое для сервера Sentry в одном инстансе:
use Fluent\Logger\FluentLogger;
use Leads\Sentry\Implementations\SentryHttp;
use Leads\Sentry\Entities\IntegrationsOptions;

$dsn = '';
$environment = 'production';
$release = '[email protected]';
$fluentHost = 'unix:///var/run/td-agent/fluentd.sock';
$fluentPort = '24224';

$sentryClient = new SentryFluentd(
    $dsn,
    new IntegrationsOptions(),
    new FluentLogger($fluentHost, $fluentPort),
    $environment,
    $release
);

Реализация Sentry клиента SentryFluentd отправляет fluentd запись с тегом sentry.store.{project_id}.{sentry_key} где:

  • project_id - идентификатор проекта в Sentry
  • sentry_key - авторизационный ключ (часть DSN)

Узел fluentd, который осуществляет отправку события в Sentry должен использовать store endpoint, например так (localhost:9000 - адрес сервера Sentry):

<match sentry.store.**>
  @type http
  @log_level debug
  
  endpoint http://localhost:9000/api/${tag[2]}/${tag[1]}/?sentry_version=7&sentry_client=td-agent&sentry_key=${tag[3]}
  open_timeout 2
  http_method post
  content_type application/json

  <buffer tag>
    @type file
    path /var/log/td-agent/sentry.store.buffer
    retry_forever true
    flush_mode immediate
    chunk_limit_size 32MB
    retry_type periodic
    retry_wait 10s
    retry_randomize true
    compress text
  </buffer>
</match>

Для fluentd >=1.12.1 можно использовать авторизацию через заголовки запроса.

Способы обработки ошибок

Так как этот код оборачивает sentry/sdk, то ему также присущи 2 способа обработки ошибок:

try {
  //...
} catch (\Throwable $e) {
  $sentryClient->captureException($e);
}

Включение или отключение производится через объект класса IntegrationsOptions при иницилазиции Sentry клиента:

use Leads\Sentry\Implementations\SentryHttp;
use Leads\Sentry\Entities\IntegrationsOptions;

$dsn = '';
$environment = 'production';
$release = '[email protected]';

$intOptions = new IntegrationsOptions();
$intOptions->setAutoHandler(true);

$sentryClient = new SentryHttp(
    $dsn,
    new IntegrationsOptions(),
    $environment,
    $release,
);

При автоматической обработке ошибок средствами Sentry клиента необходимо инициализировать этого клиента как можно раньше в коде приложения!

Дополнительные функции

Установить тег:

$sentryClient->setTag('tagName', 'tagValue');

Отправить сообщение:

$sentryClient->captureMessage('', Leads\Sentry\Entities\SeverityLevel::ERROR);

Установить пользователя получившего ошибку:

use Leads\Sentry\Entities\User;

$userId = 4687;
$userName = 'username';
$sentryClient->setUser(
    new User($id, $name)
);

Установить хлебные крошки:

use Leads\Sentry\Entities\Breadcrumb;
use Leads\Sentry\Entities\SeverityLevel;

$metadata = [
    'key' => 'value',
];

$sentryClient->addBreadcrumb(
    new Breadcrumb(
        SeverityLevel::INFO,
        'category',
        'message',
        $metadata
    )
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.