### Database Instrumentation Example in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md An example of a `DatabaseInstrumentation` class in PHP that extends `AbstractHookInstrumentation`. It defines the target class (`EntityManager`) and method (`persist`), builds a span with relevant attributes, and adds events for the start and completion of the operation. ```php final class DatabaseInstrumentation extends AbstractHookInstrumentation { public function getClass(): string { return EntityManager::class; } public function getMethod(): string { return 'persist'; } protected function buildSpan(SpanBuilderInterface $spanBuilder): SpanInterface { return $spanBuilder ->setSpanKind(SpanKind::KIND_CLIENT) ->setAttribute('db.system', 'doctrine') ->setAttribute('db.operation', 'persist') ->startSpan(); } public function pre(): void { $this->initSpan(null); $this->span->addEvent('Entity persistence started'); } public function post(): void { $this->span->addEvent('Entity persistence completed'); $this->closeSpan($this->span); } } ``` -------------------------------- ### Start Development Environment with Docker Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/README.md This command starts the development environment, likely including services like Tempo and Grafana, for testing and trace visualization. It's part of the local development setup for the bundle. ```bash make up ``` -------------------------------- ### Start and Manage Test Environment Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/CONTRIBUTING.md These commands are used to manage the local development environment for testing. 'make up' starts the environment, 'make down' stops it, and 'make health' checks its status. ```bash make up make down make health ``` -------------------------------- ### Install Symfony OpenTelemetry Bundle via Composer Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/installation.md This command installs the Symfony OpenTelemetry Bundle using Composer, the dependency manager for PHP. Ensure Composer is installed and accessible in your environment. ```bash composer require macpaw/symfony-otel-bundle ``` -------------------------------- ### Span Naming Convention Examples in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md Illustrates recommended and discouraged span naming conventions in PHP, emphasizing the use of semantic conventions for clarity and consistency in tracing. ```php // Good examples 'http.request' 'database.query' 'cache.get' 'user.authentication' 'payment.processing' // Bad examples 'HTTP_REQUEST' 'DatabaseQuery' 'cache_get' 'userAuth' ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/CONTRIBUTING.md This snippet demonstrates how to clone the project repository and install its PHP dependencies using Composer. It's a crucial first step for setting up a local development environment. ```bash git clone https://github.com/macpaw/symfony-otel-bundle.git cd symfony-otel-bundle composer install ``` -------------------------------- ### Start and Check Docker Environment (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/docker.md Commands to initiate and verify the health of the Docker development environment. Requires `make` to be installed. ```bash make up make health ``` -------------------------------- ### Environment Management Commands (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md A collection of make commands for managing the development environment, including starting, stopping, restarting, and checking the status and health of services. ```bash make up # Start environment make down # Stop environment make restart # Restart all services make status # Check service status make health # Check service health ``` -------------------------------- ### Install OpenTelemetry PHP Extension Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/installation.md This command installs the OpenTelemetry PHP extension using PECL. This extension is a prerequisite for using OpenTelemetry with PHP applications. ```bash pecl install opentelemetry-1.0.0 ``` -------------------------------- ### Start Complete Test Environment (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Initiates the full Docker test environment, including the PHP application, Tempo, Grafana, and OpenTelemetry Collector. It also provides commands to check service health and view the test application. ```bash # Start the complete test environment make up # Check service health make health # View test application open http://localhost:8080 ``` -------------------------------- ### Bash: Docker Environment Setup and Trace Generation for Symfony OpenTelemetry Source: https://context7.com/macpaw/symfony-otel-bundle/llms.txt This bash script provides commands to set up and manage a Docker environment for testing the Symfony OpenTelemetry Bundle. It includes commands to start all services (application, Tempo, Grafana, OTel Collector), check service health, generate test traces via HTTP requests, and access Grafana for trace visualization. No specific dependencies are required beyond Docker and Make. ```bash # Start all services (PHP app, Tempo, Grafana, OTel Collector) make up # Check service health make health # Generate test traces curl http://localhost:8080/api/test curl http://localhost:8080/api/slow curl http://localhost:8080/api/nested # Open Grafana to view traces (admin/admin) make grafana # Navigate to: Explore → Tempo → Search for service: "symfony-otel-test" ``` -------------------------------- ### Simulate API Load Testing with cURL (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Examples of using cURL to send GET requests to specific API endpoints of the test application. These are used for load testing and simulating different scenarios like slow operations or errors. ```bash # Generate test load make load-test # Run specific load tests curl -X GET http://localhost:8080/api/test curl -X GET http://localhost:8080/api/slow curl -X GET http://localhost:8080/api/nested curl -X GET http://localhost:8080/api/error ``` -------------------------------- ### Example TraceQL Queries for Tempo (TraceQL) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/docker.md Illustrative TraceQL queries to retrieve specific traces from the Tempo backend, demonstrating filtering by service name, duration, status, and HTTP method. ```traceql # Find all traces from the Symfony service {service.name="symfony-otel-test"} # Find slow operations (>1 second) {service.name="symfony-otel-test" && duration>1s} # Find error traces {service.name="symfony-otel-test" && status=error} # Find traces with specific HTTP methods {service.name="symfony-otel-test" && http.method="GET"} ``` -------------------------------- ### Execute Load Tests (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Provides commands for running load tests on the application. It includes a basic make command and custom examples using Apache Bench (ab) and curl for generating HTTP requests. ```bash # Run basic load test make load-test # Custom load testing with Apache Bench ab -n 100 -c 10 http://localhost:8080/api/test # Custom load testing with curl for i in {1..50}; do curl -X GET http://localhost:8080/api/test & done wait ``` -------------------------------- ### Install Symfony OpenTelemetry Bundle (Bash) Source: https://context7.com/macpaw/symfony-otel-bundle/llms.txt Installs the main bundle via Composer and optionally the gRPC transport support. For gRPC, it also requires installing the 'grpc' PECL extension. ```bash # Install via Composer composer require macpaw/symfony-otel-bundle # For gRPC transport support (recommended for production) composer require open-telemetry/transport-grpc pecl install grpc ``` -------------------------------- ### TraceQL Queries for Tempo Data (SQL) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Examples of TraceQL queries used within Tempo (accessed via Grafana) to search for specific traces. These queries filter traces based on service name, duration, status, and HTTP method. ```sql # Find all traces for the test service {.service.name="symfony-otel-test"} # Find slow operations {.service.name="symfony-otel-test"} | duration > 1s # Find error traces {.service.name="symfony-otel-test"} | status = "error" # Find specific HTTP methods {.service.name="symfony-otel-test"} | .http.method="GET" ``` -------------------------------- ### Environment Management Commands (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md A set of bash commands for managing the test environment services. Includes starting ('up'), stopping ('down'), checking health ('health'), and status ('status') of services. ```bash make up # Start all services make down # Stop all services make health # Check service health make status # Show service status ``` -------------------------------- ### Common Workflow Commands (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Provides bash commands grouped by common workflows: Development (setup, test, clear, visualize), Debugging (health check, data status, reset), and Performance Testing (clear, load test, status check). ```bash #### Development make up # Start environment make test # Run tests make clear-data # Clear for clean testing make grafana # View results #### Debugging make health # Check services make data-status # Check trace data make clear-data # Clear and retest make reset-all # Complete reset if needed #### Performance Testing make clear-data # Start clean make load-test # Generate load make data-status # Check results ``` -------------------------------- ### Run All Tests (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Executes all defined tests for the Symfony OpenTelemetry Bundle using the 'make test' command. This command ensures comprehensive testing of the bundle's functionality. ```bash make test ``` -------------------------------- ### Check Service Status and Logs (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Offers commands to verify the status of running services and to view their logs. These are essential for debugging issues related to services not starting or not functioning correctly. ```bash # Check if services are running make status # Check Tempo logs make logs-tempo # Verify trace export curl http://localhost:3200/api/traces # View all logs make logs ``` -------------------------------- ### Create Custom Database Instrumentation (PHP) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md This PHP code defines a custom instrumentation for database operations, extending the AbstractInstrumentation class. It configures spans for client-kind database calls, sets attributes for 'db.system' and 'db.operation', and adds events for the start and completion of the operation. This custom instrumentation must be registered in the application's configuration. ```php setSpanKind(SpanKind::KIND_CLIENT) ->setAttribute('db.system', 'mysql') ->setAttribute('db.operation', 'query') ->startSpan(); } public function pre(): void { $this->initSpan(null); $this->span->addEvent('Database operation started'); } public function post(): void { $this->span->addEvent('Database operation completed'); $this->closeSpan($this->span); } } ``` -------------------------------- ### Configure Instrumentation with Middleware in YAML Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md This YAML configuration demonstrates how to set up a custom instrumentation for a service. It specifies the target class and method, and includes an array of middleware services to be applied, such as `CustomSpanMiddleware` and `LoggingSpanMiddleware`. ```yaml services: custom.instrumentation: class: Macpaw\SymfonyOtelBundle\Instrumentation\ClassHookInstrumentation arguments: $className: 'App\Service\CustomService' $methodName: 'process' $spanMiddlewares: - '@App\Middleware\CustomSpanMiddleware' - '@App\Middleware\LoggingSpanMiddleware' ``` -------------------------------- ### Service and Log Management Commands (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md A set of make commands for managing individual services like PHP, Tempo, and Grafana, as well as a general command to view all service logs. ```bash make php-restart # Restart PHP application make tempo-restart # Restart Tempo make grafana-restart # Restart Grafana make logs # View all logs ``` -------------------------------- ### TraceQL Queries for Grafana Source: https://context7.com/macpaw/symfony-otel-bundle/llms.txt Examples of TraceQL queries used within Grafana to inspect and filter distributed traces generated by the Symfony OpenTelemetry Bundle. These queries help in debugging and performance analysis. ```sql -- Find all traces for your service {.service.name="my-symfony-app"} -- Find slow operations (duration > 1 second) {.service.name="my-symfony-app"} | duration > 1s -- Find failed operations {.service.name="my-symfony-app"} | status = error -- Find specific HTTP endpoints {.service.name="my-symfony-app" && .http.route="/api/payment/process"} -- Find operations with specific attributes {.service.name="my-symfony-app" && .payment.status="failed"} -- Find slow database operations {.service.name="my-symfony-app" && .db.system="mysql"} | duration > 500ms -- Find traces by trace ID {.service.name="my-symfony-app" && .trace_id="abc123def456"} -- Complex query: slow payment operations with errors {.service.name="my-symfony-app" && .operation.type="payment"} | duration > 2s && status = error ``` -------------------------------- ### PHP Creating a Root Span with TraceService Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/otel_basics.md Demonstrates how to create a root span for a new trace using the TraceService in a Symfony application. It obtains a tracer, builds and starts a span, activates its scope, executes logic within a try-finally block, and ensures the span is ended. ```php use Macpaw\SymfonyOtelBundle\Service\TraceService; class MyController { public function __construct(private TraceService $traceService) {} public function myAction(): Response { $tracer = $this->traceService->getTracer('my-app'); $rootSpan = $tracer->spanBuilder('root.operation')->startSpan(); $scope = $rootSpan->activate(); try { // ... your logic ... } finally { $scope->detach(); $rootSpan->end(); } return new Response('OK'); } } ``` -------------------------------- ### Testing Execution Commands (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Bash commands for executing tests within the bundle. 'make test' runs all tests, while 'make load-test' generates test load. ```bash make test # Run all tests make load-test # Generate test load ``` -------------------------------- ### Enable Symfony OpenTelemetry Bundle in bundles.php Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/installation.md This PHP code snippet shows how to register the Symfony OpenTelemetry Bundle within your Symfony application's configuration file (`config/bundles.php`). It ensures the bundle is loaded on all environments. ```php ['all' => true], ]; ``` -------------------------------- ### Basic Cache Instrumentation with PHP Source: https://context7.com/macpaw/symfony-otel-bundle/llms.txt Implements basic instrumentation for cache operations (e.g., Redis GET). This class extends `AbstractInstrumentation` and defines pre/post methods to capture events and attributes before and after the cache access. It requires `InstrumentationRegistry`, `TracerInterface`, and `TextMapPropagatorInterface`. ```php setSpanKind(SpanKind::KIND_CLIENT) ->setAttribute('cache.system', 'redis') ->setAttribute('cache.operation', 'get') ->startSpan(); } public function pre(): void { $this->initSpan(null); $this->span->addEvent('Cache operation started'); $this->span->setAttribute('cache.key', 'user:profile:123'); } public function post(): void { $this->span->addEvent('Cache operation completed'); $this->span->setAttribute('cache.hit', true); $this->closeSpan($this->span); } } ``` -------------------------------- ### PHP Hook for Zero-Code Instrumentation on DemoClass::run Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/otel_basics.md Registers a pre-hook and post-hook for the 'run' method of DemoClass to automatically create and manage an OpenTelemetry span. The pre-hook starts the span, and the post-hook records exceptions and ends the span. Requires the OpenTelemetry PHP SDK. ```php use OpenTelemetry\Instrumentation; // Register a hook for DemoClass::run() Instrumentation::hook( class: DemoClass::class, function: 'run', pre: static function ($context, $args) { $tracer = \OpenTelemetry\API\Globals::tracerProvider() ->getTracer('demo'); $span = $tracer->spanBuilder('demo.run')->startSpan(); return ['context' => $context->withSpan($span)]; }, post: static function ($context, $args, $result, $exception) { $span = $context->getSpan(); if ($exception instanceof \Throwable) { $span->recordException($exception); $span->setStatus(OpenTelemetry\API\Trace\StatusCode::STATUS_ERROR); } $span->end(); } ); ``` -------------------------------- ### Configure gRPC Transport for OpenTelemetry Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/README.md This bash script demonstrates how to configure the OpenTelemetry exporter for gRPC transport. It includes installing the gRPC extension and setting the endpoint and protocol environment variables. Note that `pecl install grpc` can take a significant amount of time. ```bash # Install gRPC support composer require open-telemetry/transport-grpc pecl install grpc # may take a time to compile - 30-40 minutes # Configure gRPC endpoint OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317 OTEL_EXPORTER_OTLP_PROTOCOL=grpc ``` -------------------------------- ### Enable Debug Logging (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Demonstrates how to enable debug logging for the OpenTelemetry components by setting the OTEL_LOG_LEVEL environment variable. After setting the level, services need to be restarted, and logs should be checked. ```bash # Set debug log level export OTEL_LOG_LEVEL=debug # Restart services make restart # Check logs make logs ``` -------------------------------- ### Create Custom Spans with TraceService (PHP) Source: https://context7.com/macpaw/symfony-otel-bundle/llms.txt Demonstrates using the TraceService to create custom spans for a payment processing operation. It shows how to start, activate, add events, set status, and end spans, including error handling. ```php traceService->getTracer('payment-service'); $span = $tracer->spanBuilder('payment.process') ->setSpanKind(SpanKind::KIND_SERVER) ->setAttribute('payment.order_id', $orderId) ->setAttribute('payment.amount', $amount) ->setAttribute('payment.currency', 'USD') ->startSpan(); $scope = $span->activate(); try { $span->addEvent('Payment validation started'); // Simulate payment processing $validated = $this->validatePayment($orderId, $amount); if (!$validated) { $span->setStatus(StatusCode::STATUS_ERROR, 'Payment validation failed'); return new JsonResponse(['error' => 'Invalid payment'], 400); } $span->addEvent('Payment processed successfully'); $span->setStatus(StatusCode::STATUS_OK); return new JsonResponse([ 'status' => 'success', 'order_id' => $orderId, 'trace_id' => $span->getContext()->getTraceId(), ]); } catch (\Exception $e) { $span->recordException($e); $span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage()); throw $e; } finally { $scope->detach(); $span->end(); } } } ``` -------------------------------- ### Implement Error Handling for Spans in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md Demonstrates robust error handling within the `post` method of an OpenTelemetry instrumentation in PHP. It includes try-catch-finally blocks to record exceptions, set status to error, and ensure the span is closed properly. ```php public function post(): void { try { // Your post-execution logic $this->span->setStatus(StatusCode::STATUS_OK); } catch (Exception $e) { $this->span->recordException($e); $this->span->setStatus(StatusCode::STATUS_ERROR, $e->getMessage()); } finally { $this->closeSpan($this->span); } } ``` -------------------------------- ### Register Custom Database Instrumentation (YAML) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md This YAML configuration registers a custom instrumentation class within the Symfony OpenTelemetry Bundle. By listing the fully qualified class name under 'otel_bundle.instrumentations', the bundle can discover and utilize the custom instrumentation during its operation. ```yaml otel_bundle: instrumentations: - 'App\Instrumentation\CustomDatabaseInstrumentation' ``` -------------------------------- ### Create and Register Custom Instrumentation (PHP) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Defines a custom instrumentation class by extending AbstractHookInstrumentation. It specifies the name, class, and method to instrument, along with logic to build the span. This is a prerequisite for adding custom tracing to your application. ```php setSpanKind(SpanKind::KIND_SERVER) ->setAttribute('test.operation', 'test') ->startSpan(); } } ``` -------------------------------- ### Configure gRPC Transport for OpenTelemetry Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/installation.md This configuration enables the gRPC transport for OpenTelemetry, which is recommended for faster performance. It requires installing gRPC dependencies and configuring the collector endpoint, typically on port 4317. ```bash # Install gRPC dependencies composer require open-telemetry/transport-grpc # install PHP gRPC extension by pecl or compile from source pecl install grpc # Configure gRPC endpoint (usually 4317 port) OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317 OTEL_EXPORTER_OTLP_PROTOCOL=grpc ``` -------------------------------- ### Utilize TraceService for Tracing in PHP Services Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/otel_basics.md Demonstrates how to inject and use the `TraceService` within application services to obtain tracers and create spans for monitoring business logic. This example shows nested span creation for processing lists of items. Requires OpenTelemetry API and the bundle's TraceService. ```php traceService->getTracer('my-business-service'); $span = $tracer->spanBuilder('process_data') ->setAttribute('data.count', count($data)) ->startSpan(); $scope = $span->activate(); try { // Your business logic here foreach ($data as $item) { $this->processItem($item); } } finally { $scope->detach(); $span->end(); } } private function processItem($item): void { $tracer = $this->traceService->getTracer('my-business-service'); $span = $tracer->spanBuilder('process_item') ->setAttribute('item.id', $item['id'] ?? 'unknown') ->startSpan(); $scope = $span->activate(); try { // Process individual item } finally { $scope->detach(); $span->end(); } } } ``` -------------------------------- ### Clear Test Data (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Removes all collected trace data from the test environment using 'make clear-data'. This command is useful for starting fresh test runs. ```bash make clear-data ``` -------------------------------- ### Configure HTTP Transport for OpenTelemetry Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/installation.md This configuration sets up the OpenTelemetry exporter to use the HTTP transport protocol. It specifies the endpoint for the OTLP collector and the protocol itself. This is the default but slower option. ```bash OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf ``` -------------------------------- ### Configure OpenTelemetry Environment Variables Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/installation.md These environment variables are essential for configuring the OpenTelemetry exporter. They define the service name, tracer name, exporter endpoint, protocol, propagators, and sampler settings for your application. ```bash # OpenTelemetry Configuration OTEL_SERVICE_NAME=your-service-name OTEL_TRACER_NAME=your-tracer-name OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf OTEL_PROPAGATORS=tracecontext,baggage OTEL_TRACES_SAMPLER=always_on ``` -------------------------------- ### Create Feature Branch Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/CONTRIBUTING.md This command is used to create a new Git branch for developing a new feature. It follows a common convention for naming feature branches, starting with 'feature/' followed by a descriptive name. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Set Span Attributes in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md Provides examples of setting standard OpenTelemetry attributes for HTTP requests, database operations, and custom attributes in PHP. This helps in enriching trace data for better analysis. ```php // HTTP attributes $span->setAttribute('http.method', 'GET'); $span->setAttribute('http.route', '/api/users'); $span->setAttribute('http.status_code', 200); // Database attributes $span->setAttribute('db.system', 'mysql'); $span->setAttribute('db.operation', 'SELECT'); $span->setAttribute('db.table', 'users'); // Custom attributes $span->setAttribute('user.id', $userId); $span->setAttribute('operation.type', 'background_job'); ``` -------------------------------- ### Store and Retrieve Trace Context in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/otel_basics.md Demonstrates how to store the current trace context within a span and retrieve it. This is crucial for maintaining trace continuity across operations. It requires the OpenTelemetry Context and Tracer components. ```php use OpenTelemetry\Context\Context; $tracer = $this->traceService->getTracer('my-app'); $rootSpan = $tracer->spanBuilder('root')->startSpan(); $context = $rootSpan->storeInContext(Context::getCurrent()); ``` -------------------------------- ### Testing and Data Management Commands (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Provides essential make commands for running various types of tests, including all tests, PHPUnit tests, load tests, and tests with code coverage. It also includes commands for managing test data. ```bash make test # Run all tests make phpunit # Run PHPUnit tests make load-test # Generate test load make coverage # Run tests with coverage make clear-data # Clear all test data make clear-tempo # Clear Tempo data only make reset-all # Complete environment reset make data-status # Check data status ``` -------------------------------- ### Instrument HTTP Client Requests in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md This PHP code defines a class `HttpClientInstrumentation` that extends `AbstractHookInstrumentation` to automatically instrument HTTP client requests. It captures the HTTP method and URL, sets the span kind to client, and adds events for request start and completion. This requires the OpenTelemetry PHP SDK and Symfony's event system. ```php final class HttpClientInstrumentation extends AbstractHookInstrumentation { public function getClass(): string { return HttpClientInterface::class; } public function getMethod(): string { return 'request'; } protected function buildSpan(SpanBuilderInterface $spanBuilder): SpanInterface { return $spanBuilder ->setSpanKind(SpanKind::KIND_CLIENT) ->setAttribute('http.method', 'GET') ->setAttribute('http.url', $this->getUrl()) ->startSpan(); } public function pre(): void { $this->initSpan(null); $this->span->addEvent('HTTP request started'); } public function post(): void { $this->span->addEvent('HTTP request completed'); $this->closeSpan($this->span); } } ``` -------------------------------- ### Service Access Commands (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/testing.md Bash commands to easily access different services of the test environment, such as the Grafana dashboard and application logs. ```bash make grafana # Open Grafana dashboard make logs # View all logs make logs-php # View PHP application logs ``` -------------------------------- ### Symfony OpenTelemetry Bundle Configuration (YAML) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/docker.md Configuration snippet for the `otel_bundle` in Symfony, defining the tracer name, service name, enabled instrumentations, and custom header mappings. ```yaml otel_bundle: tracer_name: '%env(OTEL_TRACER_NAME)%' service_name: '%env(OTEL_SERVICE_NAME)%' instrumentations: - 'Macpaw\SymfonyOtelBundle\Instrumentation\RequestExecutionTimeInstrumentation' header_mappings: http.request_id: 'X-Request-Id' ``` -------------------------------- ### Add Custom Attributes to SpanBuilder in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/otel_basics.md Shows how to attach custom attributes to a span before it is started using the SpanBuilder. This is useful for adding metadata like IDs or status codes. ```php use Macpaw\SymfonyOtelBundle\Service\TraceService; class MyController { public function __construct(private TraceService $traceService) {} public function processOrder(): Response { $tracer = $this->traceService->getTracer('my-app'); $span = $tracer ->spanBuilder('order.process') ->setAttribute('order.id', '12345') ->setAttribute('user.authenticated', true) ->setAttribute('retry.count', 3) ->startSpan(); $scope = $span->activate(); try { // ... } finally { $scope->detach(); $span->end(); } return new Response('OK'); } } ``` -------------------------------- ### Create PDO Hook Instrumentation (PHP) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md This PHP code defines a hook instrumentation for the PDO class's 'query' method, extending AbstractHookInstrumentation. It automatically creates client-kind spans for SQL queries, setting 'db.system' and 'db.operation' attributes. The instrumentation includes pre and post methods to add events and manage the span lifecycle, enabling instrumentation of PDO without altering its source code. ```php setSpanKind(SpanKind::KIND_CLIENT) ->setAttribute('db.system', 'sql') ->setAttribute('db.operation', 'query') ->startSpan(); } public function pre(): void { $this->initSpan(null); // Access method arguments through context if needed $this->span->addEvent('PDO query started'); } public function post(): void { $this->span->addEvent('PDO query completed'); $this->closeSpan($this->span); } } ``` -------------------------------- ### Configure OTLP Transport Protocols (Bash) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/docker.md Configures the OpenTelemetry Protocol (OTLP) endpoint and protocol for exporting traces. Use HTTP for faster builds in development and gRPC for better performance in production. These are environment variables typically set in a .env file or directly in the shell. ```bash # HTTP Transport (faster builds) OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf # gRPC Transport (better performance) OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317 OTEL_EXPORTER_OTLP_PROTOCOL=grpc ``` -------------------------------- ### Configure Class Hook Instrumentation (YAML) Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md This configuration sets up instrumentation for specific class methods using the ClassHookInstrumentation. It allows for method-level instrumentation with support for custom middleware logic and automatic span lifecycle management. The class, method, and any associated middlewares need to be defined. ```yaml services: example.instrumentation: class: Macpaw\SymfonyOtelBundle\Instrumentation\ClassHookInstrumentation arguments: $className: 'App\Service\ExampleService' $methodName: 'process' $spanMiddlewares: - '@App\Middleware\CustomSpanMiddleware' ``` -------------------------------- ### Manage Scope and Activate Context in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/otel_basics.md Illustrates how to activate a span's context, making it the current active context, and how to manage this scope using `activate()` and `detach()`. This ensures that child spans correctly inherit their parent context. Uses OpenTelemetry API and Symfony services. ```php $tracer = $this->traceService->getTracer('my-app'); $rootSpan = $tracer->spanBuilder('root')->startSpan(); $scope = $rootSpan->activate(); try { // Within this scope, new spans inherit from $rootSpan $child = $tracer->spanBuilder('child')->startSpan(); $childScope = $child->activate(); try { // child operations } finally { $childScope->detach(); $child->end(); } } finally { $scope->detach(); // restore previous context $rootSpan->end(); } ``` -------------------------------- ### Access Grafana for Traces Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/CONTRIBUTING.md After running integration tests, this command provides access to Grafana, a tool used for visualizing traces. This is essential for debugging and understanding the flow of requests in the distributed system. ```bash make grafana ``` -------------------------------- ### Create Custom Span Middleware in PHP Source: https://github.com/macpaw/symfony-otel-bundle/blob/develop/docs/instrumentation.md This middleware allows adding custom logic to OpenTelemetry instrumentations by providing pre and post execution methods. It extends the `ClassHookInstrumentationSpanMiddlewareInterface` and utilizes `ClockInterface` for timing. ```php setAttribute('custom.class', $instrumentation->getClass()); $span->setAttribute('custom.method', $instrumentation->getMethod()); $span->setAttribute('custom.start_time', $instrumentation->getStartTime()); } public function post(SpanInterface $span, HookInstrumentationInterface&TimingInterface $instrumentation): void { $executionTime = $instrumentation->getExecutionTime(); $span->setAttribute('custom.execution_time_ns', $executionTime); $span->setAttribute('custom.end_time', $instrumentation->getEndTime()); } } ```