PHP code example of quinluong / tracing-php

1. Go to this page and download the library: Download quinluong/tracing-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

quinluong / tracing-php example snippets


use Tracing\TracerFactory;

// This instance will be saved in TracerFactory internally by tracer_name, we can use it later by TracerFactory::getByName
$tracer = TracerFactory::create('tracer_name', [
    'enable' => true,
    'host_port' => 'agent_host:port',
    'sampler_type' => 'const', // const, probabilistic
    'sampler_value' => 1 // const: 0 / 1, probabilistic: 0 -> 1
]);

use OpenTracing\Formats;

$spanOptions = [
    'tags' => [
        'tag_key_1' => 'tag_value_1',
        'tag_key_2' => 'tag_value_2'
    ]
];

// Extract and use it for next span
$spanContext = $tracer->extract(Formats\TEXT_MAP, getallheaders());

if ($spanContext !== null) {
    $spanOptions['child_of'] = $spanContext;
}

$tracer->startActiveSpan('operation_name', $spanOptions);

use OpenTracing\Formats;

$tracer->inject($span->getContext(), Formats\TEXT_MAP, $arrHeader);

// At dispatcher level
$scope = $tracer->startActiveSpan('request');
...
$scope->close();

// At controller level
$scope = $tracer->startActiveSpan('controller');
...
$scope->close();

// At RPC calls level
$scope = $tracer->startActiveSpan('http');
file_get_contents('http://php.net');
$scope->close();

$parent = $tracer->startActiveSpan('parent');
...
/*
 * Since the parent span has been created by using startActiveSpan we don't need
 * to pass a reference for this child span
 */
$child = $tracer->startActiveSpan('my_second_span');
...
$child->close();
...
$parent->close();

$parent = $tracer->startSpan('parent');
...
$child = $tracer->startSpan('child', [
    'child_of' => $parent
]);
...
$child->finish();
...
$parent->finish();

// Tags are searchable in UI
$span->setTag('http.status', '200');
$span->setTag('http.url', 'abc.com/api/endpoint');

$tracer->startActiveSpan('my_span', [
    'tags' => [
        'foo-1' => 'bar-1',
        'foo-2' => 'bar-2'
        ...
    ]
]);

// Log information
$span->log([
    'error' => 'HTTP request timeout'
    'event' => 'soft error',
    'type' => 'cache timeout',
    'waiter.millis' => 1500
    ...
]);

register_shutdown_function(function() {
    $tracer = TracerFactory::getByName('tracer_name');
    // Flush the tracer to the backend
    if ($tracer !== null) {
        $tracer->flush();
    }
});

$tracer->pause();
...
// This function won't be instrumented
doSomething();
...
$tracer->resume();
bash
composer