ttrss/classes/tracer.php

81 lines
2.2 KiB
PHP
Raw Normal View History

2023-04-09 17:50:33 +00:00
<?php
2023-10-20 14:12:29 +00:00
use OpenTelemetry\Contrib\Otlp\OtlpHttpTransportFactory;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter;
2023-04-09 17:50:33 +00:00
class Tracer {
/** @var Tracer $instance */
2023-04-09 17:50:33 +00:00
private static $instance;
2023-10-20 14:12:29 +00:00
private static $tracer;
2023-04-09 17:50:33 +00:00
public function __construct() {
2023-10-20 14:12:29 +00:00
$opentelemetry_host = Config::get(Config::OPENTELEMETRY_HOST);
if ($opentelemetry_host) {
$transport = (new OtlpHttpTransportFactory())->create("http://$opentelemetry_host/v1/traces", 'application/x-protobuf');
$exporter = new SpanExporter($transport);
} else {
$exporter = new InMemoryExporter();
}
2023-10-20 14:12:29 +00:00
$tracerProvider = new TracerProvider(new SimpleSpanProcessor($exporter));
$this->tracer = $tracerProvider->getTracer('io.opentelemetry.contrib.php');
$context = TraceContextPropagator::getInstance()->extract(getallheaders());
$span = $this->tracer->spanBuilder(Config::get(Config::OPENTELEMETRY_SERVICE))
->setParent($context)
->startSpan();
$span->activate();
register_shutdown_function(function() use ($span, $tracerProvider) {
$span->end();
$tracerProvider->shutdown();
});
2023-04-09 17:50:33 +00:00
}
/**
* @param string $name
2023-04-09 18:37:17 +00:00
* @param array<string>|array<string, array<string, mixed>> $tags
* @param array<string> $args
2023-10-20 14:12:29 +00:00
* @return Span
*/
2023-10-20 14:12:29 +00:00
private function _start(string $name, array $tags = [], array $args = []) {
$span = $this->tracer->spanBuilder($name)->startSpan();
foreach ($tags as $k => $v) {
$span->setAttribute($k, $v);
}
$span->setAttribute("func.args", json_encode($args));
2023-10-20 14:12:29 +00:00
$span->activate();
2023-10-20 14:12:29 +00:00
return $span;
2023-04-09 17:50:33 +00:00
}
/**
* @param string $name
2023-04-09 18:37:17 +00:00
* @param array<string>|array<string, array<string, mixed>> $tags
* @param array<string> $args
2023-10-20 14:12:29 +00:00
* @return Span
*/
2023-10-20 14:12:29 +00:00
public static function start(string $name, array $tags = [], array $args = []) {
2023-04-09 18:37:17 +00:00
return self::get_instance()->_start($name, $tags, $args);
2023-04-09 17:50:33 +00:00
}
public static function get_instance() : Tracer {
if (self::$instance == null)
self::$instance = new self();
return self::$instance;
}
}