Skip to content

Commit

Permalink
Merge pull request #1 from gluck1986/trace
Browse files Browse the repository at this point in the history
Trace
  • Loading branch information
gluck1986 committed Aug 21, 2022
2 parents 843a266 + 8cc13c8 commit 9e7bd9f
Show file tree
Hide file tree
Showing 27 changed files with 2,202 additions and 50 deletions.
155 changes: 133 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,37 +79,148 @@ return [
];
```

Then add `SentryMiddleware` to main application middleware set and configure DSN in `config/params.php`. Console errors
are captured by default, there is no need to configure anything.
if you want to trace guzzle requests and add sentry headers to external queries, add this

```php
GuzzleHttp\Client::class => static function (ContainerInterface $container) {
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$factory = $container->get(GuzzleMiddlewareFactory::class);
$middleware = static function (callable $handler) use ($factory): callable {
return $factory->factory($handler);
};

$stack->push($middleware);

return new GuzzleHttp\Client([
'handler' => $stack,
]);
},
```


**Configure:**

add code block below to your params.php
and type your DSN
also you can define your environment and release, for example TAG from gitlab.ci
```php
'yiisoft/yii-sentry' =>
[
'options' => [
'dsn' => '',
'environment' => 'local', //SENTRY_ENVIRONMENT, //YII_ENV,
'release' => 'dev', //SENTRY_RELEASE, //TAG
// @see: https://docs.sentry.io/platforms/php/configuration/options/#send-default-pii
'send_default_pii' => true,
'traces_sample_rate' => 1.0,
],
'handleConsoleErrors' => true,
'log_level' => 'warning',
'tracing' => [
// Indicates if the tracing integrations supplied by Sentry should be loaded
'default_integrations' => true,
],
]
```

add APP_START_TIME const into index.php and yii.php
```php
define('APP_START_TIME', microtime(true));
```

add log targets for breadcrumbs and tracing in app/config/common/logger.php
or another config file with logger settings

```php
return [
// ...
LoggerInterface::class => static function (
/** your_another_log_target $your_log_target */
\Yiisoft\Yii\Sentry\SentryBreadcrumbLogTarget $sentryLogTarget,
Yiisoft\Yii\Sentry\Tracing\SentryTraceLogTarget $sentryTraceLogTarget
) {
return new Logger([
/** $your_log_target */
$sentryLogTarget,
$sentryTraceLogTarget
]);
}
];
```
**if you want to see your logs in sentry timeline**, you need to use keys (float)'**time**' and (float)'**elapsed**' in log context array
_____

add DB log decorator for tracing db queries in app/config/params.php
```php
'yiisoft/yii-cycle' => [
// DBAL config
'dbal' => [
// SQL query logger. Definition of Psr\Log\LoggerInterface
// For example, \Yiisoft\Yii\Cycle\Logger\StdoutQueryLogger::class
'query-logger' => \Yiisoft\Yii\Sentry\DbLoggerDecorator::class,
/**
* ...
* your another db settings
**/
]
]
```

add into app/config/params.php into middleware section SetRequestIpMiddleware
```php
'middlewares' => [
ErrorCatcher::class,
SentryMiddleware::class, // <-- here
SessionMiddleware::class,
CookieMiddleware::class,
CookieLoginMiddleware::class,
LocaleMiddleware::class,
\Yiisoft\Yii\Sentry\Http\SetRequestIpMiddleware::class, //add this
Router::class,
],
// ...
'yiisoft/yii-sentry' => [
'handleConsoleErrors' => false, // Add to disable console errors.
'options' => [
// Set to `null` to disable error sending (note that in case of web application errors it only prevents
// sending them via HTTP). To disable interactions with Sentry SDK completely, remove middleware and the
// rest of the config.
'dsn' => $_ENV['SENTRY_DSN'] ?? null,
'environment' => $_ENV['YII_ENV'] ?? null, // Add to separate "production" / "staging" environment errors.
],
],
// ...
]
```

Note that fatal errors are handled too.
add into app/config/common/router.php tracing middleware
```php
RouteCollectionInterface::class => static function (RouteCollectorInterface $collector) use ($config) {
$collector
->middleware(FormatDataResponse::class)
->middleware(JsonParseMiddleware::class)
->middleware(ExceptionMiddleware::class)
->middleware(\Yiisoft\Yii\Sentry\Tracing\SentryTraceMiddleware::class) // add this
->addGroup(
Group::create('')
->routes(...$config->get('routes'))
);

return new RouteCollection($collector);
},
```

________




if your transaction too heavy you can slice it to several transactions with clearing log buffer.

use SentryConsoleTransactionAdapter or SentryWebTransactionAdapter

for example:

```php
/** some code with default transaction */
/** commit default transaction and send data to sentry server */
$sentryTraceString = $this->sentryTransactionAdapter->commit();
while ($currentDate <= $endDate) {
$this->sentryTransactionAdapter->begin($sentryTraceString)
->setName('my_heavy_operation/iteration')
->setData(['date' => $currentDate->format('Y-m-d')]);

$this->process($currentDate, $sentryTraceString);
$this->sentryTransactionAdapter->commit();
}
$this->sentryTransactionAdapter->begin($sentryTraceString)
->setName('my_heavy_operation done, terminating application');
/** transaction will commit when application is terminated */
```
for this example all new transactions will linked to transaction with $sentryTraceString


In `options` you can also pass additional Sentry configuration. See
[official Sentry docs](https://docs.sentry.io/platforms/php/configuration/options/) for keys and values.
Expand Down
16 changes: 11 additions & 5 deletions composer.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "yiisoft/yii-sentry",
"name": "gluck1986/yii-sentry",
"type": "library",
"description": "A Sentry integration for Yii Framework",
"keywords": [
Expand All @@ -20,11 +20,16 @@
"require": {
"php": "^8.0",
"psr/http-message": "^1.0",
"psr/http-server-middleware": "^1.0",
"psr/http-server-handler": "^1.0",
"psr/http-server-middleware": "^1.0",
"psr/log": "^2.0",
"sentry/sdk": "^3.2",
"symfony/console": "^5.4|^6.0",
"yiisoft/di": "^1.0",
"symfony/console": "^5.4|^6.0"
"yiisoft/log": "^2.0",
"yiisoft/router": "^1.1",
"yiisoft/router-fastroute": "^1.1",
"yiisoft/yii-http": "^1.0"
},
"require-dev": {
"guzzlehttp/guzzle": "^7.3",
Expand All @@ -33,10 +38,11 @@
"phpunit/phpunit": "^9.5",
"roave/infection-static-analysis-plugin": "^1.16",
"spatie/phpunit-watcher": "^1.23",
"squizlabs/php_codesniffer": "^3.7",
"vimeo/psalm": "^4.18",
"yiisoft/error-handler": "^2.1",
"yiisoft/yii-event": "^1.0",
"yiisoft/yii-console": "^1.0"
"yiisoft/yii-console": "^1.0",
"yiisoft/yii-event": "^1.0"
},
"suggest": {
"yiisoft/yii-console": "Add error catching to console application",
Expand Down
24 changes: 4 additions & 20 deletions config/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,11 @@
declare(strict_types=1);

use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Sentry\ClientBuilder;
use Sentry\Options;
use Sentry\SentrySdk;
use Sentry\State\HubInterface;
use Sentry\Transport\TransportFactoryInterface;
use Yiisoft\Yii\Sentry\HubBootstrapper;

return [
static function (ContainerInterface $container): void {
$options = $container->get(Options::class);

$clientBuilder = new ClientBuilder($options);
$clientBuilder
->setTransportFactory($container->get(TransportFactoryInterface::class))
->setLogger($container->get(LoggerInterface::class));

$client = $clientBuilder->getClient();

$hub = $container->get(HubInterface::class);
$hub->bindClient($client);

SentrySdk::setCurrentHub($hub);
static function (ContainerInterface $container) {
$bootstrapper = $container->get(HubBootstrapper::class);
$bootstrapper->bootstrap();
},
];
7 changes: 7 additions & 0 deletions config/common.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,18 @@
use Sentry\State\HubInterface;
use Sentry\Transport\DefaultTransportFactory;
use Sentry\Transport\TransportFactoryInterface;
use Yiisoft\Yii\Sentry\YiiSentryConfig;

/**
* @var $params array
*/

return [
YiiSentryConfig::class => [
'__construct()' => [
'config' => $params['yiisoft/yii-sentry'],
],
],
TransportFactoryInterface::class => DefaultTransportFactory::class,
HttpClientFactoryInterface::class => [
'class' => HttpClientFactory::class,
Expand All @@ -31,5 +37,6 @@
$params['yiisoft/yii-sentry']['options'],
],
],

HubInterface::class => Hub::class,
];
17 changes: 17 additions & 0 deletions config/events-console.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@

declare(strict_types=1);

use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Event\ConsoleTerminateEvent;
use Yiisoft\Yii\Console\Event\ApplicationShutdown;
use Yiisoft\Yii\Console\Event\ApplicationStartup;
use Yiisoft\Yii\Sentry\SentryConsoleHandler;
use Yiisoft\Yii\Sentry\Tracing\SentryTraceConsoleListener;

/**
* @var $params array
Expand All @@ -23,4 +28,16 @@
ConsoleErrorEvent::class => [
[SentryConsoleHandler::class, 'handle'],
],
ApplicationStartup::class => [
[SentryTraceConsoleListener::class, 'listenAppStart'],
],
ConsoleCommandEvent::class => [
[SentryTraceConsoleListener::class, 'listenBeginCommand'],
],
ConsoleTerminateEvent::class => [
[SentryTraceConsoleListener::class, 'listenCommandTerminate'],
],
ApplicationShutdown::class => [
[SentryTraceConsoleListener::class, 'listenShutdown'],
],
];
6 changes: 6 additions & 0 deletions docker-compose.override.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
version: '3.8'

services:
cli:
volumes:
- ./:/app
9 changes: 9 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
version: '3.8'

services:
cli:
build:
context: ./
dockerfile: ./docker/php/Dockerfile
target: php-cli
working_dir: /app
10 changes: 10 additions & 0 deletions docker/php/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM yiisoftware/yii-php:8.0-fpm AS php-build
RUN apt-get update -y && apt-get upgrade -y
RUN apt-get clean all

FROM php-build AS php-cli
COPY ./ /app
RUN composer install
ENTRYPOINT []


24 changes: 24 additions & 0 deletions phpcs.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?xml version="1.0"?>
<ruleset name="PHP_CodeSniffer">
<description>PHPCS configuration file.</description>
<exclude-pattern>/vendor/*</exclude-pattern>
<!--
APPROVED:
A file should declare new symbols (classes, functions, constants, etc.) and cause no other side effects,
or it should execute logic with side effects, but should not do both. The first symbol is defined on line 7
and the first side effect is on line 12. (PSR1.Files.SideEffects.FoundWithSymbols)
-->
<ini name="memory_limit" value="512M" />
<arg name="extensions" value="php"/>
<arg name="encoding" value="utf-8"/>
<arg name="parallel" value="4"/>
<arg name="colors"/>

<!-- Show progress of the run -->
<arg value="p"/>
<!-- Show sniff codes in all reports -->
<arg value="s"/>

<!-- Our base rule: set to PSR12-->
<rule ref="PSR12"/>
</ruleset>
2 changes: 1 addition & 1 deletion psalm.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0"?>
<psalm
errorLevel="2"
errorLevel="1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
Expand Down
Loading

0 comments on commit 9e7bd9f

Please sign in to comment.