Skip to content

Core\Server::traceId

Core\Server::traceId(): string

Core\Server::traceId() returns the id of the request that your program is answering. The id is 32 lower-case hexadecimal characters, such as 4bf92f3577b34da6a3ce929d0e0e4736. The server writes the same id into its log lines.

Every response has a traceresponse header, such as 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-00. The second part is the id. To remove the header, set response_header = false in the [trace] block of nvs.toml. The id and the log lines do not change.

A request can have a traceparent header from a service that called yours. The id is then the one in that header, so both services log the same id. Otherwise the server creates a random id. The server ignores an X-Request-ID header.

A command-line program answers no request, so traceId throws a LogicError there.

Good to know: show the id on an error page. A person who reports a problem can give you the id, and you can find the request in the logs.

Return value

Returns string. 32 lower-case hexadecimal characters. If the request came with a traceparent header, the id is the one in that header.

Errors

  • LogicErrorThe program is not handling a request. This is the case in a command-line program or a test.

Examples

Print the id of the request

<?nvs
// Shows how to read the id of the current request.
// The request has a `traceparent` header, so `Core\Server::traceId` returns the id in that header.
// This prints "4bf92f3577b34da6a3ce929d0e0e4736".
string $id = Core\Server::traceId();
echo $id, "\n";
// The id always has 32 characters. This prints "32".
echo Core\Str::length($id), "\n";
Output
4bf92f3577b34da6a3ce929d0e0e4736
32

Show the id on an error page

<?nvs
// Shows an error page that gives the user the id of the request.
// A person who reports the problem can send you this id.
// You can then find the same id in the server's log lines.
string $id = Core\Server::traceId();
// This prints "Something went wrong. Please send us this code: 0af7651916cd43dd8448eb211c80319c".
echo 'Something went wrong. Please send us this code: ', $id, "\n";
Output
Something went wrong. Please send us this code: 0af7651916cd43dd8448eb211c80319c

A command line program has no id

<?nvs
// Shows what `Core\Server::traceId` does in a program that answers no request.
// This program runs on the command line, so there is no request.
// `traceId` throws a `LogicError`, and this prints "There is no request here.".
try {
echo Core\Server::traceId(), "\n";
} catch (LogicError $e) {
echo "There is no request here.\n";
}
Output
There is no request here.