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
projectName?string | null
string | nullprojectId?string | null
string | nullapiKey?string | null
string | nullorganizationId?string | null
string | nullapiUrl?string | null
string | nullenvironment?string | null
string | nullserializer?Serializer
SerializersupportsLiveInstrumentation?boolean
booleantrueStatic 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.
TracerConfig{}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
instrumentorInstrumentation<InstrumentationConfig>
The OpenTelemetry instrumentation to register.
Instrumentation<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
clientT
An LLM client instance (e.g. new OpenAI()).
TReturns
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
namestring
The span name.
stringattributes?Attributes | undefined
Optional span attributes.
Attributes | undefinedReturns
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{ name: string; attributes?: Attributes; }
Span options. name is required; attributes is optional.
{ name: string; attributes?: Attributes; }fn(span: Span) => T
Function to execute within the span context.
(span: Span) => TReturns
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
spanNamestring
The span name.
stringfn(span: Span) => T
Function to execute within the span.
(span: Span) => TReturns
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
spanNamestring
The span name.
stringfn(span: Span) => T
Function to execute within the span.
(span: Span) => TReturns
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
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.).
objectfn(ctx: Context) => T
Function to run inside the extracted context. Receives the extracted as its argument; most callers ignore it. Sync or async.
(ctx: Context) => TReturns
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
func(...args: TArgs) => TReturn
The function to wrap. Omit to get a decorator.
(...args: TArgs) => TReturnoptions?ObserveOptions | undefined
Optional observation options.
ObserveOptions | undefinedReturns
(...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
kindstring
The span kind (e.g. "llm", "tool", "span").
stringReturns
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
keystring
The attribute key.
stringvalueunknown
The attribute value (will be serialized).
unknownReturns
void
Static Method
setAttributes()
Set multiple attributes on a span.
function setAttributes(attributes: Record<string, unknown>): void
Parameters
attributesRecord<string, unknown>
Key-value pairs to set.
Record<string, unknown>Returns
void
Static Method
setInput()
Set the input data on a span.
function setInput(inputData: unknown): void
Parameters
inputDataunknown
The input data to record.
unknownReturns
void
Static Method
setOutput()
Set the output data on a span.
function setOutput(outputData: unknown): void
Parameters
outputDataunknown
The output data to record.
unknownReturns
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
errorunknown
The error to record.
unknownReturns
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
metadataLLMMetadata
LLM metadata including model, provider, and token counts.
LLMMetadataReturns
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
customerIdstring
The customer identifier.
stringReturns
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
customerUserIdstring
The customer user identifier.
stringReturns
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
sessionIdstring
The session identifier.
stringReturns
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
keystring
stringvaluestring
stringReturns
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
tagsstring | string[]
A single tag string or an array of tag strings.
string | 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
optionsAsyncEvaluateOptions
Evaluation options. judge is required; example is optional evaluation data.
AsyncEvaluateOptionsReturns
void