PHP code example of open-telemetry / context-swoole

1. Go to this page and download the library: Download open-telemetry/context-swoole 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/ */

    

open-telemetry / context-swoole example snippets




use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Instrumentation\Configurator;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\Context\Context;
use OpenTelemetry\Context\ContextStorage;
use OpenTelemetry\Contrib\Context\Swoole\SwooleContextStorage;
use OpenTelemetry\Contrib\Otlp\OtlpHttpTransportFactory;
use OpenTelemetry\Contrib\Otlp\SpanExporter;
use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor;
use OpenTelemetry\SDK\Trace\TracerProvider;
use Swoole\Http\Server;

nfigurator) => $configurator->withTracerProvider($tracerProvider));

// Create a Swoole HTTP server, which will start on local port 9501
$http = new Server('127.0.0.1', 9501);

// Http request callback
$http->on('request', function ($request, $response) {
    $tracer = Globals::tracerProvider()->getTracer('io.opentelemetry.contrib.swoole.php');

    try {
        $root = $tracer->spanBuilder($request->server['request_uri'])
            ->setSpanKind(SpanKind::KIND_SERVER)
            ->startSpan();
        $scope = $root->activate();

        for ($i = 0; $i < 3; $i++) {
            // start a span, register some events
            $span = $tracer->spanBuilder('loop-' . $i)->startSpan();

            $span
                ->setAttribute('remote_ip', '1.2.3.4')
                ->setAttribute('country', 'USA');

            $span->addEvent('found_login' . $i, [
                'id' => $i,
                'username' => 'otuser' . $i,
            ]);
            $span->addEvent('generated_session', [
                'id' => md5((string) microtime(true)),
            ]);

            $span->end();
        }
    } finally {
        $root->end();
        $scope->detach();
    }

    $response->header('Content-Type', 'text/plain');
    $response->end('Hello Swoole Context');
});

// Start server
$http->start();