PHP code example of cascata / hyperf-opentelemetry

1. Go to this page and download the library: Download cascata/hyperf-opentelemetry 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/ */

    

cascata / hyperf-opentelemetry example snippets


return [
    'http' => [
        \Cascata\HyperfOpenTelemetry\Middleware\CorrelationIdMiddleware::class,
        \Cascata\HyperfOpenTelemetry\Middleware\TracingMiddleware::class,
        // ... your other middlewares
    ],
];

use Cascata\HyperfOpenTelemetry\Logging\OtelLogHandler;
use Cascata\HyperfOpenTelemetry\Logging\OtelTraceContextProcessor;
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

return [
    'default' => [
        'handlers' => [
            [
                'class' => StreamHandler::class,
                'constructor' => [
                    'stream' => BASE_PATH . '/runtime/logs/hyperf.log',
                    'level'  => Logger::DEBUG,
                ],
                'formatter' => [
                    'class' => JsonFormatter::class,
                    'constructor' => [],
                ],
            ],
            [
                'class' => OtelLogHandler::class,
                'constructor' => [
                    'level' => Logger::INFO,
                ],
            ],
        ],
        'processors' => [
            ['class' => OtelTraceContextProcessor::class],
        ],
    ],
];

use Cascata\HyperfOpenTelemetry\Tracing\Annotation\Traced;

class CreateUser
{
    #[Traced(name: 'usecase.user.create')]
    public function execute(CreateUserInput $input): CreateUserOutput
    {
        // automatic span: usecase.user.create
    }
}

#[Traced(name: 'mq.welcome.publish', kind: 'producer')]    // PRODUCER (publish)
#[Traced(name: 'mq.welcome.consume', kind: 'consumer')]    // CONSUMER (read)
#[Traced(name: 'http.payment.charge', kind: 'client')]     // CLIENT (outbound)
#[Traced(name: 'usecase.foo')]                             // INTERNAL (default)

use OpenTelemetry\API\Globals;

$meter   = Globals::meterProvider()->getMeter('my-service.business');
$counter = $meter->createCounter('orders_created_total');
$counter->add(1, ['tenant' => $tenantId]);
bash
# Publish opentelemetry.php to config/autoload/
php bin/hyperf.php vendor:publish cascata/hyperf-opentelemetry --id=config

# Publish Tempo + Prometheus + Loki + Grafana + OTel Collector docker stack
php bin/hyperf.php vendor:publish cascata/hyperf-opentelemetry --id=observability-stack
dotenv
OTEL_LOG_LEVEL=debug
OTEL_PHP_INTERNAL_LOG_LEVEL=debug
bash
rm -rf runtime/container && php bin/hyperf.php start