PHP code example of nadi-pro / nadi-php

1. Go to this page and download the library: Download nadi-pro/nadi-php 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/ */

    

nadi-pro / nadi-php example snippets


use Nadi\Transporter\OpenTelemetry;
use Nadi\Data\Entry;
use Nadi\Data\Type;

// Configure OpenTelemetry transporter
$transporter = new OpenTelemetry();
$transporter->configure([
    'endpoint' => 'http://localhost:4318',  // Use https:// in production
    'service_name' => 'my-php-app',
    'service_version' => '1.0.0',
]);

// Create an entry
$entry = Entry::make(Type::EXCEPTION, [
    'class' => 'RuntimeException',
    'message' => 'An error occurred',
    'file' => __FILE__,
    'line' => __LINE__,
]);

// Store and send
$transporter->store($entry->toArray());
$transporter->send();

use Nadi\Metric\System;

$system = new System();
$metrics = $system->toArray();

// Returns OTel-compliant metrics:
// - system.cpu.load_average.1m
// - system.cpu.load_average.5m
// - system.cpu.load_average.15m
// - system.cpu.logical_count
// - system.memory.usage
// - system.memory.limit
// - system.memory.peak
// - system.filesystem.usage
// - system.filesystem.available
// - system.filesystem.total

use Nadi\Metric\Runtime;

$runtime = new Runtime();
$metrics = $runtime->toArray();

// Returns:
// - process.runtime.name: 'php'
// - process.runtime.version: '8.3.0'
// - process.runtime.description: 'PHP 8.3.0'
// - process.pid: 12345

use Nadi\Metric\OperatingSystem;

$os = new OperatingSystem();
$metrics = $os->toArray();

// Returns:
// - os.type: 'darwin'
// - os.description: 'Darwin 23.0.0'
// - os.name: 'Darwin'
// - os.version: '23.0.0'
// - host.name: 'macbook-pro.local'
// - host.arch: 'x86_64'

use Nadi\Metric\Network;

$network = new Network();
$metrics = $network->toArray();

// Returns:
// - host.name: 'server-01'
// - host.id: 'unique-machine-id'

use Nadi\Data\Entry;
use Nadi\Data\Type;

// Entry automatically captures active OTel span context
$entry = Entry::make(Type::EXCEPTION, [
    'class' => 'DatabaseException',
    'message' => 'Connection failed',
]);

// Or set manually
$entry->setTraceId('4bf92f3577b34da6a3ce929d0e0e4736');
$entry->setSpanId('00f067aa0ba902b7');

// Trace IDs are 

$transporter->configure([
    'endpoint' => 'http://jaeger:4318',  // Use https:// in production
    'service_name' => 'my-app',
]);

$transporter->configure([
    'endpoint' => 'http://tempo:4318',  // Use https:// in production
    'service_name' => 'my-app',
]);



namespace App\Metric;

use Nadi\Support\Arr;
use Nadi\Metric\Base;
use Illuminate\Support\Str;

class Http extends Base
{
    public function metrics(): array
    {
        $startTime = defined('LARAVEL_START') ? LARAVEL_START : request()->server('REQUEST_TIME_FLOAT');

        return [
            'http.client.duration' => $startTime ? floor((microtime(true) - $startTime) * 1000) : null,
            'http.scheme' => request()->getScheme(),
            'http.route' => request()->getRequestUri(),
            'http.method' => request()->getMethod(),
            'http.status_code' => http_response_code(),
            'http.query' => request()->getQueryString(),
            'http.uri' => str_replace(request()->root(), '', request()->fullUrl()) ?: '/',
            'http.headers' => Arr::undot(collect(request()->headers->all())
                ->map(function ($header) {
                    return $header[0];
                })
                ->reject(function ($header, $key) {
                    return in_array($key, [
                        'authorization', config('nadi.header-key'), 'nadi-key',
                    ]);
                })
                ->toArray()),
        ];
    }
}

use App\Metrics\Http;
use Nadi\Metric\Metric;

$metric = new Metric();

$metric->add(new Http());

$metric->toArray();

'metrics' => [
    \App\Metrics\Http::class,
];

use Nadi\Sampling\Config;

$config = new Config(
    samplingRate: 0.1,
    baseRate: 0.05,
    loadFactor: 1.0,
    intervalSeconds: 60
);

use Nadi\Sampling\FixedRateSampling;

$samplingStrategy = new FixedRateSampling($config);

if($samplingStrategy->shouldSample()) {
    // do something
}

use Nadi\Sampling\SamplingManager;

$samplingManager = new SamplingManager($samplingStrategy);

if($samplingManager->shouldSample()) {
    // do something
}

namespace App\Sampling;

use Nadi\Sampling\Contract;
use Nadi\Sampling\Config;

class CustomSampling implements Contract
{
    public function __construct(protected Config $config) {}

    public function shouldSample(): bool
    {
        // do your logic hhere

        return true;
    }
}

use Nadi\Shipper\BinaryManager;

// Create manager with target directory
$manager = new BinaryManager('/path/to/bin');

// Install latest version
$binaryPath = $manager->install();

// Check if installed
if ($manager->isInstalled()) {
    echo "Shipper installed at: " . $manager->getBinaryPath();
    echo "Version: " . $manager->getInstalledVersion();
}

// Check for updates
if ($manager->needsUpdate()) {
    $newVersion = $manager->update();
    echo "Updated to: " . $newVersion;
}

// Execute shipper
$result = $manager->execute(['--config=/path/to/nadi.yaml', '--record']);
echo $result['output'];

// Uninstall
$manager->uninstall();

use Nadi\Shipper\PlatformDetector;

$detector = new PlatformDetector();

echo $detector->getOS();           // darwin, linux, windows
echo $detector->getArch();         // amd64, 386, arm64
echo $detector->getBinaryName('v1.0.0');  // shipper-v1.0.0-darwin-arm64.tar.gz

if ($detector->isSupported()) {
    // Platform is supported
}

use Nadi\Shipper\VersionResolver;

$resolver = new VersionResolver();

$latestVersion = $resolver->getLatestVersion();  // e.g., "v1.0.0"
$downloadUrl = $resolver->getReleaseUrl($latestVersion, 'shipper-v1.0.0-linux-amd64.tar.gz');
$configContent = $resolver->downloadReferenceConfig();

use Nadi\Shipper\BinaryManager;
use Nadi\Shipper\Exceptions\ShipperException;
use Nadi\Shipper\Exceptions\DownloadException;
use Nadi\Shipper\Exceptions\ExtractionException;
use Nadi\Shipper\Exceptions\UnsupportedPlatformException;

try {
    $manager = new BinaryManager('/path/to/bin');
    $manager->install();
} catch (UnsupportedPlatformException $e) {
    // Platform not supported (e.g., Windows 386)
} catch (DownloadException $e) {
    // Network error or GitHub API issue
} catch (ExtractionException $e) {
    // Failed to extract the archive
} catch (ShipperException $e) {
    // General shipper error
}
bash
composer