MediaWiki master
OtlpHttpExporter.php
Go to the documentation of this file.
1<?php
2namespace Wikimedia\Telemetry;
3
4use GuzzleHttp\Psr7\Utils;
5use Psr\Http\Client\ClientExceptionInterface;
6use Psr\Http\Client\ClientInterface;
7use Psr\Http\Message\RequestFactoryInterface;
8use Psr\Log\LoggerInterface;
9
17 private ClientInterface $client;
18 private RequestFactoryInterface $requestFactory;
19 private LoggerInterface $logger;
20
25 private string $endpoint;
26
31 private string $serviceName;
32
37 private string $hostName;
38
39 public function __construct(
40 ClientInterface $client,
41 RequestFactoryInterface $requestFactory,
42 LoggerInterface $logger,
43 string $uri,
44 string $serviceName,
45 string $hostName
46 ) {
47 $this->client = $client;
48 $this->requestFactory = $requestFactory;
49 $this->logger = $logger;
50 $this->endpoint = $uri;
51 $this->serviceName = $serviceName;
52 $this->hostName = $hostName;
53 }
54
56 public function export( TracerState $tracerState ): void {
57 $spanContexts = $tracerState->getSpanContexts();
58 if ( count( $spanContexts ) === 0 ) {
59 return;
60 }
61
62 $resourceInfo = array_filter( [
63 'service.name' => $this->serviceName,
64 'host.name' => $this->hostName,
65 "server.socket.address" => $_SERVER['SERVER_ADDR'] ?? null,
66 ] );
67
68 $data = [
69 'resourceSpans' => [
70 [
71 'resource' => [
72 'attributes' => OtlpSerializer::serializeKeyValuePairs( $resourceInfo )
73 ],
74 'scopeSpans' => [
75 [
76 'scope' => [
77 'name' => 'org.wikimedia.telemetry',
78 ],
79 'spans' => $spanContexts
80 ]
81 ]
82 ]
83 ]
84 ];
85
86 $request = $this->requestFactory->createRequest( 'POST', $this->endpoint )
87 ->withHeader( 'Content-Type', 'application/json' )
88 ->withBody( Utils::streamFor( json_encode( $data ) ) );
89
90 try {
91 $response = $this->client->sendRequest( $request );
92 if ( $response->getStatusCode() !== 200 ) {
93 $this->logger->error( 'Failed to export trace data' );
94 }
95 } catch ( ClientExceptionInterface $e ) {
96 $this->logger->error( 'Failed to connect to exporter', [ 'exception' => $e ] );
97 }
98
99 // Clear out finished spans after exporting them.
100 $tracerState->clearSpanContexts();
101 }
102}
An ExporterInterface that exports collected data over HTTP, serialized in OTLP JSON format.
export(TracerState $tracerState)
Export all trace data.void
__construct(ClientInterface $client, RequestFactoryInterface $requestFactory, LoggerInterface $logger, string $uri, string $serviceName, string $hostName)
static serializeKeyValuePairs(array $keyValuePairs)
Serialize an associative array into the format expected by the OTLP JSON format.
Holds shared telemetry state, such as finished span data buffered for export.
clearSpanContexts()
Clear the list of finished spans.
Base interface for OTEL trace data exporters.