Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: use NoopTracerProvider if Sdk is disabled #55

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
"require-dev": {
"doctrine/dbal": "^3.0",
"friends-of-phpspec/phpspec-expect": "^4.0",
"open-telemetry/transport-grpc": "^1.0",
"open-telemetry/gen-otlp-protobuf": "^1.0",
"php-http/httplug": "^2.3",
"phpspec/phpspec": "^7.5",
Expand Down
40 changes: 24 additions & 16 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,31 @@
### Features

#### Tracing

- Using the official [OpenTelemetry SDK](https://github.com/open-telemetry/opentelemetry-php)
- Minimal auto-instrumentation for **requests**, console **commands**, **consumers** and **doctrine**
- Trace context propagation from incoming **requests** to **consumers**, **outgoing http calls** and **databases** (using [`sqlcommenter`](https://google.github.io/sqlcommenter/))
- Configurable blacklisting of requests by path to avoid useless traces, eg. `/metrics` or `/_healthz`
- Automatic log inclusion with configurable log level and channels
- Disabling tracing with the `NoopTracerProvider` thanks to OTEL_SDK_DISABLED=true
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't think it's worth mentioning here


#### Metrics

- Using the [Prometheus Client](https://github.com/PromPHP/prometheus_client_php)
- Minimal auto-instrumentation for common **request**, **consumer** and **message** metrics (see list of provided [default metrics](./docs/metrics/default-metrics.md)).
- Autoconfigurable metric providers, see below.

#### Logging

- Adds trace context to logs for correlation, with customizable keys.

#### Baggage

- Using the official [OpenTelemetry SDK](https://github.com/open-telemetry/opentelemetry-php)
- Baggage propagation from incoming **requests** to **consumers** and **outgoing http calls**

#### Health

- A simple endpoint to expose application health (default: `/_healthz`)
- Autoconfigurable healthcheck interface to add healthchecks to be made for global application health

Expand All @@ -30,19 +36,21 @@
```sh
composer require worldia/instrumentation-bundle <your-exporter>
```

You will aso need to install an [exporter implementation](https://packagist.org/packages/open-telemetry/exporter-otlp?query=open-telemetry%2Fexporter-) and `APCu` is required by the prometheus exporter.
```

````
GCalmels marked this conversation as resolved.
Show resolved Hide resolved

Add to ```bundles.php```:
```php
return [
// Other bundles
Instrumentation\InstrumentationBundle::class => ['all' => true],
];
```
````

**Minimal configuration**
See the complete [configuration reference here](./docs/config-reference.md) or run ```bin/console config:dump-reference instrumentation```.
**Minimal configuration**
See the complete [configuration reference here](./docs/config-reference.md) or run `bin/console config:dump-reference instrumentation`.

```yaml
// docker-compose.yaml
Expand Down Expand Up @@ -71,18 +79,18 @@ instrumentation: ~
### Usage

- **Tracing**
- [Simple tracing example](./docs/tracing/simple-trace.md)
- [Simple tracing example using the static API](./docs/tracing/static-usage.md)
- [Add Urls to your traces in error messages](./docs/tracing/add-urls-to-your-traces.md)
- [Use upstream request id as trace id](./docs/tracing/upstream-request-id.md)
- [Customize operation (span) name for a message](./docs/tracing/custom-operation-name-for-message.md)
- [Link strategy for a message](./docs/tracing/link-strategy-for-message.md)
- [Propagating trace/baggage context in HTTP requests](./docs/tracing/propagating-context.md)
- [Add request / response bodies as span attributes for HTTP requests](./docs/tracing/message-bodies.md)
- [Simple tracing example](./docs/tracing/simple-trace.md)
- [Simple tracing example using the static API](./docs/tracing/static-usage.md)
- [Add Urls to your traces in error messages](./docs/tracing/add-urls-to-your-traces.md)
- [Use upstream request id as trace id](./docs/tracing/upstream-request-id.md)
- [Customize operation (span) name for a message](./docs/tracing/custom-operation-name-for-message.md)
- [Link strategy for a message](./docs/tracing/link-strategy-for-message.md)
- [Propagating trace/baggage context in HTTP requests](./docs/tracing/propagating-context.md)
- [Add request / response bodies as span attributes for HTTP requests](./docs/tracing/message-bodies.md)
- **Metrics**
- [Adding a metric](./docs/metrics/adding-a-metric.md)
- [Using Redis as storage adapter](./docs/metrics/using-redis-as-storage.md) (Recommended)
- [Adding a metric](./docs/metrics/adding-a-metric.md)
- [Using Redis as storage adapter](./docs/metrics/using-redis-as-storage.md) (Recommended)
- **Logging**
- [Customizing trace context log keys](./docs/logging/custom-keys.md)
- [Customizing trace context log keys](./docs/logging/custom-keys.md)
- **Health**
- [Adding a healthcheck](./docs/health/adding-a-healthcheck.md)
- [Adding a healthcheck](./docs/health/adding-a-healthcheck.md)
40 changes: 21 additions & 19 deletions src/Bridge/GoogleCloud/Logging/Formatter/StdOutFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,30 +45,32 @@ protected function normalize(mixed $data, int $depth = 0): mixed
$data['severity'] = $data['level_name'];
unset($data['level_name']);

// Map tracing
if (isset($data['context']['trace'])) {
$data['logging.googleapis.com/trace'] = 'projects/'.$this->project.'/traces/'.$data['context']['trace'];
}
if (isset($data['context']['span'])) {
$data['logging.googleapis.com/spanId'] = $data['context']['span'];
}
if (isset($data['context']['sampled'])) {
$data['logging.googleapis.com/trace_sampled'] = $data['context']['sampled'];
}
if (isset($data['context']['operation'])) {
$data['logging.googleapis.com/operation'] = $data['context']['operation'];
if (\is_array($data['context'])) {
// Map tracing
if (isset($data['context']['trace'])) {
$data['logging.googleapis.com/trace'] = 'projects/'.$this->project.'/traces/'.$data['context']['trace'];
}
if (isset($data['context']['span'])) {
$data['logging.googleapis.com/spanId'] = $data['context']['span'];
}
if (isset($data['context']['sampled'])) {
$data['logging.googleapis.com/trace_sampled'] = $data['context']['sampled'];
}
if (isset($data['context']['operation'])) {
$data['logging.googleapis.com/operation'] = $data['context']['operation'];
}
unset($data['context']['trace'], $data['context']['span'], $data['context']['sampled'], $data['context']['operation']);

if ($exception = $data['context']['exception'] ?? false) {
$data['message'] = $exception['message'];
$data['context'] = array_merge($data['context'], $exception['context']);
unset($data['context']['exception']);
}
}
unset($data['context']['trace'], $data['context']['span'], $data['context']['sampled'], $data['context']['operation']);

// Map channel
$data['logging.googleapis.com/labels'] = ['channel' => $data['channel']];
unset($data['channel']);

if ($exception = $data['context']['exception'] ?? false) {
$data['message'] = $exception['message'];
$data['context'] = array_merge($data['context'], $exception['context']);
unset($data['context']['exception']);
}
}

return $data;
Expand Down
7 changes: 5 additions & 2 deletions src/Metrics/CounterAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

class CounterAdapter implements CounterInterface
{
use IterableAttributesTrait;

public function __construct(
private string $name,
private string $description,
Expand All @@ -20,11 +22,12 @@ public function __construct(
}

/**
* @param int $amount
* @param array{labels: array<string,mixed>} $attributes
* @param int $amount
* @param iterable<string,array<string,mixed>> $attributes
*/
public function add($amount, iterable $attributes = [], $context = null): void
{
$attributes = $this->normalizeAttributes($attributes);
/** @var array<string> $labelNames */
$labelNames = array_keys($attributes['labels'] ?? []);
$labelValues = array_values($attributes['labels'] ?? []);
Expand Down
3 changes: 3 additions & 0 deletions src/Metrics/HistogramAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

class HistogramAdapter implements HistogramInterface
{
use IterableAttributesTrait;

public function __construct(
private string $name,
private string $description,
Expand All @@ -25,6 +27,7 @@ public function __construct(
*/
public function record($amount, iterable $attributes = [], $context = null): void
{
$attributes = $this->normalizeAttributes($attributes);
/** @var array<string> $labelNames */
$labelNames = array_keys($attributes['labels'] ?? []);
$labelValues = array_values($attributes['labels'] ?? []);
Expand Down
26 changes: 26 additions & 0 deletions src/Metrics/IterableAttributesTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

/*
* This file is part of the worldia/instrumentation-bundle package.
* (c) Worldia <[email protected]>
*/

namespace Instrumentation\Metrics;

trait IterableAttributesTrait
{
/**
* @param iterable<string,array<string,mixed>> $attributes
*
* @return array<string,array<string,mixed>>
*/
public function normalizeAttributes(iterable $attributes): array
{
$newAttr = [];
foreach ($attributes as $key => $value) {
$newAttr[$key] = $value;
}

return $newAttr;
}
}
3 changes: 3 additions & 0 deletions src/Metrics/UpDownCounterAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@

class UpDownCounterAdapter implements UpDownCounterInterface
{
use IterableAttributesTrait;

public function __construct(
private string $name,
private string $description,
Expand All @@ -25,6 +27,7 @@ public function __construct(
*/
public function add($amount, iterable $attributes = [], $context = null): void
{
$attributes = $this->normalizeAttributes($attributes);
/** @var array<string> $labelNames */
$labelNames = array_keys($attributes['labels'] ?? []);
$labelValues = array_values($attributes['labels'] ?? []);
Expand Down
5 changes: 5 additions & 0 deletions src/Tracing/Tracing.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\TracerProviderInterface;
use OpenTelemetry\Context\Context;
use OpenTelemetry\SDK\Sdk;
use OpenTelemetry\SDK\Trace\NoopTracerProvider;

final class Tracing
{
Expand Down Expand Up @@ -46,6 +48,9 @@ public static function setProvider(TracerProviderInterface $tracerProvider): voi

private static function getProvider(): TracerProviderInterface
{
if (Sdk::isDisabled()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is not the right place to handle it because it will not handle a disabled SDK within Symfony, only for static usage.

Don't you think we should rather adapt the TracerProvider in Symfony itself?
Something by the lines of:

<?php

declare(strict_types=1);

/*
 * This file is part of the worldia/instrumentation-bundle package.
 * (c) Worldia <[email protected]>
 */

namespace Instrumentation\Tracing;

use OpenTelemetry\API\Trace\NoopTracer;
use OpenTelemetry\API\Trace\TracerInterface;
use OpenTelemetry\API\Trace\TracerProviderInterface;
use OpenTelemetry\SDK\Sdk;

class TogglableTracerProvider implements TracerProviderInterface
{
    public function __construct(private TracerProviderInterface $decorated)
    {
    }

    public function getTracer(string $name, string|null $version = null, string|null $schemaUrl = null, iterable $attributes = []): TracerInterface
    {
        if (Sdk::isDisabled()) {
            return new NoopTracer();
        }

        return $this->decorated->getTracer($name, $version, $schemaUrl, $attributes);
    }
}

With :

use Instrumentation\Tracing\TogglableTracerProvider;
use OpenTelemetry\API\Trace\TracerProviderInterface;

return static function (ContainerConfigurator $container) {
    $container->services()
        ->set(TogglableTracerProvider::class)
        ->decorate(TracerProviderInterface::class)
        ->args([
            service('.inner'),
        ])
    ;
};

WDYT?

return new NoopTracerProvider();
}
if (!self::$tracerProvider) {
throw new \RuntimeException('No trace provider was set.');
}
Expand Down
Loading