PHP code example of herdwatch-oss / monolog-ecs-formatter

1. Go to this page and download the library: Download herdwatch-oss/monolog-ecs-formatter 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/ */

    

herdwatch-oss / monolog-ecs-formatter example snippets


use Herdwatch\MonologEcsFormatter\Ecs\{Metrics, Labels, Tags, Service, EcsError};

$log->info('Order processed', [
    Metrics::create()->total('orders_total', 1200)->gauge('latency_ms', 12.5)->flag('is_retry', false),
    Labels::create()->add('tenant', 'acme')->add('env', 'prod'),
    Tags::of('billing', 'reconciliation'),
]);

Herdwatch\MonologEcsFormatter\MonologEcsFormatterBundle::class => ['all' => true],

$log->info('User authenticated', [
    new Service('billing-svc', version: '1.4.0', environment: 'prod'),
    new User(id: 42, email: '[email protected]'),
    new Tracing($traceId, $transactionId),
    'request_id' => $requestId,        // plain context — stays under "context", not promoted
]);

// ✅ Recommended — positional
$log->error('Sync failed', [
    new EcsError($e),
    new Service('billing-svc'),
    Labels::create()->add('tenant', 'acme'),
]);

// ⚠️ Works, but the key is redundant (it is NOT used to route the field)
$log->error('Sync failed', ['error' => new EcsError($e)]);

Metrics::fromArray(['rows_total' => 1200, 'avg_ms' => 8.3]); // non-numeric values are ignored
Labels::fromArray($keyValuePairs);
Tags::fromArray($list);

$log->error('Sync failed', [new EcsError($exception)]);

$log->info('Inbound request', [
    new Http(statusCode: 200, method: 'POST'),
    new Client(ip: $request->getClientIp()),
    Url::parse((string) $request->getUri()),
    new Event(action: 'api.request', start: $startedAt),
]);

use Herdwatch\MonologEcsFormatter\Ecs\EcsField;
use Herdwatch\MonologEcsFormatter\Ecs\SerializesToEcs;

final class FarmContext implements EcsField
{
    use SerializesToEcs;

    public function __construct(private string $herdId, private string $region) {}

    public function toEcs(): array
    {
        return ['farm' => ['herd_id' => $this->herdId, 'region' => $this->region]];
    }
}

$log->info('Herd sync complete', [new FarmContext($herd->id(), $herd->region())]);
// → { …, "farm": {"herd_id": "…", "region": "…"} }