---
title: Tracer
seo:
  title: Tracer — TypeScript SDK
  description: Concrete tracer implementation for Node.js applications. (TypeScript SDK)
description: 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.

```typescript
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

| Prop | Type | Default | Description |
| - | - | - | - |
| `projectName?` | `string \| null` | - | |
| `projectId?` | `string \| null` | - | |
| `apiKey?` | `string \| null` | - | |
| `organizationId?` | `string \| null` | - | |
| `apiUrl?` | `string \| null` | - | |
| `environment?` | `string \| null` | - | |
| `serializer?` | `Serializer` | - | |
| `supportsLiveInstrumentation?` | `boolean` | `true` | |

***

<Badge>
  Static Method
</Badge>

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

```typescript
const tracer = await Tracer.init({
  projectName: "my-project",
  environment: "production",
});
```

```typescript
async function init(config: TracerConfig = {}): Promise<Tracer>
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `config?` | `TracerConfig` | `{}` | Tracer configuration options. |

### Returns

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

***

## getSpanExporter()

Get or create the span exporter for this tracer.

```typescript
function getSpanExporter(): JudgmentSpanExporter
```

### Returns

`JudgmentSpanExporter` - The span exporter instance.

***

## getSpanProcessor()

Get or create the span processor for this tracer.

```typescript
function getSpanProcessor(): JudgmentSpanProcessor
```

### Returns

`JudgmentSpanProcessor` - The span processor instance.

***

## setActive()

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

```typescript
function setActive(): boolean
```

### Returns

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

***

<Badge>
  Static Method
</Badge>

## getCurrentSpan()

Get the currently active span.

```typescript
function getCurrentSpan(): Span | undefined
```

### Returns

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

***

<Badge>
  Static Method
</Badge>

## forceFlush()

Flush all pending spans to the export endpoint.

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

```typescript
await Tracer.forceFlush();
```

```typescript
async function forceFlush(): Promise<void>
```

### Returns

`Promise<void>`

***

<Badge>
  Static Method
</Badge>

## shutdown()

Shut down the tracer and flush any pending data.

```typescript
await Tracer.shutdown();
```

```typescript
async function shutdown(): Promise<void>
```

### Returns

`Promise<void>`

***

<Badge>
  Static Method
</Badge>

## registerOTELInstrumentation()

Register an OpenTelemetry instrumentation to capture spans automatically.

```typescript
import { OpenAIInstrumentation } from "@opentelemetry/instrumentation-openai";
Tracer.registerOTELInstrumentation(new OpenAIInstrumentation());
```

```typescript
function registerOTELInstrumentation(instrumentor: Instrumentation<InstrumentationConfig>): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `instrumentor` | `Instrumentation<InstrumentationConfig>` | - | The OpenTelemetry instrumentation to register. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

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

```typescript
import OpenAI from "openai";

const client = Tracer.wrap(new OpenAI());
```

```typescript
function wrap(client: T): T
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `client` | `T` | - | An LLM client instance (e.g. new OpenAI()). |

### Returns

`T` - The same client instance, instrumented.

***

<Badge>
  Static Method
</Badge>

## getOTELTracer()

Get the underlying OpenTelemetry Tracer instance.

```typescript
function getOTELTracer(): Tracer
```

### Returns

`Tracer` - The OpenTelemetry `Tracer`.

***

<Badge>
  Static Method
</Badge>

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

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

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `name` | `string` | - | The span name. |
| `attributes?` | `Attributes \| undefined` | - | Optional span attributes. |

### Returns

`Span` - The created span.

***

<Badge>
  Static Method
</Badge>

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

```typescript
Tracer.startActiveSpan({ name: "fetch-user" }, (span) => {
  // ...
});
```

```typescript
function startActiveSpan(options: { name: string; attributes?: Attributes; }, fn: (span: Span) => T): T
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `options` | `{ name: string; attributes?: Attributes; }` | - | Span options. name is required; attributes is optional. |
| `fn` | `(span: Span) => T` | - | Function to execute within the span context. |

### Returns

`T` - The return value of `fn`.

***

<Badge>
  Static Method
</Badge>

## span()

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

Errors are recorded on the span and re-thrown.

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

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `spanName` | `string` | - | The span name. |
| `fn` | `(span: Span) => T` | - | Function to execute within the span. |

### Returns

`T` - The return value of `fn`.

***

<Badge>
  Static Method
</Badge>

## with()

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

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

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `spanName` | `string` | - | The span name. |
| `fn` | `(span: Span) => T` | - | Function to execute within the span. |

### Returns

`T` - The return value of `fn`.

***

<Badge>
  Static Method
</Badge>

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

```typescript
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):

```typescript
import { propagation } from "judgeval";

const headers: Record<string, string> = {};
propagation.inject(headers);
await fetch(downstreamUrl, { headers, method: "POST", body });
```

```typescript
function continueTrace(carrier: object, fn: (ctx: Context) => T): T
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `carrier` | `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` | `(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`.

***

<Badge>
  Static Method
</Badge>

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

```typescript
// 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,
});
```

```typescript
function observe(func: (...args: TArgs) => TReturn, options?: ObserveOptions | undefined): (...args: TArgs) => TReturn
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `func` | `(...args: TArgs) => TReturn` | - | The function to wrap. Omit to get a decorator. |
| `options?` | `ObserveOptions \| undefined` | - | Optional observation options. |

### Returns

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

***

<Badge>
  Static Method
</Badge>

## setSpanKind()

Set the kind of a span.

```typescript
function setSpanKind(kind: string): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `kind` | `string` | - | The span kind (e.g. "llm", "tool", "span"). |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## setLLMSpan()

Set the current span kind to "llm".

```typescript
function setLLMSpan(): void
```

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## setToolSpan()

Set the current span kind to "tool".

```typescript
function setToolSpan(): void
```

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## setGeneralSpan()

Set the current span kind to "span".

```typescript
function setGeneralSpan(): void
```

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## setAttribute()

Set a single attribute on a span.

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

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `key` | `string` | - | The attribute key. |
| `value` | `unknown` | - | The attribute value (will be serialized). |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## setAttributes()

Set multiple attributes on a span.

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

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `attributes` | `Record<string, unknown>` | - | Key-value pairs to set. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## setInput()

Set the input data on a span.

```typescript
function setInput(inputData: unknown): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `inputData` | `unknown` | - | The input data to record. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## setOutput()

Set the output data on a span.

```typescript
function setOutput(outputData: unknown): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `outputData` | `unknown` | - | The output data to record. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## setError()

Record an error on a span.

Sets the span status to ERROR and records the exception.

```typescript
function setError(error: unknown): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `error` | `unknown` | - | The error to record. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## recordLLMMetadata()

Record LLM usage metadata on a span.

```typescript
Tracer.recordLLMMetadata({
  model: "gpt-4o",
  provider: "openai",
  output_tokens: 150,
});
```

```typescript
function recordLLMMetadata(metadata: LLMMetadata): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `metadata` | `LLMMetadata` | - | LLM metadata including model, provider, and token counts. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

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

```typescript
function setCustomerId(customerId: string): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `customerId` | `string` | - | The customer identifier. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

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

```typescript
function setCustomerUserId(customerUserId: string): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `customerUserId` | `string` | - | The customer user identifier. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

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

```typescript
function setSessionId(sessionId: string): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `sessionId` | `string` | - | The session identifier. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

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

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

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `key` | `string` | - | |
| `value` | `string` | - | |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

## tag()

Add tags to the current trace.

```typescript
Tracer.tag("production");
Tracer.tag(["important", "customer-facing"]);
```

```typescript
function tag(tags: string | string[]): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `tags` | `string \| string[]` | - | A single tag string or an array of tag strings. |

### Returns

`void`

***

<Badge>
  Static Method
</Badge>

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

```typescript
Tracer.asyncEvaluate({
  judge: "answer_relevancy",
  example: {
    input: "What is AI?",
    actual_output: response,
  },
});
```

```typescript
function asyncEvaluate(options: AsyncEvaluateOptions): void
```

### Parameters

| Prop | Type | Default | Description |
| - | - | - | - |
| `options` | `AsyncEvaluateOptions` | - | Evaluation options. judge is required; example is optional evaluation data. |

### Returns

`void`
