PHP library for the OpenTracing's API.
In order to understand the library, one must first be familiar with the OpenTracing project and specification more specifically.
When consuming this library one really only need to worry
about a couple of key abstractions: the Tracer::startSpan
method, the Span
interface, and binding a Tracer
at bootstrap time. Here are code snippets
demonstrating some important use cases:
The simplest starting point is to set the global tracer. As early as possible, do:
use OpenTracing\GlobalTracer;
use OtherOpenTracingImplementation\Tracer;
GlobalTracer::setGlobalTracer(Tracer::create());
Note that the GlobalTracer
is a singleton itself but all the rest public methods are
static
so it can be perfectly injected on any DI approach.
To start a new Span
, you can use the StartSpanFromContext
method.
use Psr\Http\Message\RequestInterface;
...
$spanContext = GlobalTracer::globalTracer()->extract(
Propagator::HTTP_HEADERS,
HttpHeaders::withHeaders($request->getHeaders())
);
function doSomething(SpanContext $spanContext, ...) {
...
$span = GlobalTracer::globalTracer()->startSpan('operation_name', ChildOf::withContext($spanContext), null);
...
$span->logFields(
Log::asString('event', 'soft error'),
Log::asString('type', 'cache timeout'),
Log::asInt('waited.millis', 1500))
)
$span->finish();
}
It's always possible to create a "root" Span
with no parent or other causal
reference.
$span = $tracer->startSpan('operation_name');
...
$span->finish();
use OpenTracing\SpanReference\ChildOf;
function xyz(Span $parentSpan, ...) {
...
$span = GlobalTracer::globalTracer()->startSpan(
'operation_name',
ChildOf::withContext($span->context())
);
$span->finish();
...
}
use OpenTracing\Carriers\HttpHeaders as HttpHeadersCarrier;
use OpenTracing\Context;
use OpenTracing\GlobalTracer;
...
$tracer = GlobalTracer::globalTracer();
$spanContext = $tracer->extract(
Propagator::HTTP_HEADERS,
HttpHeaders::withHeaders($request->getHeaders())
);
try {
$span = $tracer->startSpan('operation_name', ChildOf::withContext($spanContext), null);
$client = new GuzzleHttp\Client;
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://myservice');
$tracer->inject(
$span->context(),
Propagator::HTTP_HEADERS,
HttpHeadersCarrier::withHeaders($request->getHeaders())
)
$client->send($request);
...
} catch (Exception $e) {
...
}
...