> ## Documentation Index
> Fetch the complete documentation index at: https://docs.apivalk.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Observability

> Logs, trace id, metrics and traces for an Apivalk app: what Apivalk logs by itself, which hook to use for what, and how to wire up OpenTelemetry.

Apivalk has no event system of its own. The two PSR-15 middleware stacks, the exception handler and the trace id cover every point an event would mark, with the same tools you already use for everything else.

## What you get out of the box

### Trace id

Every request gets an `ApivalkTraceId`, a UUIDv7, before the global middleware run. Apivalk's request log lines carry it under `apivalk_trace_id`, and `enableTraceIdInResponseHeaders()` sends it back to the client. How to read it in a controller, a routed or a global middleware and the exception handler is in [Trace id](https://docs.apivalk.com/configuration.md#trace-id). Put it into your own log lines under the same key, and one id finds every line of a request.

### What Apivalk logs

| Level | When | Message | Context |
| - | - | - | - |
| `warning` | `run()` cannot build the PSR-7 request, the client gets a 400 | `Malformed request rejected: ...` | `exception`, `apivalk_trace_id` |
| `error` | a throwable from a global middleware, routing, a routed middleware or the controller | `Unhandled <class> while handling a request: <message>` | `exception`, `apivalk_trace_id` |
| `critical` | the exception handler throws, returns no response or one the `Responder` cannot render | `The configured exception handler failed with <class>: <message>` | `exception`, `apivalk_trace_id` |
| `warning` | `JwtAuthenticator` cannot load the JWKS | `JWKS from <url> could not be loaded: <message>` | `exception` |

The first three go to the PSR-3 logger of `ApivalkConfiguration`, a `NullLogger` when you pass none. `JwtAuthenticator` logs to the logger passed to its own constructor.

That is all. There is no line per request and nothing for a 4xx your routes and middleware answer: an invalid token, a failed validation or a 404 is an answer, not a failure. The access log, metrics and traces are yours, built from the hooks below.

## Where to hook in

| | Global middleware (`getGlobalMiddlewareStack()`) | Routed middleware (`getMiddlewareStack()`) |
| - | - | - |
| Sees | every request, the 404, 405 and 500 included | routed requests only. A 404 or 405 never reaches it, and a throwable passes through it as an exception, the 500 is built outside |
| Knows | the PSR-7 request, the trace id via `ApivalkTraceId::fromRequest($request)` | the same plus `ApivalkContext::fromRequest($request)`: route, controller, typed request, auth identity |
| Use for | access log, the root span of a trace, counting every request | metrics per route, naming the span after the route, anything per identity |

If you are looking for an event, this is where it lives in 4.0:

| Event | Hook |
| - | - |
| Request received, response sent | global middleware, before and after `$handler->handle($request)` |
| Route matched | routed middleware, `ApivalkContext::fromRequest($request)->getRoute()` |
| Authenticated | routed middleware added after `AuthenticationMiddleware`, `ApivalkContext::fromRequest($request)->getRequest()->getAuthIdentity()` |
| Authorized | routed middleware added after `SecurityMiddleware`, it only runs for a request that passed |
| Authorization denied, validation failed | the response a middleware added before `SecurityMiddleware` or `RequestValidationMiddleware` gets back: status 401, 403 or 422 and its body |
| Exception thrown | the [exception handler](https://docs.apivalk.com/core/error-handling.md), `callable(\Throwable, ServerRequestInterface)` |

## Access log

The `AccessLogMiddleware` in [Middleware](https://docs.apivalk.com/middleware/index.md#apivalk-context) is a global middleware, so the 404 and the 500 get a line too, with method, path, status and trace id. For the duration, take `hrtime(true)` before `$handler->handle($request)` and log the difference, as the metrics middleware below does. An access log line may carry the raw path; a metric label may not.

## Metrics

A routed middleware that records method, route, status and duration. `HttpMetrics` stands for your metrics client (a Prometheus client, StatsD, an OpenTelemetry meter):

```php theme={null}
interface HttpMetrics
{
    public function observeRequest(string $method, string $route, int $status, float $seconds): void;
}
```

```php theme={null}
use apivalk\apivalk\Http\ApivalkContext;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final readonly class RequestMetricsMiddleware implements MiddlewareInterface
{
    public function __construct(private HttpMetrics $metrics)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $route = ApivalkContext::fromRequest($request)->getRoute();
        $startedAt = hrtime(true);
        $status = 500; // a throwable from further in ends as the exception handler's response, a 500 by default

        try {
            $response = $handler->handle($request);
            $status = $response->getStatusCode();

            return $response;
        } finally {
            $this->metrics->observeRequest(
                $route->getMethod()->value,
                $route->getUrl(),
                $status,
                (hrtime(true) - $startedAt) / 1e9
            );
        }
    }
}

$configuration->getMiddlewareStack()->add(new RequestMetricsMiddleware($metrics));
```

Label with the route template, `$route->getUrl()` (`/pets/{pet_id}`), never with the request path (`/pets/7`). Every distinct label value is a new time series in your metrics backend: the template gives one series per route, the path one per id, and any client can create new series by requesting new ids until the backend runs out of memory.

Add it first to the routed stack, so it times authentication, rate limiting and validation and sees their 401, 403, 429 and 422. A 404 or 405 never reaches it. If you need those, count them in a global middleware under a fixed label, again never the path.

## Error reporting

If your error tracker has a PSR-3 integration, you need no code: pass it as the logger, or add it as a handler to the logger you pass. Every unhandled throwable reaches it at `error` level, with the throwable under `exception` and the trace id under `apivalk_trace_id`.

Otherwise report from the exception handler. `$errorReporter` stands for your tracker's client:

```php theme={null}
use apivalk\apivalk\ApivalkConfiguration;
use apivalk\apivalk\ApivalkExceptionHandler;
use apivalk\apivalk\Http\ApivalkTraceId;
use apivalk\apivalk\Http\Response\AbstractApivalkResponse;
use Psr\Http\Message\ServerRequestInterface;

$configuration = new ApivalkConfiguration(
    $router,
    static function (
        \Throwable $throwable,
        ServerRequestInterface $request
    ) use ($errorReporter): AbstractApivalkResponse {
        $errorReporter->report($throwable, ['apivalk_trace_id' => ApivalkTraceId::fromRequest($request)]);

        return ApivalkExceptionHandler::handle($throwable, $request);
    }
);
```

It runs for every throwable `handle()` catches, one from a global middleware included, right after the `error` log line. The request is the PSR-7 request without an `ApivalkContext`, so the route is not there. If the reporter throws, Apivalk logs that at `critical` and the client still gets the default 500. See [Error Handling](https://docs.apivalk.com/core/error-handling.md).

## OpenTelemetry

`Apivalk` is a PSR-15 `RequestHandlerInterface` and its middleware are PSR-15 middleware, so OpenTelemetry's PSR-15 instrumentation works without anything Apivalk specific. Without the extension, a global middleware does the same job by hand.

> [!NOTE]
>
> Tested against Apivalk 4.0 on FrankenPHP, classic and worker mode, with `ext-opentelemetry` 1.5.0, `open-telemetry/sdk` 1.18.0, `open-telemetry/opentelemetry-auto-psr15` 1.3.2 and the console exporter.

### Auto-instrumentation

Install the `opentelemetry` PHP extension as the [OpenTelemetry PHP docs](https://opentelemetry.io/docs/zero-code/php/) describe, then the SDK, the PSR-15 instrumentation and an exporter:

```bash theme={null}
composer require open-telemetry/sdk open-telemetry/opentelemetry-auto-psr15 open-telemetry/exporter-otlp
```

Configure it through the environment, e.g.:

```bash theme={null}
OTEL_PHP_AUTOLOAD_ENABLED=true
OTEL_SERVICE_NAME=my-api
OTEL_TRACES_EXPORTER=otlp # console prints the spans to stdout, for a first look
```

What you get:

* `Apivalk::handle()` is the first `RequestHandlerInterface::handle()` of the request, so it becomes the server span. It continues an incoming `traceparent`. `run()` goes through `handle()`, so a plain front controller is covered too.
* One internal span per middleware `process()` and per handler (`MiddlewareChain`, `RoutingHandler`, `DispatchHandler`), global and routed stack alike.
* The server span is named after the HTTP method only (`GET`) and carries `url.path`, not the route. The middleware below adds it.
* The instrumentation marks the server span and every handler span as an error when the status is 400 or higher, a 404 or a 422 included.
* A throwable is recorded on the spans of the routed stack it passed through. The server span sees the 500 the exception handler built, not the exception.

The instrumentation stores the server span on the request under the attribute `OpenTelemetry\API\Trace\SpanInterface`. A routed middleware names it after the route template, for the same cardinality reason as the metrics label, and adds the trace id, so a trace leads to the log lines:

```php theme={null}
use apivalk\apivalk\Http\ApivalkContext;
use OpenTelemetry\API\Trace\SpanInterface;
use OpenTelemetry\SemConv\Attributes\HttpAttributes;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final readonly class RouteSpanMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $span = $request->getAttribute(SpanInterface::class);

        if ($span instanceof SpanInterface) {
            $context = ApivalkContext::fromRequest($request);
            $route = $context->getRoute();

            $span->updateName(\sprintf('%s %s', $route->getMethod()->value, $route->getUrl()))
                ->setAttribute(HttpAttributes::HTTP_ROUTE, $route->getUrl())
                ->setAttribute('apivalk.trace_id', $context->getApivalkTraceId());
        }

        return $handler->handle($request);
    }
}

$configuration->getMiddlewareStack()->add(new RouteSpanMiddleware());
```

A 404 or 405 never reaches a routed middleware, so its span keeps the plain method name.

### Route match, request population and respond

The PSR-15 instrumentation stops at `handle()` and `process()`. Matching the route (loading the route index from the cache included) and building the typed request happen inside `RoutingHandler`, the controller and the JSON encoding inside `DispatchHandler`, so they only show up as the own time of those spans. The extension's `hook()` gives them spans of their own, without changing Apivalk:

```php theme={null}
<?php

// otel-apivalk-hooks.php: require it once after vendor/autoload.php, in a worker before the request loop

declare(strict_types=1);

use apivalk\apivalk\Http\Request\AbstractApivalkRequest;
use apivalk\apivalk\Http\Response\Responder;
use apivalk\apivalk\Router\AbstractRouter;
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\Span;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\Context\Context;

use function OpenTelemetry\Instrumentation\hook;

if (!\extension_loaded('opentelemetry')) {
    return;
}

$startSpan = static fn(string $spanName): \Closure => static function () use ($spanName): void {
    $span = Globals::tracerProvider()->getTracer('apivalk')->spanBuilder($spanName)->startSpan();
    Context::storage()->attach($span->storeInContext(Context::getCurrent()));
};

$endSpan = static function (mixed $object, array $params, mixed $returnValue, ?\Throwable $exception): void {
    $scope = Context::storage()->scope();

    if ($scope === null) {
        return;
    }

    $scope->detach();
    $span = Span::fromContext($scope->context());

    if ($exception !== null) {
        $span->recordException($exception);
        $span->setStatus(StatusCode::STATUS_ERROR);
    }

    $span->end();
};

hook(AbstractRouter::class, 'match', pre: $startSpan('apivalk.route.match'), post: $endSpan);
hook(AbstractApivalkRequest::class, 'populate', pre: $startSpan('apivalk.request.populate'), post: $endSpan);
hook(Responder::class, 'respond', pre: $startSpan('apivalk.respond'), post: $endSpan);
```

A routed request then looks like this (`MiddlewareChain` spans left out):

```
GET /pets/{pet_id}                        server span, Apivalk::handle()
└─ RoutingHandler::handle
   ├─ apivalk.route.match                 loading the route index from the cache included
   ├─ apivalk.request.populate            typed request from the PSR-7 request
   └─ <your routed middleware>
      └─ DispatchHandler::handle          controller factory, __invoke(), respond
         └─ apivalk.respond               typed response to PSR-7, the JSON encoding
```

* The controller has no span of its own: every controller declares its own `__invoke()`, there is no parent method to hook. Its time is `DispatchHandler::handle` minus `apivalk.respond`.
* `apivalk.respond` also shows up where a middleware answers (401, 403, 422, 429) and directly under `RoutingHandler` for the 404, 405 and the exception handler's 500.
* The hook on `AbstractRouter::match` covers your own router as well.

### Without the extension: a span middleware

`open-telemetry/sdk` and an exporter are enough for a server span of your own, the extension is not needed. Add this first to the global stack, so it wraps everything else and every response, the 404 and the 500 included:

```php theme={null}
use OpenTelemetry\API\Globals;
use OpenTelemetry\API\Trace\SpanInterface;
use OpenTelemetry\API\Trace\SpanKind;
use OpenTelemetry\API\Trace\StatusCode;
use OpenTelemetry\API\Trace\TracerInterface;
use OpenTelemetry\SemConv\Attributes\HttpAttributes;
use OpenTelemetry\SemConv\Attributes\UrlAttributes;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final readonly class TracingMiddleware implements MiddlewareInterface
{
    public function __construct(private TracerInterface $tracer)
    {
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $span = $this->tracer->spanBuilder($request->getMethod())
            ->setSpanKind(SpanKind::KIND_SERVER)
            ->setParent(Globals::propagator()->extract($request->getHeaders()))
            ->setAttribute(HttpAttributes::HTTP_REQUEST_METHOD, $request->getMethod())
            ->setAttribute(UrlAttributes::URL_PATH, $request->getUri()->getPath())
            ->startSpan();
        $scope = $span->activate();

        try {
            $response = $handler->handle($request->withAttribute(SpanInterface::class, $span));
            $span->setAttribute(HttpAttributes::HTTP_RESPONSE_STATUS_CODE, $response->getStatusCode());

            if ($response->getStatusCode() >= 500) {
                $span->setStatus(StatusCode::STATUS_ERROR);
            }

            return $response;
        } finally {
            $scope->detach();
            $span->end();
        }
    }
}

$configuration->getGlobalMiddlewareStack()->add(new TracingMiddleware(Globals::tracerProvider()->getTracer('my-api')));
```

It needs no `catch`: inside the global stack, a throwable from routing, a routed middleware or the controller comes back as the exception handler's response. The `finally` ends the span when a global middleware added after it throws.

It puts the span under the same request attribute as the auto-instrumentation, so `RouteSpanMiddleware` names it after the route as well. Use one or the other: with both, every request gets two server spans.

The SDK still reads the `OTEL_*` variables above when `OTEL_PHP_AUTOLOAD_ENABLED=true`; without autoloading, set up a tracer provider as the [OpenTelemetry PHP docs](https://opentelemetry.io/docs/languages/php/) show.

## Long-running workers

Every recipe here keeps its request state in local variables and request attributes, never on the middleware, so it is safe in a [FrankenPHP worker](https://docs.apivalk.com/how-to/frankenphp-worker.md), where one middleware instance serves every request.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.