Skip to main content
ImmutableLog logo
← Back
SymfonyPHP

Symfony Integration

Integrate ImmutableLog into any Symfony application with an EventSubscriber of three listeners: `kernel.request` marks the start, `kernel.exception` stores the exception, and `kernel.terminate` (which Symfony fires after delivering the response to the client) builds and sends the event via cURL. A send failure only produces a logger `warning`. Read the PHP-FPM section before using it in production.

Installation

There is no Composer package: you copy the `ImmutableLogSubscriber.php` file from GitHub to `src/EventSubscriber/ImmutableLogSubscriber.php`. It only uses `ext-curl` and `ext-json` (present in the official PHP images) and components that `symfony/framework-bundle` already ships (`http-kernel`, `routing`, `psr/log`). Symfony 6.4 or newer (tested on 8.1), PHP 8.1+. The file declares `namespace App\EventSubscriber;`.

bash
src/EventSubscriber/ImmutableLogSubscriber.php   # conteúdo do ImmutableLogSubscriber.php

EventSubscriber code

This is the whole file. `onRequest` marks the start of the main request (except `OPTIONS` and the paths in `SKIP_PATHS`); `onException` stores the exception; `onTerminate` builds the event and sends it after the response. An unhandled exception also produces an event, with status 500 and `error_*`. The ignored paths, the trail header setting and the timeout are constants at the top of the class (`SKIP_PATHS`, `TRUST_TRAIL_HEADER`, `TIMEOUT_MS`): edit them in your file.

php
<?php

// ImmutableLog event subscriber for Symfony (6.4, 7.x).
//
// Copy this file to src/EventSubscriber/ImmutableLogSubscriber.php. With the default
// services.yaml (autowire + autoconfigure) nothing else is needed: the kernel.event_subscriber
// tag is applied automatically. Uses only ext-curl and ext-json; no Composer package.

namespace App\EventSubscriber;

use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\TerminateEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;

final class ImmutableLogSubscriber implements EventSubscriberInterface
{
    private const DEFAULT_API_URL = 'https://api.immutablelog.com';
    private const SKIP_PATHS = ['/health', '/healthz'];
    private const CONNECT_TIMEOUT_MS = 1000;
    private const TIMEOUT_MS = 5000;
    private const MAX_ERROR_MESSAGE = 500;
    private const MAX_PATH = 2048;
    private const MAX_USER_AGENT = 512;
    private const MAX_TRAIL = 256;

    /** Read X-Imtbl-Trail from the request when the controller sets no trail. Off: caller-controlled. */
    private const TRUST_TRAIL_HEADER = false;

    /** @var array<string, string> route name -> path template, kept for the process lifetime */
    private static array $routePaths = [];

    private LoggerInterface $logger;

    public function __construct(?LoggerInterface $logger = null, private ?RouterInterface $router = null)
    {
        $this->logger = $logger ?? new NullLogger();
    }

    public static function getSubscribedEvents(): array
    {
        return [
            // High priority: start the clock before the router and the firewall.
            KernelEvents::REQUEST => ['onRequest', 4096],
            KernelEvents::EXCEPTION => ['onException', 4096],
            KernelEvents::TERMINATE => 'onTerminate',
        ];
    }

    public function onRequest(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }
        $req = $event->getRequest();
        if ($req->getMethod() === 'OPTIONS' || in_array($req->getPathInfo(), self::SKIP_PATHS, true)) {
            return;
        }
        $req->attributes->set('imtbl.started_at', microtime(true));
    }

    public function onException(ExceptionEvent $event): void
    {
        if ($event->isMainRequest()) {
            $event->getRequest()->attributes->set('imtbl.exception', $event->getThrowable());
        }
    }

    /**
     * kernel.terminate runs after the response was sent (under PHP-FPM, after
     * fastcgi_finish_request()), so the POST to ImmutableLog never delays it.
     */
    public function onTerminate(TerminateEvent $event): void
    {
        $req = $event->getRequest();
        if (!$req->attributes->has('imtbl.started_at')) {
            return; // skipped (OPTIONS, health)
        }
        try {
            $apiKey = self::env('IMTBL_API_KEY', '');
            if ($apiKey === '') {
                return;
            }
            [$requestId, $body] = $this->buildEvent($req, $event->getResponse());
            $this->send(rtrim(self::env('IMTBL_URL', self::DEFAULT_API_URL), '/').'/v1/events', $apiKey, $requestId, $body);
        } catch (\Throwable $e) {
            $this->logger->warning('[ImmutableLog] failed to send event: '.$e->getMessage());
        }
    }

    /** Symfony's Dotenv fills $_SERVER/$_ENV, not getenv(): look in all three. */
    private static function env(string $name, string $default): string
    {
        $v = $_SERVER[$name] ?? $_ENV[$name] ?? getenv($name);

        return ($v === false || $v === null || $v === '') ? $default : (string) $v;
    }

    /** @return array{0: string, 1: string} */
    private function buildEvent(Request $req, Response $res): array
    {
        $status = $res->getStatusCode();
        $kind = $status >= 400 ? 'error' : ($status >= 300 ? 'info' : ($status >= 200 ? 'success' : 'info'));
        $method = $req->getMethod();
        $path = mb_substr($req->getPathInfo(), 0, self::MAX_PATH);
        $requestId = self::uuid4();
        $latencyMs = (int) round((microtime(true) - (float) $req->attributes->get('imtbl.started_at')) * 1000);
        $clientIp = self::clientIp($req->headers->get('X-Forwarded-For'), $req->headers->get('X-Real-IP'), $req->server->get('REMOTE_ADDR'));
        $service = self::env('IMTBL_SERVICE_NAME', 'symfony-service');
        $env = self::env('IMTBL_ENV', 'production');

        $eventName = $req->attributes->get('imtbl.event_name') ?: "http.$method.$path";
        $trailSource = $req->attributes->get('imtbl.trail');
        if ($trailSource === null && self::TRUST_TRAIL_HEADER) {
            $trailSource = $req->headers->get('X-Imtbl-Trail');
        }
        $trail = self::sanitizeTrail($trailSource);

        $exception = $req->attributes->get('imtbl.exception');
        $errorType = $exception instanceof \Throwable ? get_class($exception) : null;
        $errorMessage = $exception instanceof \Throwable ? $exception->getMessage() : null;

        $payload = [
            'id' => self::uuid4(),
            'kind' => $kind,
            'message' => "$method $path -> $status",
            'timestamp' => gmdate('Y-m-d\TH:i:s\Z'),
            'context' => [
                'ip' => $clientIp ?? 'unknown',
                'user_agent' => mb_substr((string) $req->headers->get('User-Agent'), 0, self::MAX_USER_AGENT),
            ],
            'request' => ['request_id' => $requestId, 'method' => $method, 'path' => $path],
            'metrics' => ['latency_ms' => $latencyMs, 'status_code' => $status],
            'severity' => $kind === 'error' ? 'high' : 'low',
        ];
        if ($kind === 'error') {
            $payload['error'] = [
                'status_code' => $status,
                'retryable' => in_array($status, [408, 429, 500, 502, 503, 504], true),
            ];
            if ($errorType !== null) {
                $payload['error']['exception'] = $errorType;
                $payload['error']['exception_message'] = mb_substr((string) $errorMessage, 0, self::MAX_ERROR_MESSAGE);
            }
        }

        // meta is a string -> string map in the core: every value is cast with (string).
        // http_status goes as "200", never as the integer 200.
        $meta = [
            'type' => $kind,
            'event_type' => $kind,
            'event_name' => (string) $eventName,
            'service' => $service,
            'request_id' => $requestId,
            // "env" is the legacy key; "environment" is the canonical one (CONTRACT.md §4.1).
            'env' => $env,
            'environment' => $env,
            'http_method' => $method,
            'http_status' => (string) $status,
            'http_route' => $this->routeTemplate($req) ?? $path,
            'log_level' => match ($kind) { 'error' => 'error', 'warning' => 'warn', 'debug' => 'debug', default => 'info' },
        ];
        if ($clientIp !== null) {
            $meta['client_ip'] = $clientIp;
        }
        if ($errorType !== null) {
            $meta['error_type'] = $errorType;
            if ((string) $errorMessage !== '') {
                $meta['error_message'] = mb_substr((string) $errorMessage, 0, self::MAX_ERROR_MESSAGE);
            }
        }
        if ($trail !== null) {
            $meta['immutable_trail'] = $trail;
        }

        $flags = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR;

        return [$requestId, json_encode(['payload' => json_encode($payload, $flags), 'meta' => $meta], $flags)];
    }

    /**
     * Route template ("/users/{id}"). The request only carries the route NAME (_route); the
     * path comes from the route collection. Null on a 404 (no _route): the caller uses the path.
     */
    private function routeTemplate(Request $req): ?string
    {
        $name = $req->attributes->get('_route');
        if (!is_string($name) || $name === '' || $this->router === null) {
            return null;
        }
        if (!array_key_exists($name, self::$routePaths)) {
            self::$routePaths[$name] = $this->router->getRouteCollection()->get($name)?->getPath() ?? '';
        }

        return self::$routePaths[$name] !== '' ? self::$routePaths[$name] : null;
    }

    private function send(string $url, string $apiKey, string $idempotencyKey, string $body): void
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer '.$apiKey,
                'Idempotency-Key: '.$idempotencyKey,
            ],
            CURLOPT_RETURNTRANSFER => true,
            // Runs after the client got the response, but holds the PHP-FPM worker until done.
            CURLOPT_CONNECTTIMEOUT_MS => self::CONNECT_TIMEOUT_MS,
            CURLOPT_TIMEOUT_MS => self::TIMEOUT_MS,
        ]);
        $result = curl_exec($ch);
        $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        if ($result === false) {
            $this->logger->warning('[ImmutableLog] failed to send event: '.curl_error($ch));
        } elseif ($status >= 400) {
            $this->logger->warning("[ImmutableLog] event rejected: HTTP $status");
        }
        curl_close($ch);
    }

    /**
     * client_ip for the SIEM: first entry of X-Forwarded-For, then X-Real-IP, then REMOTE_ADDR.
     * Only a bare IP is returned (no port): the SIEM drops "ip:port" silently. The headers are
     * read directly, without framework.trusted_proxies; see "Proxy e X-Forwarded-For" in the README.
     */
    public static function clientIp(?string $xff, ?string $realIp, ?string $remoteAddr): ?string
    {
        $first = $xff !== null ? explode(',', $xff)[0] : null;

        return self::bareIp($first) ?? self::bareIp($realIp) ?? self::bareIp($remoteAddr);
    }

    /** "203.0.113.7", "203.0.113.7:4711", "[2001:db8::1]:8080", "2001:db8::1" -> bare IP. */
    private static function bareIp(?string $raw): ?string
    {
        $s = trim((string) $raw);
        if ($s === '') {
            return null;
        }
        if ($s[0] === '[') {
            $end = strpos($s, ']');
            $s = $end === false ? '' : substr($s, 1, $end - 1);
        } elseif (substr_count($s, ':') === 1) {
            $s = explode(':', $s)[0];
        }
        if (filter_var($s, FILTER_VALIDATE_IP) === false) {
            return null;
        }
        // "::ffff:10.0.0.1" -> "10.0.0.1"
        if (stripos($s, '::ffff:') === 0 && filter_var(substr($s, 7), FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) {
            return substr($s, 7);
        }

        return $s;
    }

    /** The core rejects a trail that is empty, longer than 256 chars or contains ':'. */
    private static function sanitizeTrail(mixed $value): ?string
    {
        if (!is_scalar($value)) {
            return null;
        }
        $s = mb_substr(str_replace(':', '-', trim((string) $value)), 0, self::MAX_TRAIL);

        return $s === '' ? null : $s;
    }

    private static function uuid4(): string
    {
        $b = random_bytes(16);
        $b[6] = chr((ord($b[6]) & 0x0F) | 0x40);
        $b[8] = chr((ord($b[8]) & 0x3F) | 0x80);

        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4));
    }
}

Registration and configuration

With the default `config/services.yaml` (`autowire: true`, `autoconfigure: true` and `App\` loaded from `src/`), there is nothing to register: the subscriber is detected and gets the `kernel.event_subscriber` tag. The constructor's `LoggerInterface` and `RouterInterface` are injected by autowiring (both are optional). Without autoconfigure, register it by hand.

yaml
# Verifique o registro:
bin/console debug:event-dispatcher kernel.terminate
#  App\EventSubscriber\ImmutableLogSubscriber::onTerminate()

# Sem autoconfigure, registre à mão em config/services.yaml:
services:
    App\EventSubscriber\ImmutableLogSubscriber:
        tags: [kernel.event_subscriber]

The subscriber reads `$_SERVER`, `$_ENV` and `getenv()`, in that order. Symfony's Dotenv fills the first two, so `.env`, `.env.local` and `secrets:set` work. Without a key, the subscriber sends nothing.

bash
# .env.local (fora do git)
IMTBL_API_KEY=iml_live_xxxxxxxxxxxxxxxx
IMTBL_SERVICE_NAME=meu-servico-symfony
IMTBL_ENV=production
VariableRequiredDescription
IMTBL_API_KEYYesImmutableLog API key, with the `events:write` scope
IMTBL_URLNoAPI base URL (default `https://api.immutablelog.com`)
IMTBL_SERVICE_NAMENoService name (`meta.service`); default `symfony-service`
IMTBL_ENVNoEnvironment (`meta.environment` and `meta.env`); default `production`

Never put the key in code or in the repository: use .env.local kept out of git, `bin/console secrets:set IMTBL_API_KEY` or a secrets manager. On PHP-FPM, with `clear_env = yes` (the default), variables exported only in the process environment do not reach PHP; use .env.local, Symfony secrets or `env[IMTBL_API_KEY] = ...` in the FPM pool.

How it works

kernel.request

Priority 4096. Marks imtbl.started_at on the main request (except OPTIONS and ignored paths)

kernel.exception

Priority 4096. Stores the exception in imtbl.exception

kernel.terminate

Runs after the response: reads status, route, exception and markers; builds the event; POST via cURL

Idempotency-Key

A new UUID v4 per event, equal to meta.request_id. The incoming X-Request-Id is not used, because it comes from the caller and two different events with the same value would be discarded as a duplicate

body

The subscriber never reads the request body: no content, no hash. Sub-requests do not produce their own event

Sending, PHP-FPM and response time

PHP has no background thread: the POST runs in the same process, in `kernel.terminate`. How you serve the application changes the effect.

How it is servedEffect of sending
PHP-FPMThe client gets the response without waiting for the send (`fastcgi_finish_request()` runs first). But the FPM worker stays busy until the send finishes, at most the timeout. With a slow ImmutableLog, workers get stuck and the following requests wait in the pool queue (the default is 5 workers).
symfony server:start / php -SThere is no `fastcgi_finish_request()`: the connection only closes after kernel.terminate. With a slow ImmutableLog, every response is delayed up to the timeout (measured: 5 s with the core stalled). Use it in development only.

Keep `TIMEOUT_MS` low (the file default is 5000) and size the FPM pool. To isolate it for good, move the send to Messenger, which is not in this file. With ImmutableLog simply down (connection refused), there is no visible effect.

Custom event and trail

Set the `imtbl.event_name` and `imtbl.trail` request attributes in any controller. `onTerminate` reads these values when building the event.

php
#[Route('/payments', name: 'payments', methods: ['POST'])]
public function create(Request $request): JsonResponse
{
    $request->attributes->set('imtbl.event_name', 'payment.created');
    $request->attributes->set('imtbl.trail', 'order-7782');

    return new JsonResponse(['ok' => true], 201);
}

Auto default: http.METHOD.path.

Immutable trail (immutable_trail)

A trail groups related events into a single auditable timeline and goes in `meta.immutable_trail`. Set the `imtbl.trail` request attribute. The value goes through `sanitizeTrail` before sending.

php
#[Route('/flows/{id}/run', methods: ['POST'])]
public function run(Request $request, string $id): JsonResponse
{
    $request->attributes->set('imtbl.trail', "flow-{$id}");
    // ... business logic ...
    return new JsonResponse(['status' => 'ok']);
}

The trail cannot be empty, exceed 256 characters, or contain `:`, and violations return `400 invalid_immutable_trail`. That is why `sanitizeTrail` replaces `:` with `-`, truncates at 256 and omits the key if it ends up empty.

The `X-Imtbl-Trail` header is optional and off by default. It is only read with `TRUST_TRAIL_HEADER = true` (constante no topo da classe), and only when the controller did not set the trail. The header comes from whoever calls the service, so any caller could hang events on another caller's trail within the same tenant. Turn it on only when the service receives calls exclusively from your own internal services.

Response and status codes

The ingestion API is asynchronous. Success returns 202 (new) or 200 (idempotent duplicate). Sending happens on `kernel.terminate` and a rejection only produces a logger `warning`, so these codes matter mostly if you send events manually.

StatusMeaning
202Event accepted and queued (new)
200Idempotency-Key already exists (duplicate: true)
400Missing/empty Idempotency-Key or invalid_immutable_trail
403Inactive/expired subscription, scope or retention
413payload_too_large (server limit: 16KB)
429monthly_limit_exceeded, do not retry
503mempool_full, transient, retryable

meta fields

Beyond the payload, the meta object carries the fields the SIEM uses to normalize (ECS) and enrich the event. All meta values are strings.

Field in metaWhat it does in the SIEM
event_nameThe event label (e.g. http.GET.auth-me-user, Payment error), the identifier shown in the listing. Becomes event.action and derives event.category (e.g. a name with login → authentication).
client_ipBecomes source.ip with maximum precedence and provenance client_asserted. It is the only meta field that becomes source.ip. It must be a plain IP, without a port. See the section below.
immutable_trailBecomes imtbl.immutable_trail, which groups related events for investigation (e.g. one order, one user).
typeEvent severity: error / warning / info / success. Colors the badge in the listing. (event_type is accepted as a synonym.)
http_method, http_status, http_route, log_level, environment, error_type, error_messageSent by the middlewares, always as a string (including http_status, e.g. "200"). error_type and error_message only exist when there is an error.
service, env, request_idMetadata: indexed and queryable in the dashboard (search/filters).

client_ip: end-user IP

The problem it solves

Between the browser and the core there are proxies/ALB. The IP the core sees on the connection is the previous hop (the client's backend or an AWS proxy), not the user's. Without action, source.ip would be the proxy IP, useless for geo, threat and IP-based detection. (Real example: XFF arrived as 44.192.13.3 (AWS) while the user was 179.110.4.205.)

The solution

The client's backend is the only one that sees the browser's real IP, so it forwards that IP in meta.client_ip when calling POST /v1/events.

How the SIEM handles it

  • Validates it is an IP (v4/v6). A non-IP value is ignored, without dropping the event. An IP with a port (e.g. 1.2.3.4:5678) is also silently discarded.
  • Writes to source.ip with maximum precedence (see order below).
  • Stamps imtbl.source_ip_origin = "client_asserted"; the UI shows the “User IP” badge.
  • Feeds GeoIP, threat intel and IP-based detection rules.
source.ip precedence:client_ipX-Forwarded-For (1º hop)X-Real-IPconnection IP

Provenance and trust

client_ip is asserted by the tenant: the client's backend claims the IP, and it can be forged by whoever controls that backend. However it stays contained within the tenant (it never crosses another tenant's boundary). A threat/geo hit on a client_asserted value is a claim, not an edge observation.

How to obtain the IP in your backend

Try the candidates in order: the first IP from X-Forwarded-For (closest to the user), then X-Real-IP (if your proxy sets it) and finally the connection IP. Each candidate goes through a function that strips the port (1.2.3.4:5678, [2001:db8::1]:8080) and the brackets and checks that it is a real IP, without any DNS lookup. An invalid value (garbage, localhost, an IPv6 zone such as fe80::1%eth0) is ignored and the next candidate is tried. Send a plain IP, without a port, and if no candidate is a valid IP omit the client_ip key (meta does not accept null, and never send “unknown”).

Only behind a trusted proxy: reading the first IP from X-Forwarded-For is only safe when a trusted proxy or ALB sits in front of the application and overwrites or appends the header. Without a proxy, the client controls the header and can forge the IP, and the SIEM will promote that value to source.ip.

php
function bare_ip(?string $value): ?string {
    $v = trim((string) $value);
    if ($v === '') return null;
    if ($v[0] === '[') {
        $end = strpos($v, ']');
        if ($end === false) return null;
        $rest = substr($v, $end + 1);
        if ($rest !== '' && !preg_match('/^:\d+$/', $rest)) return null;
        $v = substr($v, 1, $end - 1);
    } elseif (substr_count($v, ':') === 1) {
        $v = explode(':', $v, 2)[0]; // 1.2.3.4:5678 -> 1.2.3.4
    }
    if (strpos($v, '%') !== false) return null; // zona IPv6 (fe80::1%eth0) nao e IP puro
    return filter_var($v, FILTER_VALIDATE_IP) !== false ? $v : null;
}

// Candidatos na ordem: 1o item do X-Forwarded-For, X-Real-IP, IP de conexao.
function client_ip(): ?string {
    $xff = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
    if ($xff !== '' && ($ip = bare_ip(explode(',', $xff)[0])) !== null) return $ip;
    if (($ip = bare_ip($_SERVER['HTTP_X_REAL_IP'] ?? null)) !== null) return $ip;
    return bare_ip($_SERVER['REMOTE_ADDR'] ?? null);
}

$meta = ['event_name' => 'user.login'];
$ip = client_ip();
if ($ip !== null) {
    $meta['client_ip'] = $ip; // sem IP valido, omita a chave (nunca "unknown")
}

Payload example

json
{
  "payload": "{\"user\":\"bob\",\"action\":\"login\"}",
  "meta": {
    "event_name": "user.login",
    "client_ip": "179.110.4.205",
    "immutable_trail": "user-bob"
  }
}

PII note: client_ip is PII and gets sealed into the immutable block (permanent). Decide consciously between forensic evidence and “right to be forgotten” before sending it.

This documentation reflects the current integration behavior. For questions or advanced integrations, contact the support team.

Back to PHP