Skip to content
Judgment Labs
Esc
navigateopen⌘Jpreview
On this page

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.

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

PropType
projectName?string | null
Typestring | null
projectId?string | null
Typestring | null
apiKey?string | null
Typestring | null
organizationId?string | null
Typestring | null
apiUrl?string | null
Typestring | null
environment?string | null
Typestring | null
serializer?Serializer
TypeSerializer
supportsLiveInstrumentation?boolean
Typeboolean
Defaulttrue

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

PropType
config?TracerConfig

Tracer configuration options.

TypeTracerConfig
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

PropType
instrumentorInstrumentation<InstrumentationConfig>

The OpenTelemetry instrumentation to register.

TypeInstrumentation<InstrumentationConfig>

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.

Lives on BaseTracer (rather than a runtime-specific subclass) because the OpenAI wrapper relies only on fetch-based method interception — the openai import is types-only and it uses no Node built-ins — so it is safe in both the Node and Workers runtimes.

import OpenAI from "openai";

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

Parameters

PropType
clientT

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

TypeT

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

PropType
namestring

The span name.

Typestring
attributes?Attributes | undefined

Optional span attributes.

TypeAttributes | undefined

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

PropType
options{ name: string; attributes?: Attributes; }

Span options. name is required; attributes is optional.

Type{ name: string; attributes?: Attributes; }
fn(span: Span) => T

Function to execute within the span context.

Type(span: Span) => T

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

PropType
spanNamestring

The span name.

Typestring
fn(span: Span) => T

Function to execute within the span.

Type(span: Span) => T

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

PropType
spanNamestring

The span name.

Typestring
fn(span: Span) => T

Function to execute within the span.

Type(span: Span) => T

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

PropType
carrierobject

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.).

Typeobject
fn(ctx: Context) => T

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

Type(ctx: Context) => T

Returns

T - The return value of fn.


Static Method

observe()

Wrap a function to automatically create spans and record inputs/outputs.

Can be called with a function to wrap it directly, or with just options to get a decorator (e.g. for TC39 decorator syntax).

// Direct wrapping
const traced = Tracer.observe(
  async (query: string) => search(query),
  { spanType: "tool" },
);

// Decorator form
class Agent {
  \@Tracer.observe({ spanType: "llm" })
  async chat(input: string) { ... }
}

// Fork into a linked trace
const delegate = Tracer.observe(runSubsystem, {
  spanType: "agent",
  fork: true,
});
function observe(func: (...args: TArgs) => TReturn, options?: ObserveOptions | undefined): (...args: TArgs) => TReturn

Parameters

PropType
func(...args: TArgs) => TReturn

The function to wrap. Omit to get a decorator.

Type(...args: TArgs) => TReturn
options?ObserveOptions | undefined

Optional observation options.

TypeObserveOptions | undefined

Returns

(...args: TArgs) => TReturn - The wrapped function, or a decorator if func is omitted.


Static Method

setSpanKind()

Set the kind of a span.

function setSpanKind(kind: string): void

Parameters

PropType
kindstring

The span kind (e.g. "llm", "tool", "span").

Typestring

Returns

void


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

setAttribute()

Set a single attribute on a span.

function setAttribute(key: string, value: unknown): void

Parameters

PropType
keystring

The attribute key.

Typestring
valueunknown

The attribute value (will be serialized).

Typeunknown

Returns

void


Static Method

setAttributes()

Set multiple attributes on a span.

function setAttributes(attributes: Record<string, unknown>): void

Parameters

PropType
attributesRecord<string, unknown>

Key-value pairs to set.

TypeRecord<string, unknown>

Returns

void


Static Method

setInput()

Set the input data on a span.

function setInput(inputData: unknown): void

Parameters

PropType
inputDataunknown

The input data to record.

Typeunknown

Returns

void


Static Method

setOutput()

Set the output data on a span.

function setOutput(outputData: unknown): void

Parameters

PropType
outputDataunknown

The output data to record.

Typeunknown

Returns

void


Static Method

setError()

Record an error on a span.

Sets the span status to ERROR and records the exception.

function setError(error: unknown): void

Parameters

PropType
errorunknown

The error to record.

Typeunknown

Returns

void


Static Method

recordLLMMetadata()

Record LLM usage metadata on a span.

Tracer.recordLLMMetadata({
  model: "gpt-4o",
  provider: "openai",
  output_tokens: 150,
});
function recordLLMMetadata(metadata: LLMMetadata): void

Parameters

PropType
metadataLLMMetadata

LLM metadata including model, provider, and token counts.

TypeLLMMetadata

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

PropType
customerIdstring

The customer identifier.

Typestring

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

PropType
customerUserIdstring

The customer user identifier.

Typestring

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

PropType
sessionIdstring

The session identifier.

Typestring

Returns

void


Static Method

setPropagatingAttribute()

Set an attribute and propagate it to all child spans via baggage.

Unlike setAttribute (single span only). The judgment. prefix is reserved and ignored.

function setPropagatingAttribute(key: string, value: string): void

Parameters

PropType
keystring
Typestring
valuestring
Typestring

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

PropType
tagsstring | string[]

A single tag string or an array of tag strings.

Typestring | string[]

Returns

void


Static Method

asyncEvaluate()

Trigger an asynchronous server-side evaluation on a span.

The evaluation is queued and processed server-side by the Judgment platform after the span ends. Use this to score live traffic without blocking your application.

Tracer.asyncEvaluate({
  judge: "answer_relevancy",
  example: {
    input: "What is AI?",
    actual_output: response,
  },
});
function asyncEvaluate(options: AsyncEvaluateOptions): void

Parameters

PropType
optionsAsyncEvaluateOptions

Evaluation options. judge is required; example is optional evaluation data.

TypeAsyncEvaluateOptions

Returns

void

Was this page helpful?