PHP code example of penguin-seven / thinkphp-open-telemetry

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

    

penguin-seven / thinkphp-open-telemetry example snippets


return [
    'enabled' => env('OTEL_ENABLED', true),
    'endpoint' => env('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://localhost:4318'),
    'service_name' => env('OTEL_SERVICE_NAME', 'thinkphp-app'),
    // 可选:指定主机名,用于与 Infrastructure 监控关联。默认使用 php_uname('n')
    'host_name' => env('OTEL_RESOURCE_ATTRIBUTES_HOST_NAME', php_uname('n')),
];

return [
    // ...
    \tpOpenTelemetry\middleware\Telemetry::class,
];

return [
    // ...
    'listen' => [
        // ... 其他监听器
        
        // OpenTelemetry 队列追踪
        'think\queue\event\JobProcessing' => ['tpOpenTelemetry\middleware\TraceQueueListener'],
        'think\queue\event\JobProcessed'  => ['tpOpenTelemetry\middleware\TraceQueueListener'],
        'think\queue\event\JobFailed'     => ['tpOpenTelemetry\middleware\TraceQueueListener'],
    ],
];

use tpOpenTelemetry\service\OpenTelemetry;

$otel = app(OpenTelemetry::class);

// 开始一个 Span
$span = $otel->startSpan('my-custom-operation');

try {
    // 业务逻辑...
    $otel->log('INFO', 'Something happened');
} catch (\Exception $e) {
    // 记录异常
} finally {
    // 结束 Span
    $otel->endSpan($span);
}

   'host_name' => 'your-host-name', // 或者通过环境变量 OTEL_RESOURCE_ATTRIBUTES_HOST_NAME 注入