php -vcomposer -v
index.php
is an HTTP Server using PDO to connect to a MySQL database for database operations. Set up the corresponding MySQL service yourself or purchase cloud services directly.mkdir <project-name> && cd <project-name>composer init \\--no-interaction \\--stability beta \\--require slim/slim:"^4" \\--require slim/psr7:"^1"composer update
index.php
file in the <project-name> directory and add the following content.<?php use Psr\\Http\\Message\\ResponseInterface as Response; use Psr\\Http\\Message\\ServerRequestInterface as Request; use Slim\\Factory\\AppFactory; require __DIR__ . '/vendor/autoload.php'; $app = AppFactory::create(); $app->get('/getID', function (Request $request, Response $response) { $dbms = 'mysql'; // Database type $host = 'localhost'; // Database hostname $dbName = 'Mydb'; // Database in use $user = 'root'; // Database connection username $pass = ''; // Corresponding password $dsn = "$dbms:host=$host;dbname=$dbName"; try { $dbh = new PDO($dsn, $user, $pass); // Initialize a PDO object echo "Connection successful<br/>"; foreach ($dbh->query('SELECT id from userInfo') as $row) { $response->getBody()->write($row[0] . "<br/>"); } $dbh = null; } catch (PDOException $e) { die ("Error!: " . $e->getMessage() . "<br/>"); } return $response; }); $app->run();
brew install gcc make autoconf
sudo apt-get install gcc make autoconf
pecl install opentelemetry
Build process completed successfullyInstalling '/opt/homebrew/Cellar/php/8.2.8/pecl/2020829/opentelemetry.so'install ok: channel://pecl.php.net/opentelemetry-1.0.3Extension opentelemetry enabled in php.ini
Extension opentelemetry enabled in php.ini
is output in the previous step, it is enabled. Skip this step.php.ini
file:[opentelemetry]extension=opentelemetry.so
php.ini
file locations may include:OS | PATH |
Linux | /etc/php.ini
/usr/bin/php5/bin/php.ini
/etc/php/php.ini
/etc/php5/apache2/php.ini |
Mac OSX | /private/etc/php.ini |
Windows (with XAMPP installed) | C:/xampp/php/php.ini |
php -m | grep opentelemetry
opentelemetry
php --ri opentelemetry
opentelemetryopentelemetry support => enabledextension version => 1.0.3
pecl install grpc # This step takes a long time to build.composer require \\ open-telemetry/sdk \\ open-telemetry/exporter-otlp \\ open-telemetry/transport-grpc \\php-http/guzzle7-adapter \\open-telemetry/opentelemetry-auto-slim \\open-telemetry/opentelemetry-auto-pdo
open-telemetry/opentelemetry-auto-slim
and open-telemetry/opentelemetry-auto-pdo
are imported because the example demo uses the PDO and Slim frameworks. You can adjust according to your specific business needs. If your business components require OpenTelemetry automatic event tracking, you need to import the corresponding automatic event tracking packets into the project. For detailed import methods, see OpenTelemetry official documentation.env OTEL_PHP_AUTOLOAD_ENABLED=true \\OTEL_TRACES_EXPORTER=otlp \\OTEL_METRICS_EXPORTER=none \\OTEL_LOGS_EXPORTER=none \\OTEL_EXPORTER_OTLP_PROTOCOL=grpc \\OTEL_EXPORTER_OTLP_ENDPOINT=<endpoint> \\ # Replace with the access point obtained in Step 1.OTEL_RESOURCE_ATTRIBUTES="service.name=<service-name>,token=<token>" \\ # Replace <service-name> with your custom service name and <token> with the token obtained in Step 1.OTEL_PROPAGATORS=baggage,tracecontext \\php -S localhost:8080
http://localhost:8080/getID
https://localhost:8080/getID
. If there is normal traffic, the integrated application will be displayed in APM > Application monitoring > Application list, and the integrated application instances will be displayed in APM > Application monitoring > Application details > Instance monitoring. Since there is a certain delay in processing observable data, if the application or instance is not found in the console after integration, please wait about 30 seconds.<?php use OpenTelemetry\\API\\Globals; // Required packet require __DIR__ . '/vendor/autoload.php'; function wait(): void { // Obtain the currently configured providers through the Globals packet.$tracerProvider = Globals::tracerProvider(); $tracer = $tracerProvider->getTracer( 'instrumentation-scope-name', //name (required) 'instrumentation-scope-version', //version 'http://example.com/my-schema', //schema url ['foo' => 'bar'] //attributes );// Custom Event Tracking $span = $tracer->spanBuilder("wait")->startSpan();// Business code.null sleep(5);null// Custom event tracking ends.$span->end(); } wait();
composer require guzzlehttp/guzzle
composer require \\open-telemetry/sdk \\open-telemetry/exporter-otlp
pecl install grpc # Skip this step if gRPC has already been downloaded.composer require open-telemetry/transport-grpc
opentelemetry_util.php
file in the directory where the index.php
file is located and add the following code to the file:<?php// Includes setting application name, Trace export method, Trace reporting access point, and creates a global TraceProvider.use OpenTelemetry\\API\\Globals;use OpenTelemetry\\API\\Trace\\Propagation\\TraceContextPropagator;use OpenTelemetry\\Contrib\\Otlp\\SpanExporter;use OpenTelemetry\\SDK\\Common\\Attribute\\Attributes;use OpenTelemetry\\SDK\\Common\\Export\\Stream\\StreamTransportFactory;use OpenTelemetry\\SDK\\Resource\\ResourceInfo;use OpenTelemetry\\SDK\\Resource\\ResourceInfoFactory;use OpenTelemetry\\SDK\\Sdk;use OpenTelemetry\\SDK\\Trace\\Sampler\\AlwaysOnSampler;use OpenTelemetry\\SDK\\Trace\\Sampler\\ParentBased;use OpenTelemetry\\SDK\\Trace\\SpanProcessor\\SimpleSpanProcessor;use OpenTelemetry\\SDK\\Trace\\SpanProcessor\\BatchSpanProcessorBuilder;use OpenTelemetry\\SDK\\Trace\\TracerProvider;use OpenTelemetry\\SemConv\\ResourceAttributes;use OpenTelemetry\\Contrib\\Grpc\\GrpcTransportFactory;use OpenTelemetry\\Contrib\\Otlp\\OtlpUtil;use OpenTelemetry\\API\\Signals;// OpenTelemetry initialization configuration (OpenTelemetry initialization configuration needs to be done when the PHP application initializes)function initOpenTelemetry(){// 1. Set OpenTelemetry resource information.$resource = ResourceInfoFactory::emptyResource()->merge(ResourceInfo::create(Attributes::create([ResourceAttributes::SERVICE_NAME => '<your-service-name>', // Application name, required, e.g., php-opentelemetry-demo.ResourceAttributes::HOST_NAME => '<your-host-name>' // hostname, optional.'token' => '<your-token>' // Replace with the token obtained in step 1.])));// 2. Create a SpanExplorer to output spans to the console.// $spanExporter = new SpanExporter(// (new StreamTransportFactory())->create('php://stdout', 'application/json')// );// 2. Create a SpanExplorer to report spans via gRPC.$transport = (new GrpcTransportFactory())->create('<grpc-endpoint>' . OtlpUtil::method(Signals::TRACE)); # Replace with the access point information obtained in step 1.$spanExporter = new SpanExporter($transport);// 3. Create a global TraceProvider to create a tracer.$tracerProvider = TracerProvider::builder()->addSpanProcessor((new BatchSpanProcessorBuilder($spanExporter))->build())->setResource($resource)->setSampler(new ParentBased(new AlwaysOnSampler()))->build();Sdk::builder()->setTracerProvider($tracerProvider)->setPropagator(TraceContextPropagator::getInstance())->setAutoShutdown(true) // Automatically shut down the tracerProvider after the PHP program exits to ensure all linkage data is reported.->buildAndRegisterGlobal(); // Add the tracerProvider to the global.}?>
index.php
file:<?phpuse OpenTelemetry\\API\\Globals; use OpenTelemetry\\API\\Trace\\StatusCode; use OpenTelemetry\\API\\Trace\\SpanKind; use OpenTelemetry\\SDK\\Common\\Attribute\\Attributes; use OpenTelemetry\\SDK\\Trace\\TracerProvider; use Psr\\Http\\Message\\ResponseInterface as Response; use Psr\\Http\\Message\\ServerRequestInterface as Request; use Slim\\Factory\\AppFactory;require __DIR__ . '/opentelemetry_util.php';
initOpenTelemetry
method to complete initialization. OpenTelemetry initialization configuration needs to be done when the PHP application initializes:// OpenTelemetry initialization, including setting the application name, trace export method, trace reporting access point and creating a global TraceProvider.initOpenTelemetry();
rolldice
API./*** 1. API feature: Simulate rolling a dice, returning a random integer between 1 and 6.* Demonstrate how to create a span, set attributes, events, and events with attributes.*/$app->get('/rolldice', function (Request $request, Response $response) {// Obtain tracer.$tracer = \\OpenTelemetry\\API\\Globals::tracerProvider()->getTracer('my-tracer');// Create span; set span kind; default is KIND_INTERNAL if not set.$span = $tracer->spanBuilder("/rolldice")->setSpanKind(SpanKind::KIND_SERVER)->startSpan();// Set attributes for span.$span->setAttribute("http.method", "GET");// Set events for span.$span->addEvent("Init");// Set events with attributes.$eventAttributes = Attributes::create(["key1" => "value","key2" => 3.14159,]);// Business code.$result = random_int(1,6);$response->getBody()->write(strval($result));$span->addEvent("End");// Terminate span.$span->end();return $response;});
rolltwodices
API to simulate rolling two dice, returning two random positive integers between 1 and 6. The following code demonstrates how to create nested spans:$app->get('/rolltwodices', function (Request $request, Response $response) {// Obtain tracer.$tracer = \\OpenTelemetry\\API\\Globals::tracerProvider()->getTracer('my-tracer');// Create span.$parentSpan = $tracer->spanBuilder("/rolltwodices/parent")->setSpanKind(SpanKind::KIND_SERVER)->startSpan();$scope = $parentSpan->activate();$value1 = random_int(1,6);$childSpan = $tracer->spanBuilder("/rolltwodices/parent/child")->startSpan();// Business code.$value2 = random_int(1,6);$result = "dice1: " . $value1 . ", dice2: " . $value2;// Terminate span.$childSpan->end();$parentSpan->end();$scope->detach();$response->getBody()->write(strval($result));return $response;});
error
API to simulate an API exception. The following code demonstrates how to use span to record the status when an exception occurs in the code:$app->get('/error', function (Request $request, Response $response) {// Obtain tracer.$tracer = \\OpenTelemetry\\API\\Globals::tracerProvider()->getTracer('my-tracer');// Create span.$span3 = $tracer->spanBuilder("/error")->setSpanKind(SpanKind::KIND_SERVER)->startSpan();try {// Simulate code exception.throw new \\Exception('exception!');} catch (\\Throwable $t) {// Set span status to error.$span3->setStatus(\\OpenTelemetry\\API\\Trace\\StatusCode::STATUS_ERROR, "expcetion in span3!");// Record exception stack track.$span3->recordException($t, ['exception.escaped' => true]);} finally {$span3->end();$response->getBody()->write("error");return $response;}});
php -S localhost:8080
http://localhost:8080/rolldicehttp://localhost:8080/rolltwodiceshttp://localhost:8080/error
https://localhost:8080/getID
. If there is normal traffic, the integrated application will be displayed in APM > Application monitoring > Application list, and the integrated application instances will be displayed in APM > Application monitoring > Application details > Instance monitoring. Since there is a certain delay in processing observable data, if the application or instance is not found in the console after integration, please wait about 30 seconds.
Was this page helpful?