Judgment Labs Logo

Tracer

Concrete tracer implementation for Node.js applications. Use `Tracer.init()` to create and activate a new tracer. This sets up OpenTelemetry span processing and export to the Judgment platform.

Concrete tracer implementation for Node.js applications.

Use Tracer.init() to create and activate a new tracer. This sets up OpenTelemetry span processing and export to the Judgment platform.

import { Tracer } from "judgeval";

const tracer = await Tracer.init({ projectName: "my-project" });

const traced = Tracer.observe(async (input: string) => {
  return await processInput(input);
});

await traced("hello");
await Tracer.forceFlush();
await Tracer.shutdown();

Attributes

projectName

:

string | null

projectId

:

string | null

apiKey

:

string | null

organizationId

:

string | null

apiUrl

:

string | null

environment

:

string | null

serializer

:

Serializer

supportsLiveInstrumentation

:

boolean

Default:

true


Static Method

init()

Create and activate a new Tracer.

This is the recommended way to initialize tracing. Credentials are read from environment variables if not provided explicitly.

const tracer = await Tracer.init({
  projectName: "my-project",
  environment: "production",
});
async function init(config: TracerConfig = {}): Promise<Tracer>

Parameters

config

:

TracerConfig

Tracer configuration options.

Default:

{}

Returns

Promise<Tracer> - A configured and activated Tracer instance.


getSpanExporter()

Get or create the span exporter for this tracer.

function getSpanExporter(): JudgmentSpanExporter

Returns

JudgmentSpanExporter - The span exporter instance.


getSpanProcessor()

Get or create the span processor for this tracer.

function getSpanProcessor(): JudgmentSpanProcessor

Returns

JudgmentSpanProcessor - The span processor instance.


setActive()

Set this tracer as the active tracer in the global provider.

function setActive(): boolean

Returns

boolean - true if activation succeeded, false if a root span is active.


Static Method

getCurrentSpan()

Get the currently active span.

function getCurrentSpan(): Span | undefined

Returns

Span | undefined - The active span, or undefined if none.


Static Method

forceFlush()

Flush all pending spans to the export endpoint.

Call this before your process exits to ensure all spans are sent.

await Tracer.forceFlush();
async function forceFlush(): Promise<void>

Returns

Promise<void>


Static Method

shutdown()

Shut down the tracer and flush any pending data.

await Tracer.shutdown();
async function shutdown(): Promise<void>

Returns

Promise<void>


Static Method

registerOTELInstrumentation()

Register an OpenTelemetry instrumentation to capture spans automatically.

import { OpenAIInstrumentation } from "@opentelemetry/instrumentation-openai";
Tracer.registerOTELInstrumentation(new OpenAIInstrumentation());
function registerOTELInstrumentation(instrumentor: Instrumentation<InstrumentationConfig>): void

Parameters

instrumentor

required

:

Instrumentation<InstrumentationConfig>

The OpenTelemetry instrumentation to register.

Returns

void


Static Method

wrap()

Wrap a supported LLM client to add automatic tracing.

Currently supports OpenAI clients. The client is instrumented in-place and returned.

import OpenAI from "openai";

const client = Tracer.wrap(new OpenAI());
function wrap(client: T): T

Parameters

client

required

:

T

An LLM client instance (e.g. new OpenAI()).

Returns

T - The same client instance, instrumented.


Static Method

getOTELTracer()

Get the underlying OpenTelemetry Tracer instance.

function getOTELTracer(): Tracer

Returns

Tracer - The OpenTelemetry Tracer.


Static Method

startSpan()

Start a new span without setting it as active.

Most users should prefer observe or with, which handle activation, error recording, and span ending automatically. Use this only when you need low-level control over the span lifecycle.

function startSpan(name: string, attributes?: Attributes | undefined): Span

Parameters

name

required

:

string

The span name.

attributes

:

Attributes | undefined

Optional span attributes.

Returns

Span - The created span.


Static Method

startActiveSpan()

Start a new active span and run a function within it.

The span is automatically ended when the function completes.

Most users should prefer observe or with, which additionally record inputs/outputs and capture errors automatically. Use this only when you need low-level control over the span lifecycle.

Tracer.startActiveSpan({ name: "fetch-user" }, (span) => {
  // ...
});
function startActiveSpan(options: { name: string; attributes?: Attributes; }, fn: (span: Span) => T): T

Parameters

options

required

:

{ name: string; attributes?: Attributes; }

Span options. name is required; attributes is optional.

fn

required

:

(span: Span) => T

Function to execute within the span context.

Returns

T - The return value of fn.


Static Method

span()

Create a named span, execute a function, and handle errors.

Errors are recorded on the span and re-thrown.

function span(spanName: string, fn: (span: Span) => T): T

Parameters

spanName

required

:

string

The span name.

fn

required

:

(span: Span) => T

Function to execute within the span.

Returns

T - The return value of fn.


Static Method

with()

Alias for span. Create a named span and execute a function within it.

function with(spanName: string, fn: (span: Span) => T): T

Parameters

spanName

required

:

string

The span name.

fn

required

:

(span: Span) => T

Function to execute within the span.

Returns

T - The return value of fn.


Static Method

continueTrace()

Continue a distributed trace from an upstream service.

Extracts W3C trace context and baggage from carrier and installs it as the active context for the duration of fn. Any span started inside — including @Tracer.observe-wrapped functions and Tracer.with blocks — becomes a child of the upstream parent, stitching your service into the caller's trace.

Use this at the entry point of an inbound request (HTTP handler, message queue consumer, RPC dispatcher, etc.) to join a trace started by the upstream caller. If the carrier contains no trace context, fn still runs normally with a fresh context.

import { Tracer } from "judgeval";

const handle = Tracer.observe(async (payload: unknown) => {
  // ... your agent logic ...
});

// Express / Node http handler:
app.post("/run", async (req, res) => {
  await Tracer.continueTrace(req.headers, async () => {
    const result = await handle(req.body);
    res.json(result);
  });
});

Propagating in the opposite direction (outbound):

import { propagation } from "judgeval";

const headers: Record<string, string> = {};
propagation.inject(headers);
await fetch(downstreamUrl, { headers, method: "POST", body });
function continueTrace(carrier: object, fn: (ctx: Context) => T): T

Parameters

carrier

required

:

object

A mapping containing propagation headers. Typically req.headers from Node's http/Express/Fastify, but any dict-shaped object with lowercase keys works (queue attributes, Lambda event headers, RPC metadata, etc.).

fn

required

:

(ctx: Context) => T

Function to run inside the extracted context. Receives the extracted as its argument; most callers ignore it. Sync or async.

Returns

T - The return value of fn.


Static Method

setLLMSpan()

Set the current span kind to "llm".

function setLLMSpan(): void

Returns

void


Static Method

setToolSpan()

Set the current span kind to "tool".

function setToolSpan(): void

Returns

void


Static Method

setGeneralSpan()

Set the current span kind to "span".

function setGeneralSpan(): void

Returns

void


Static Method

setCustomerId()

Set the customer ID on the current active span.

The ID is automatically propagated to all child spans via baggage. This method always targets the active span because it modifies the active context's baggage for propagation.

function setCustomerId(customerId: string): void

Parameters

customerId

required

:

string

The customer identifier.

Returns

void


Static Method

setCustomerUserId()

Set the customer user ID on the current active span.

The ID is automatically propagated to all child spans via baggage. This method always targets the active span because it modifies the active context's baggage for propagation.

function setCustomerUserId(customerUserId: string): void

Parameters

customerUserId

required

:

string

The customer user identifier.

Returns

void


Static Method

setSessionId()

Set the session ID on the current active span.

The ID is automatically propagated to all child spans via baggage. This method always targets the active span because it modifies the active context's baggage for propagation.

function setSessionId(sessionId: string): void

Parameters

sessionId

required

:

string

The session identifier.

Returns

void


Static Method

tag()

Add tags to the current trace.

Tracer.tag("production");
Tracer.tag(["important", "customer-facing"]);
function tag(tags: string | string[]): void

Parameters

tags

required

:

string | string[]

A single tag string or an array of tag strings.

Returns

void