TracerA tracing backend used by Effect to create spans. Custom tracers implement
span to allocate a span from the supplied name, parent, annotations,
links, start time, kind, root flag, and sampling decision.
export interface Tracer {
Tracer.span(this: Tracer, options: { readonly name: string; readonly parent: Option.Option<AnySpan>; readonly annotations: Context.Context<never>; readonly links: Array<SpanLink>; readonly startTime: bigint; readonly kind: SpanKind; readonly root: boolean; readonly sampled: boolean }): Spanspan(this: Tracer(parameter) this: {
span: (this: Tracer, options: { readonly name: string; readonly parent: Option.Option<AnySpan>; readonly annotations: Context.Context<never>; readonly links: Array<SpanLink>; readonly startTime: bigint; readonly kind: SpanKind; readonly root: bo…;
context: (<X>(primitive: EffectPrimitive<X>, fiber: Fiber<any, any>) => X) | undefined;
}
this: Tracer, options: {
readonly name: string
readonly parent: Option.Option<AnySpan>
readonly annotations: Context.Context<never>
readonly links: Array<SpanLink>
readonly startTime: bigint
readonly kind: SpanKind
readonly root: boolean
readonly sampled: boolean
}
options: {
readonly name: stringname: string
readonly parent: Option.Option<AnySpan>parent: import OptionOption.type Option<A> = Option.None<A> | Option.Some<A>The Option data type represents optional values. An Option<A> is either
Some<A>, containing a value of type A, or None, representing absence.
When to use
Use to represent initial values that may not yet exist
- Returning from partial functions (not defined for all inputs)
- Managing optional fields in data structures
Namespace containing utility types for Option.
When to use
Use to access type-level helpers associated with Option.
Option<type AnySpan = Span | ExternalSpanA span value that can participate in tracing, either an Effect-managed
Span or an ExternalSpan propagated from another tracing system.
Example (Accepting any span)
import { Effect, Tracer } from "effect"
// Function that accepts any span type
const logSpan = (span: Tracer.AnySpan) => {
console.log(`Span ID: ${span.spanId}, Trace ID: ${span.traceId}`)
return Effect.succeed(span)
}
// Works with both Span and ExternalSpan
const externalSpan = Tracer.externalSpan({
spanId: "span-123",
traceId: "trace-456"
})
AnySpan>
readonly annotations: Context.Context<never>(property) annotations: {
mapUnsafe: ReadonlyMap<string, any>;
mutable: boolean;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
annotations: import ContextContext.interface Context<in Services>Immutable collection of service implementations used for dependency
injection in Effect programs.
Details
The type parameter tracks the service identifiers available in the context.
At runtime, services are stored by each key's string key.
Example (Creating a context with multiple services)
import { Context } from "effect"
// Create a context with multiple services
const Logger = Context.Service<{ log: (msg: string) => void }>("Logger")
const Database = Context.Service<{ query: (sql: string) => string }>(
"Database"
)
const context = Context.make(Logger, {
log: (msg: string) => console.log(msg)
})
.pipe(Context.add(Database, { query: (sql) => `Result: ${sql}` }))
Context<never>
readonly links: Array<SpanLink>links: interface Array<T>Array<SpanLink>
readonly startTime: bigintstartTime: bigint
readonly kind: SpanKindkind: type SpanKind =
| "internal"
| "server"
| "client"
| "producer"
| "consumer"
OpenTelemetry-style role describing the kind of operation represented by a
span: internal work, server handling, client calls, producing, or consuming.
Example (Configuring span kinds)
import { Effect } from "effect"
import type { Tracer } from "effect"
// Different span kinds for different operations
const serverSpan = Effect.withSpan("handle-request", {
kind: "server" as Tracer.SpanKind
})
const clientSpan = Effect.withSpan("api-call", {
kind: "client" as Tracer.SpanKind
})
const internalSpan = Effect.withSpan("internal-process", {
kind: "internal" as Tracer.SpanKind
})
SpanKind
readonly root: booleanroot: boolean
readonly sampled: booleansampled: boolean
}): Span
readonly Tracer.context?: (<X>(primitive: EffectPrimitive<X>, fiber: Fiber<any, any>) => X) | undefinedcontext?:
| (<function (type parameter) X in <X>(primitive: EffectPrimitive<X>, fiber: Fiber<any, any>): XX>(primitive: EffectPrimitive<X>primitive: interface EffectPrimitive<X>A low-level Effect primitive that can be evaluated by a tracer-specific
context for the current fiber.
EffectPrimitive<function (type parameter) X in <X>(primitive: EffectPrimitive<X>, fiber: Fiber<any, any>): XX>, fiber: Fiber<any, any>(parameter) fiber: {
id: number;
currentOpCount: number;
getRef: <A>(ref: Context.Reference<A>) => A;
context: Context.Context<never>;
setContext: (context: Context.Context<never>) => void;
currentScheduler: Scheduler;
currentDispatcher: SchedulerDispatcher;
currentSpan: AnySpan | undefined;
currentLogLevel: LogLevel;
minimumLogLevel: LogLevel;
currentStackFrame: StackFrame | undefined;
maxOpsBeforeYield: number;
currentPreventYield: boolean;
addObserver: (cb: (exit: Exit<A, E>) => void) => () => void;
interruptUnsafe: (fiberId?: number | undefined, annotations?: Context.Context<never> | undefined) => void;
pollUnsafe: () => Exit<A, E> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
fiber: interface Fiber<out A, out E = never>A runtime fiber is a lightweight thread that executes Effects. Fibers are
the unit of concurrency in Effect. They provide a way to run multiple
Effects concurrently while maintaining structured concurrency and
cancellation safety.
When to use
Use to observe, join, interrupt, or coordinate work that has already been
forked.
Details
A fiber exposes both safe Effect-based operations, such as
await
,
join
, and
interrupt
, and low-level runtime fields used by
the scheduler and runtime internals.
Gotchas
Prefer the exported functions in this module over calling interruptUnsafe
or pollUnsafe directly. The unsafe methods are immediate runtime hooks and
do not provide the same Effect-based sequencing guarantees.
Example (Awaiting a forked fiber)
import { Effect, Fiber } from "effect"
const program = Effect.gen(function*() {
// Fork an effect to run in a new fiber
const fiber = yield* Effect.forkChild(Effect.succeed(42))
// Wait for the fiber to complete and get its result
const result = yield* Fiber.await(fiber)
console.log(result) // Exit.succeed(42)
return result
})
The Fiber namespace contains utility types and functions for working with fibers.
It provides type-level utilities for fiber operations and variance encoding.
When to use
Use to reference type-level helpers associated with Fiber.
Details
The namespace currently exposes type-level support used by the Fiber
interface. Runtime operations are exported as module-level functions.
Example (Working with fiber types)
import { Effect, Fiber } from "effect"
const program = Effect.gen(function*() {
// Create a fiber
const fiber = yield* Effect.forkChild(Effect.succeed(42))
// Use namespace types for variance
const typedFiber: Fiber.Fiber<number, never> = fiber
// Access fiber properties
console.log(`Fiber ID: ${fiber.id}`)
// Join the fiber
const result = yield* Fiber.join(fiber)
return result // 42
})
Fiber<any, any>) => function (type parameter) X in <X>(primitive: EffectPrimitive<X>, fiber: Fiber<any, any>): XX)
| undefined
}
const const evaluate: "~effect/Effect/evaluate"evaluate = "~effect/Effect/evaluate" satisfies import corecore.type evaluate = "~effect/Effect/evaluate"evaluate
/**
* A low-level Effect primitive that can be evaluated by a tracer-specific
* context for the current fiber.
*
* @category models
* @since 4.0.0
*/
export interface interface EffectPrimitive<X>A low-level Effect primitive that can be evaluated by a tracer-specific
context for the current fiber.
EffectPrimitive<function (type parameter) X in EffectPrimitive<X>X> {
[const evaluate: "~effect/Effect/evaluate"evaluate](this: EffectPrimitive<X>this: interface EffectPrimitive<X>A low-level Effect primitive that can be evaluated by a tracer-specific
context for the current fiber.
EffectPrimitive<function (type parameter) X in EffectPrimitive<X>X>, fiber: Fiber<any, any>(parameter) fiber: {
id: number;
currentOpCount: number;
getRef: <A>(ref: Context.Reference<A>) => A;
context: Context.Context<never>;
setContext: (context: Context.Context<never>) => void;
currentScheduler: Scheduler;
currentDispatcher: SchedulerDispatcher;
currentSpan: AnySpan | undefined;
currentLogLevel: LogLevel;
minimumLogLevel: LogLevel;
currentStackFrame: StackFrame | undefined;
maxOpsBeforeYield: number;
currentPreventYield: boolean;
addObserver: (cb: (exit: Exit<A, E>) => void) => () => void;
interruptUnsafe: (fiberId?: number | undefined, annotations?: Context.Context<never> | undefined) => void;
pollUnsafe: () => Exit<A, E> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
fiber: interface Fiber<out A, out E = never>A runtime fiber is a lightweight thread that executes Effects. Fibers are
the unit of concurrency in Effect. They provide a way to run multiple
Effects concurrently while maintaining structured concurrency and
cancellation safety.
When to use
Use to observe, join, interrupt, or coordinate work that has already been
forked.
Details
A fiber exposes both safe Effect-based operations, such as
await
,
join
, and
interrupt
, and low-level runtime fields used by
the scheduler and runtime internals.
Gotchas
Prefer the exported functions in this module over calling interruptUnsafe
or pollUnsafe directly. The unsafe methods are immediate runtime hooks and
do not provide the same Effect-based sequencing guarantees.
Example (Awaiting a forked fiber)
import { Effect, Fiber } from "effect"
const program = Effect.gen(function*() {
// Fork an effect to run in a new fiber
const fiber = yield* Effect.forkChild(Effect.succeed(42))
// Wait for the fiber to complete and get its result
const result = yield* Fiber.await(fiber)
console.log(result) // Exit.succeed(42)
return result
})
The Fiber namespace contains utility types and functions for working with fibers.
It provides type-level utilities for fiber operations and variance encoding.
When to use
Use to reference type-level helpers associated with Fiber.
Details
The namespace currently exposes type-level support used by the Fiber
interface. Runtime operations are exported as module-level functions.
Example (Working with fiber types)
import { Effect, Fiber } from "effect"
const program = Effect.gen(function*() {
// Create a fiber
const fiber = yield* Effect.forkChild(Effect.succeed(42))
// Use namespace types for variance
const typedFiber: Fiber.Fiber<number, never> = fiber
// Access fiber properties
console.log(`Fiber ID: ${fiber.id}`)
// Join the fiber
const result = yield* Fiber.join(fiber)
return result // 42
})
Fiber<any, any>): function (type parameter) X in EffectPrimitive<X>X
}
/**
* Lifecycle state of a span, where `Started` records the start time and
* `Ended` records the start time, end time, and exit value with which the span
* completed.
*
* **Example** (Creating span statuses)
*
* ```ts
* import { Exit } from "effect"
* import type { Tracer } from "effect"
*
* const startTime = 1_000_000_000n
* const endTime = 1_500_000_000n
*
* const startedStatus: Tracer.SpanStatus = {
* _tag: "Started",
* startTime
* }
*
* const endedStatus: Tracer.SpanStatus = {
* _tag: "Ended",
* startTime,
* endTime,
* exit: Exit.succeed("result")
* }
*
* console.log(startedStatus._tag) // "Started"
* console.log(endedStatus.endTime - endedStatus.startTime) // 500000000n
* ```
*
* @category models
* @since 2.0.0
*/
export type type SpanStatus =
| {
_tag: "Started"
startTime: bigint
}
| {
_tag: "Ended"
startTime: bigint
endTime: bigint
exit: Exit.Exit<unknown, unknown>
}
Lifecycle state of a span, where Started records the start time and
Ended records the start time, end time, and exit value with which the span
completed.
Example (Creating span statuses)
import { Exit } from "effect"
import type { Tracer } from "effect"
const startTime = 1_000_000_000n
const endTime = 1_500_000_000n
const startedStatus: Tracer.SpanStatus = {
_tag: "Started",
startTime
}
const endedStatus: Tracer.SpanStatus = {
_tag: "Ended",
startTime,
endTime,
exit: Exit.succeed("result")
}
console.log(startedStatus._tag) // "Started"
console.log(endedStatus.endTime - endedStatus.startTime) // 500000000n
SpanStatus = {
_tag: "Started"_tag: "Started"
startTime: bigintstartTime: bigint
} | {
_tag: "Ended"_tag: "Ended"
startTime: bigintstartTime: bigint
endTime: bigintendTime: bigint
exit: Exit.Exit<unknown, unknown>exit: import ExitExit.type Exit<A, E = never> = Exit.Success<A, E> | Exit.Failure<A, E>Represents the result of an Effect computation.
When to use
Use when you need to synchronously inspect whether an Effect computation
succeeded or failed.
Details
An Exit<A, E> is either Success<A, E> containing a value of type A, or
Failure<A, E> containing a Cause<E> describing why the computation
failed.
Since Exit is also an Effect, you can yield it inside Effect.gen.
Example (Pattern matching on an Exit)
import { Exit } from "effect"
const success: Exit.Exit<number> = Exit.succeed(42)
const failure: Exit.Exit<number, string> = Exit.fail("error")
const result = Exit.match(success, {
onSuccess: (value) => `Got value: ${value}`,
onFailure: (cause) => `Got error: ${cause}`
})
Namespace containing helper types shared by Exit values.
When to use
Use to reference helper types that describe the shared structure of Exit
values.
Exit<unknown, unknown>
}
/**
* A span value that can participate in tracing, either an Effect-managed
* `Span` or an `ExternalSpan` propagated from another tracing system.
*
* **Example** (Accepting any span)
*
* ```ts
* import { Effect, Tracer } from "effect"
*
* // Function that accepts any span type
* const logSpan = (span: Tracer.AnySpan) => {
* console.log(`Span ID: ${span.spanId}, Trace ID: ${span.traceId}`)
* return Effect.succeed(span)
* }
*
* // Works with both Span and ExternalSpan
* const externalSpan = Tracer.externalSpan({
* spanId: "span-123",
* traceId: "trace-456"
* })
* ```
*
* @category models
* @since 2.0.0
*/
export type type AnySpan = Span | ExternalSpanA span value that can participate in tracing, either an Effect-managed
Span or an ExternalSpan propagated from another tracing system.
Example (Accepting any span)
import { Effect, Tracer } from "effect"
// Function that accepts any span type
const logSpan = (span: Tracer.AnySpan) => {
console.log(`Span ID: ${span.spanId}, Trace ID: ${span.traceId}`)
return Effect.succeed(span)
}
// Works with both Span and ExternalSpan
const externalSpan = Tracer.externalSpan({
spanId: "span-123",
traceId: "trace-456"
})
AnySpan = Span | ExternalSpan
/**
* Defines the string key for the parent-span context service.
*
* **When to use**
*
* Use when you need the raw context key for parent span lookup in lower-level
* tracing code.
*
* **Example** (Reading the parent span key)
*
* ```ts
* import { Tracer } from "effect"
*
* // The key used to identify parent spans in the context
* console.log(Tracer.ParentSpanKey) // "effect/Tracer/ParentSpan"
* ```
*
* @category constants
* @since 4.0.0
*/
export const const ParentSpanKey: "effect/Tracer/ParentSpan"Defines the string key for the parent-span context service.
When to use
Use when you need the raw context key for parent span lookup in lower-level
tracing code.
Example (Reading the parent span key)
import { Tracer } from "effect"
// The key used to identify parent spans in the context
console.log(Tracer.ParentSpanKey) // "effect/Tracer/ParentSpan"
ParentSpanKey = "effect/Tracer/ParentSpan"
/**
* Context service containing the `Span` or `ExternalSpan` to use as the parent
* of newly-created child spans.
*
* **Example** (Accessing the parent span)
*
* ```ts
* import { Effect, Tracer } from "effect"
*
* // Access the parent span from the context
* const program = Effect.gen(function*() {
* const parentSpan = yield* Effect.service(Tracer.ParentSpan)
* console.log(`Parent span: ${parentSpan.spanId}`)
* })
* ```
*
* @category services
* @since 2.0.0
*/
export class class ParentSpanclass ParentSpan {
Service: Service;
key: Identifier;
}
Context service containing the Span or ExternalSpan to use as the parent
of newly-created child spans.
Example (Accessing the parent span)
import { Effect, Tracer } from "effect"
// Access the parent span from the context
const program = Effect.gen(function*() {
const parentSpan = yield* Effect.service(Tracer.ParentSpan)
console.log(`Parent span: ${parentSpan.spanId}`)
})
ParentSpan extends import ContextContext.const Service: {
<Identifier, Shape = Identifier>(
key: string
): Service<Identifier, Shape>
<Self, Shape>(): <
Identifier extends string,
E,
R = Types.unassigned,
Args extends ReadonlyArray<any> = never
>(
id: Identifier,
options?:
| {
readonly make:
| ((
...args: Args
) => Effect<Shape, E, R>)
| Effect<Shape, E, R>
| undefined
}
| undefined
) => ServiceClass<Self, Identifier, Shape> &
([Types.unassigned] extends [R]
? unknown
: {
readonly make: [Args] extends [never]
? Effect<Shape, E, R>
: (
...args: Args
) => Effect<Shape, E, R>
})
<Self>(): <
Identifier extends string,
Make extends
| Effect<any, any, any>
| ((...args: any) => Effect<any, any, any>)
>(
id: Identifier,
options: { readonly make: Make }
) => ServiceClass<
Self,
Identifier,
Make extends
| Effect<infer _A, infer _E, infer _R>
| ((
...args: infer _Args
) => Effect<infer _A, infer _E, infer _R>)
? _A
: never
> & { readonly make: Make }
}
Service<class ParentSpanclass ParentSpan {
Service: Service;
key: Identifier;
}
Context service containing the Span or ExternalSpan to use as the parent
of newly-created child spans.
Example (Accessing the parent span)
import { Effect, Tracer } from "effect"
// Access the parent span from the context
const program = Effect.gen(function*() {
const parentSpan = yield* Effect.service(Tracer.ParentSpan)
console.log(`Parent span: ${parentSpan.spanId}`)
})
ParentSpan, type AnySpan = Span | ExternalSpanA span value that can participate in tracing, either an Effect-managed
Span or an ExternalSpan propagated from another tracing system.
Example (Accepting any span)
import { Effect, Tracer } from "effect"
// Function that accepts any span type
const logSpan = (span: Tracer.AnySpan) => {
console.log(`Span ID: ${span.spanId}, Trace ID: ${span.traceId}`)
return Effect.succeed(span)
}
// Works with both Span and ExternalSpan
const externalSpan = Tracer.externalSpan({
spanId: "span-123",
traceId: "trace-456"
})
AnySpan>()(const ParentSpanKey: "effect/Tracer/ParentSpan"Defines the string key for the parent-span context service.
When to use
Use when you need the raw context key for parent span lookup in lower-level
tracing code.
Example (Reading the parent span key)
import { Tracer } from "effect"
// The key used to identify parent spans in the context
console.log(Tracer.ParentSpanKey) // "effect/Tracer/ParentSpan"
ParentSpanKey) {}
/**
* Represents a span created outside Effect's tracer, carrying trace and span
* identifiers, sampling state, and annotations so it can be used as a parent or
* link in Effect tracing.
*
* **Example** (Creating an external span value)
*
* ```ts
* import { Context } from "effect"
* import type { Tracer } from "effect"
*
* // Create an external span from another tracing system
* const externalSpan: Tracer.ExternalSpan = {
* _tag: "ExternalSpan",
* spanId: "span-abc-123",
* traceId: "trace-xyz-789",
* sampled: true,
* annotations: Context.empty()
* }
*
* console.log(`External span: ${externalSpan.spanId}`)
* ```
*
* @category models
* @since 2.0.0
*/
export interface ExternalSpan {
readonly ExternalSpan._tag: "ExternalSpan"_tag: "ExternalSpan"
readonly ExternalSpan.spanId: stringspanId: string
readonly ExternalSpan.traceId: stringtraceId: string
readonly ExternalSpan.sampled: booleansampled: boolean
readonly ExternalSpan.annotations: Context.Context<never>(property) ExternalSpan.annotations: {
mapUnsafe: ReadonlyMap<string, any>;
mutable: boolean;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
annotations: import ContextContext.interface Context<in Services>Immutable collection of service implementations used for dependency
injection in Effect programs.
Details
The type parameter tracks the service identifiers available in the context.
At runtime, services are stored by each key's string key.
Example (Creating a context with multiple services)
import { Context } from "effect"
// Create a context with multiple services
const Logger = Context.Service<{ log: (msg: string) => void }>("Logger")
const Database = Context.Service<{ query: (sql: string) => string }>(
"Database"
)
const context = Context.make(Logger, {
log: (msg: string) => console.log(msg)
})
.pipe(Context.add(Database, { query: (sql) => `Result: ${sql}` }))
Context<never>
}
/**
* Options accepted by span-creating APIs, combining span metadata such as
* attributes, links, parent/root selection, kind, sampling, and trace level
* with stack trace capture settings.
*
* **Example** (Configuring span options)
*
* ```ts
* import { Effect } from "effect"
* import type { Tracer } from "effect"
*
* // Create an effect with span options
* const options: Tracer.SpanOptions = {
* attributes: { "user.id": "123", "operation": "data-processing" },
* kind: "internal",
* root: false,
* captureStackTrace: true
* }
*
* const program = Effect.succeed("Hello World").pipe(
* Effect.withSpan("my-operation", options)
* )
* ```
*
* @category options
* @since 3.1.0
*/
export interface SpanOptions extends SpanOptionsNoTrace, TraceOptions {}
/**
* Span creation options that do not control stack trace capture, including
* attributes, links, parent or root selection, annotations, span kind,
* sampling, and the trace level used for filtering.
*
* @category options
* @since 4.0.0
*/
export interface SpanOptionsNoTrace {
readonly SpanOptionsNoTrace.attributes?: Record<string, unknown> | undefinedattributes?: type Record<K extends keyof any, T> = {
[P in K]: T
}
Construct a type with a set of properties K of type T
Record<string, unknown> | undefined
readonly SpanOptionsNoTrace.links?: ReadonlyArray<SpanLink> | undefinedlinks?: interface ReadonlyArray<T>ReadonlyArray<SpanLink> | undefined
readonly SpanOptionsNoTrace.parent?: AnySpan | undefinedparent?: type AnySpan = Span | ExternalSpanA span value that can participate in tracing, either an Effect-managed
Span or an ExternalSpan propagated from another tracing system.
Example (Accepting any span)
import { Effect, Tracer } from "effect"
// Function that accepts any span type
const logSpan = (span: Tracer.AnySpan) => {
console.log(`Span ID: ${span.spanId}, Trace ID: ${span.traceId}`)
return Effect.succeed(span)
}
// Works with both Span and ExternalSpan
const externalSpan = Tracer.externalSpan({
spanId: "span-123",
traceId: "trace-456"
})
AnySpan | undefined
readonly SpanOptionsNoTrace.root?: boolean | undefinedroot?: boolean | undefined
readonly SpanOptionsNoTrace.annotations?: Context.Context<never> | undefinedannotations?: import ContextContext.interface Context<in Services>Immutable collection of service implementations used for dependency
injection in Effect programs.
Details
The type parameter tracks the service identifiers available in the context.
At runtime, services are stored by each key's string key.
Example (Creating a context with multiple services)
import { Context } from "effect"
// Create a context with multiple services
const Logger = Context.Service<{ log: (msg: string) => void }>("Logger")
const Database = Context.Service<{ query: (sql: string) => string }>(
"Database"
)
const context = Context.make(Logger, {
log: (msg: string) => console.log(msg)
})
.pipe(Context.add(Database, { query: (sql) => `Result: ${sql}` }))
Context<never> | undefined
readonly SpanOptionsNoTrace.kind?: SpanKind | undefinedkind?: type SpanKind =
| "internal"
| "server"
| "client"
| "producer"
| "consumer"
OpenTelemetry-style role describing the kind of operation represented by a
span: internal work, server handling, client calls, producing, or consuming.
Example (Configuring span kinds)
import { Effect } from "effect"
import type { Tracer } from "effect"
// Different span kinds for different operations
const serverSpan = Effect.withSpan("handle-request", {
kind: "server" as Tracer.SpanKind
})
const clientSpan = Effect.withSpan("api-call", {
kind: "client" as Tracer.SpanKind
})
const internalSpan = Effect.withSpan("internal-process", {
kind: "internal" as Tracer.SpanKind
})
SpanKind | undefined
readonly SpanOptionsNoTrace.sampled?: boolean | undefinedsampled?: boolean | undefined
readonly SpanOptionsNoTrace.level?: LogLevel | undefinedlevel?: type LogLevel = "All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None"Represents every level used by Effect logging, including concrete message
severities and the All and None sentinel levels.
When to use
Use to type values that may be either concrete log message severities or
logging configuration sentinels.
Details
The levels are ordered from most severe to least severe:
All - Special level that allows all messages
Fatal - System is unusable, immediate attention required
Error - Error conditions that should be investigated
Warn - Warning conditions that may indicate problems
Info - Informational messages about normal operation
Debug - Debug information useful during development
Trace - Very detailed trace information
None - Special level that suppresses all messages
Example (Using log levels)
import { Effect } from "effect"
// Using log levels with Effect logging
const program = Effect.gen(function*() {
yield* Effect.logFatal("System failure")
yield* Effect.logError("Database error")
yield* Effect.logWarning("High memory usage")
yield* Effect.logInfo("User logged in")
yield* Effect.logDebug("Processing request")
yield* Effect.logTrace("Variable state")
})
// Type-safe log level variables
const errorLevel = "Error" // LogLevel
const debugLevel = "Debug" // LogLevel
LogLevel | undefined
}
/**
* Options that control stack trace capture for tracing wrappers.
* `captureStackTrace` can disable capture or provide a lazy stack string.
*
* @category options
* @since 4.0.0
*/
export interface TraceOptions {
readonly TraceOptions.captureStackTrace?: boolean | LazyArg<string | undefined> | undefinedcaptureStackTrace?: boolean | type LazyArg<A> = () => AA zero-argument function that produces a value when invoked.
When to use
Use to type a lazy value provider that should not run until called.
Example (Creating a lazy argument)
import { Function } from "effect"
const constNull: Function.LazyArg<null> = Function.constant(null)
LazyArg<string | undefined> | undefined
}
/**
* OpenTelemetry-style role describing the kind of operation represented by a
* span: internal work, server handling, client calls, producing, or consuming.
*
* **Example** (Configuring span kinds)
*
* ```ts
* import { Effect } from "effect"
* import type { Tracer } from "effect"
*
* // Different span kinds for different operations
* const serverSpan = Effect.withSpan("handle-request", {
* kind: "server" as Tracer.SpanKind
* })
*
* const clientSpan = Effect.withSpan("api-call", {
* kind: "client" as Tracer.SpanKind
* })
*
* const internalSpan = Effect.withSpan("internal-process", {
* kind: "internal" as Tracer.SpanKind
* })
* ```
*
* @category models
* @since 3.1.0
*/
export type type SpanKind =
| "internal"
| "server"
| "client"
| "producer"
| "consumer"
OpenTelemetry-style role describing the kind of operation represented by a
span: internal work, server handling, client calls, producing, or consuming.
Example (Configuring span kinds)
import { Effect } from "effect"
import type { Tracer } from "effect"
// Different span kinds for different operations
const serverSpan = Effect.withSpan("handle-request", {
kind: "server" as Tracer.SpanKind
})
const clientSpan = Effect.withSpan("api-call", {
kind: "client" as Tracer.SpanKind
})
const internalSpan = Effect.withSpan("internal-process", {
kind: "internal" as Tracer.SpanKind
})
SpanKind = "internal" | "server" | "client" | "producer" | "consumer"
/**
* A span created by an Effect tracer. It carries trace identity, parent,
* annotations, attributes, links, sampling and kind information, lifecycle
* status, and methods to end the span or add attributes, events, and links.
*
* **Example** (Working with spans)
*
* ```ts
* import { Context, Exit, Option } from "effect"
* import type { Tracer } from "effect"
*
* const attributes = new Map<string, unknown>()
* const links: Array<Tracer.SpanLink> = []
* let status: Tracer.SpanStatus = {
* _tag: "Started",
* startTime: 1_000_000_000n
* }
*
* const span: Tracer.Span = {
* _tag: "Span",
* name: "load-user",
* spanId: "span-1",
* traceId: "trace-1",
* parent: Option.none(),
* annotations: Context.empty(),
* get status() {
* return status
* },
* attributes,
* links,
* sampled: true,
* kind: "internal",
* end(endTime, exit) {
* status = { _tag: "Ended", startTime: status.startTime, endTime, exit }
* },
* attribute(key, value) {
* attributes.set(key, value)
* },
* event(name, startTime, eventAttributes = {}) {
* console.log(`${name} at ${startTime} with ${Object.keys(eventAttributes).length} attributes`)
* },
* addLinks(newLinks) {
* links.push(...newLinks)
* }
* }
*
* span.attribute("user.id", "123")
* span.end(1_500_000_000n, Exit.succeed("user"))
*
* console.log(span.name) // "load-user"
* console.log(span.attributes.get("user.id")) // "123"
* console.log(span.status._tag) // "Ended"
* ```
*
* @category models
* @since 2.0.0
*/
export interface Span {
readonly Span._tag: "Span"_tag: "Span"
readonly Span.name: stringname: string
readonly Span.spanId: stringspanId: string
readonly Span.traceId: stringtraceId: string
readonly Span.parent: Option.Option<AnySpan>parent: import OptionOption.type Option<A> = Option.None<A> | Option.Some<A>The Option data type represents optional values. An Option<A> is either
Some<A>, containing a value of type A, or None, representing absence.
When to use
Use to represent initial values that may not yet exist
- Returning from partial functions (not defined for all inputs)
- Managing optional fields in data structures
Namespace containing utility types for Option.
When to use
Use to access type-level helpers associated with Option.
Option<type AnySpan = Span | ExternalSpanA span value that can participate in tracing, either an Effect-managed
Span or an ExternalSpan propagated from another tracing system.
Example (Accepting any span)
import { Effect, Tracer } from "effect"
// Function that accepts any span type
const logSpan = (span: Tracer.AnySpan) => {
console.log(`Span ID: ${span.spanId}, Trace ID: ${span.traceId}`)
return Effect.succeed(span)
}
// Works with both Span and ExternalSpan
const externalSpan = Tracer.externalSpan({
spanId: "span-123",
traceId: "trace-456"
})
AnySpan>
readonly Span.annotations: Context.Context<never>(property) Span.annotations: {
mapUnsafe: ReadonlyMap<string, any>;
mutable: boolean;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
annotations: import ContextContext.interface Context<in Services>Immutable collection of service implementations used for dependency
injection in Effect programs.
Details
The type parameter tracks the service identifiers available in the context.
At runtime, services are stored by each key's string key.
Example (Creating a context with multiple services)
import { Context } from "effect"
// Create a context with multiple services
const Logger = Context.Service<{ log: (msg: string) => void }>("Logger")
const Database = Context.Service<{ query: (sql: string) => string }>(
"Database"
)
const context = Context.make(Logger, {
log: (msg: string) => console.log(msg)
})
.pipe(Context.add(Database, { query: (sql) => `Result: ${sql}` }))
Context<never>
readonly Span.status: SpanStatusstatus: type SpanStatus =
| {
_tag: "Started"
startTime: bigint
}
| {
_tag: "Ended"
startTime: bigint
endTime: bigint
exit: Exit.Exit<unknown, unknown>
}
Lifecycle state of a span, where Started records the start time and
Ended records the start time, end time, and exit value with which the span
completed.
Example (Creating span statuses)
import { Exit } from "effect"
import type { Tracer } from "effect"
const startTime = 1_000_000_000n
const endTime = 1_500_000_000n
const startedStatus: Tracer.SpanStatus = {
_tag: "Started",
startTime
}
const endedStatus: Tracer.SpanStatus = {
_tag: "Ended",
startTime,
endTime,
exit: Exit.succeed("result")
}
console.log(startedStatus._tag) // "Started"
console.log(endedStatus.endTime - endedStatus.startTime) // 500000000n
SpanStatus
readonly Span.attributes: ReadonlyMap<string, unknown>attributes: interface ReadonlyMap<K, V>ReadonlyMap<string, unknown>
readonly Span.links: ReadonlyArray<SpanLink>links: interface ReadonlyArray<T>ReadonlyArray<SpanLink>
readonly Span.sampled: booleansampled: boolean
readonly Span.kind: SpanKindkind: type SpanKind =
| "internal"
| "server"
| "client"
| "producer"
| "consumer"
OpenTelemetry-style role describing the kind of operation represented by a
span: internal work, server handling, client calls, producing, or consuming.
Example (Configuring span kinds)
import { Effect } from "effect"
import type { Tracer } from "effect"
// Different span kinds for different operations
const serverSpan = Effect.withSpan("handle-request", {
kind: "server" as Tracer.SpanKind
})
const clientSpan = Effect.withSpan("api-call", {
kind: "client" as Tracer.SpanKind
})
const internalSpan = Effect.withSpan("internal-process", {
kind: "internal" as Tracer.SpanKind
})
SpanKind
Span.end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): voidend(endTime: bigintendTime: bigint, exit: Exit.Exit<unknown, unknown>exit: import ExitExit.type Exit<A, E = never> = Exit.Success<A, E> | Exit.Failure<A, E>Represents the result of an Effect computation.
When to use
Use when you need to synchronously inspect whether an Effect computation
succeeded or failed.
Details
An Exit<A, E> is either Success<A, E> containing a value of type A, or
Failure<A, E> containing a Cause<E> describing why the computation
failed.
Since Exit is also an Effect, you can yield it inside Effect.gen.
Example (Pattern matching on an Exit)
import { Exit } from "effect"
const success: Exit.Exit<number> = Exit.succeed(42)
const failure: Exit.Exit<number, string> = Exit.fail("error")
const result = Exit.match(success, {
onSuccess: (value) => `Got value: ${value}`,
onFailure: (cause) => `Got error: ${cause}`
})
Namespace containing helper types shared by Exit values.
When to use
Use to reference helper types that describe the shared structure of Exit
values.
Exit<unknown, unknown>): void
Span.attribute(key: string, value: unknown): voidattribute(key: stringkey: string, value: unknownvalue: unknown): void
Span.event(name: string, startTime: bigint, attributes?: Record<string, unknown>): voidevent(name: stringname: string, startTime: bigintstartTime: bigint, attributes: Record<string, unknown> | undefinedattributes?: type Record<K extends keyof any, T> = {
[P in K]: T
}
Construct a type with a set of properties K of type T
Record<string, unknown>): void
Span.addLinks(links: ReadonlyArray<SpanLink>): voidaddLinks(links: ReadonlyArray<SpanLink>links: interface ReadonlyArray<T>ReadonlyArray<SpanLink>): void
}
/**
* A relationship from one span to another span, with attributes describing the
* relationship.
*
* **Example** (Linking spans)
*
* ```ts
* import { Effect, Tracer } from "effect"
*
* // Create a span link to connect spans
* const externalSpan = Tracer.externalSpan({
* spanId: "external-span-123",
* traceId: "trace-456"
* })
*
* const link: Tracer.SpanLink = {
* span: externalSpan,
* attributes: { "link.type": "follows-from", "service": "external-api" }
* }
*
* const program = Effect.succeed("result").pipe(
* Effect.withSpan("linked-operation", { links: [link] })
* )
* ```
*
* @category models
* @since 2.0.0
*/
export interface SpanLink {
readonly SpanLink.span: AnySpanspan: type AnySpan = Span | ExternalSpanA span value that can participate in tracing, either an Effect-managed
Span or an ExternalSpan propagated from another tracing system.
Example (Accepting any span)
import { Effect, Tracer } from "effect"
// Function that accepts any span type
const logSpan = (span: Tracer.AnySpan) => {
console.log(`Span ID: ${span.spanId}, Trace ID: ${span.traceId}`)
return Effect.succeed(span)
}
// Works with both Span and ExternalSpan
const externalSpan = Tracer.externalSpan({
spanId: "span-123",
traceId: "trace-456"
})
AnySpan
readonly SpanLink.attributes: Readonly<Record<string, unknown>>attributes: type Readonly<T> = {
readonly [P in keyof T]: T[P]
}
Make all properties in T readonly
Readonly<type Record<K extends keyof any, T> = {
[P in K]: T
}
Construct a type with a set of properties K of type T
Record<string, unknown>>
}
/**
* Creates a `Tracer` value from a tracer implementation object.
*
* **When to use**
*
* Use to create a custom tracing backend value that Effect can use when
* creating spans.
*
* **Details**
*
* `make` returns the supplied implementation object unchanged. The object must
* satisfy the `Tracer` contract, including a `span` method that returns a
* `Span`.
*
* @see {@link Span} for the span values returned by tracer implementations
*
* @category constructors
* @since 2.0.0
*/
export const const make: (options: Tracer) => TracerCreates a Tracer value from a tracer implementation object.
When to use
Use to create a custom tracing backend value that Effect can use when
creating spans.
Details
make returns the supplied implementation object unchanged. The object must
satisfy the Tracer contract, including a span method that returns a
Span.
make = (options: Tracer(parameter) options: {
span: (this: Tracer, options: { readonly name: string; readonly parent: Option.Option<AnySpan>; readonly annotations: Context.Context<never>; readonly links: Array<SpanLink>; readonly startTime: bigint; readonly kind: SpanKind; readonly root: bo…;
context: (<X>(primitive: EffectPrimitive<X>, fiber: Fiber<any, any>) => X) | undefined;
}
options: Tracer): Tracer => options: Tracer(parameter) options: {
span: (this: Tracer, options: { readonly name: string; readonly parent: Option.Option<AnySpan>; readonly annotations: Context.Context<never>; readonly links: Array<SpanLink>; readonly startTime: bigint; readonly kind: SpanKind; readonly root: bo…;
context: (<X>(primitive: EffectPrimitive<X>, fiber: Fiber<any, any>) => X) | undefined;
}
options
/**
* Creates an `ExternalSpan` from trace and span identifiers, defaulting
* `sampled` to `true` and annotations to an empty context when they are not
* provided.
*
* **Example** (Creating an external span)
*
* ```ts
* import { Effect, Tracer } from "effect"
*
* // Create an external span from another tracing system
* const span = Tracer.externalSpan({
* spanId: "span-abc-123",
* traceId: "trace-xyz-789",
* sampled: true
* })
*
* // Use the external span as a parent
* const program = Effect.succeed("Hello").pipe(
* Effect.withSpan("child-operation", { parent: span })
* )
* ```
*
* @category constructors
* @since 2.0.0
*/
export const const externalSpan: (options: {
readonly spanId: string
readonly traceId: string
readonly sampled?: boolean | undefined
readonly annotations?:
| Context.Context<never>
| undefined
}) => ExternalSpan
Creates an ExternalSpan from trace and span identifiers, defaulting
sampled to true and annotations to an empty context when they are not
provided.
Example (Creating an external span)
import { Effect, Tracer } from "effect"
// Create an external span from another tracing system
const span = Tracer.externalSpan({
spanId: "span-abc-123",
traceId: "trace-xyz-789",
sampled: true
})
// Use the external span as a parent
const program = Effect.succeed("Hello").pipe(
Effect.withSpan("child-operation", { parent: span })
)
externalSpan = (
options: {
readonly spanId: string
readonly traceId: string
readonly sampled?: boolean | undefined
readonly annotations?:
| Context.Context<never>
| undefined
}
options: {
readonly spanId: stringspanId: string
readonly traceId: stringtraceId: string
readonly sampled?: boolean | undefinedsampled?: boolean | undefined
readonly annotations?: Context.Context<never> | undefinedannotations?: import ContextContext.interface Context<in Services>Immutable collection of service implementations used for dependency
injection in Effect programs.
Details
The type parameter tracks the service identifiers available in the context.
At runtime, services are stored by each key's string key.
Example (Creating a context with multiple services)
import { Context } from "effect"
// Create a context with multiple services
const Logger = Context.Service<{ log: (msg: string) => void }>("Logger")
const Database = Context.Service<{ query: (sql: string) => string }>(
"Database"
)
const context = Context.make(Logger, {
log: (msg: string) => console.log(msg)
})
.pipe(Context.add(Database, { query: (sql) => `Result: ${sql}` }))
Context<never> | undefined
}
): ExternalSpan => ({
ExternalSpan._tag: "ExternalSpan"_tag: "ExternalSpan",
ExternalSpan.spanId: stringspanId: options: {
readonly spanId: string
readonly traceId: string
readonly sampled?: boolean | undefined
readonly annotations?:
| Context.Context<never>
| undefined
}
options.spanId: stringspanId,
ExternalSpan.traceId: stringtraceId: options: {
readonly spanId: string
readonly traceId: string
readonly sampled?: boolean | undefined
readonly annotations?:
| Context.Context<never>
| undefined
}
options.traceId: stringtraceId,
ExternalSpan.sampled: booleansampled: options: {
readonly spanId: string
readonly traceId: string
readonly sampled?: boolean | undefined
readonly annotations?:
| Context.Context<never>
| undefined
}
options.sampled?: boolean | undefinedsampled ?? true,
ExternalSpan.annotations: Context.Context<never>(property) ExternalSpan.annotations: {
mapUnsafe: ReadonlyMap<string, any>;
mutable: boolean;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
annotations: options: {
readonly spanId: string
readonly traceId: string
readonly sampled?: boolean | undefined
readonly annotations?:
| Context.Context<never>
| undefined
}
options.annotations?: Context.Context<never> | undefinedannotations ?? import ContextContext.const empty: () => Context<never>Returns an empty Context.
Example (Creating an empty context)
import { Context } from "effect"
import * as assert from "node:assert"
assert.strictEqual(Context.isContext(Context.empty()), true)
empty()
})
/**
* Context reference for disabling trace propagation.
*
* **When to use**
*
* Use to prevent spans in a scope from propagating tracing context.
*
* **Details**
*
* When enabled on fiber or span annotations, new spans are created as
* non-propagating no-op spans and disabled spans are skipped when deriving a
* parent span.
*
* **Example** (Disabling span propagation)
*
* ```ts
* import { Effect, Tracer } from "effect"
*
* // Disable span propagation for a specific effect
* const program = Effect.gen(function*() {
* yield* Effect.log("This will not propagate parent span")
* }).pipe(
* Effect.provideService(Tracer.DisablePropagation, true)
* )
* ```
*
* @category references
* @since 3.12.0
*/
export const const DisablePropagation: Context.Reference<boolean>const DisablePropagation: {
defaultValue: () => Shape;
of: (this: void, self: boolean) => boolean;
context: (self: boolean) => Context.Context<never>;
use: (f: (service: boolean) => Effect<A, E, R>) => Effect<A, E, R>;
useSync: (f: (service: boolean) => A) => Effect<A, never, never>;
Identifier: Identifier;
Service: Shape;
key: string;
stack: string | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
Context reference for disabling trace propagation.
When to use
Use to prevent spans in a scope from propagating tracing context.
Details
When enabled on fiber or span annotations, new spans are created as
non-propagating no-op spans and disabled spans are skipped when deriving a
parent span.
Example (Disabling span propagation)
import { Effect, Tracer } from "effect"
// Disable span propagation for a specific effect
const program = Effect.gen(function*() {
yield* Effect.log("This will not propagate parent span")
}).pipe(
Effect.provideService(Tracer.DisablePropagation, true)
)
DisablePropagation = import ContextContext.const Reference: <Service>(
key: string,
options: {
readonly defaultValue: () => Service
}
) => Reference<Service>
Creates a context key with a default value.
When to use
Use when you need to define a context key with a lazily computed default
value.
Details
Context.Reference allows you to create a key that can hold a value. You
can provide a default value for the service, which will automatically be used
when the context is accessed, or override it with a custom implementation
when needed. The default value is computed lazily and cached on the
reference.
Example (Creating references with default values)
import { Context } from "effect"
// Create a reference with a default value
const LoggerRef = Context.Reference("Logger", {
defaultValue: () => ({ log: (msg: string) => console.log(msg) })
})
// The reference provides the default value when accessed from an empty context
const context = Context.empty()
const logger = Context.get(context, LoggerRef)
// You can also override the default value
const customContext = Context.make(LoggerRef, {
log: (msg: string) => `Custom: ${msg}`
})
const customLogger = Context.get(customContext, LoggerRef)
Reference<boolean>(
"effect/Tracer/DisablePropagation",
{ defaultValue: LazyArg<boolean>defaultValue: const constFalse: LazyArg<boolean>Returns false when called.
When to use
Use when you need a thunk that returns false on every invocation.
Example (Returning false from a thunk)
import { Function } from "effect"
import * as assert from "node:assert"
assert.deepStrictEqual(Function.constFalse(), false)
constFalse }
)
/**
* Context reference for controlling the current trace level for dynamic filtering.
*
* **When to use**
*
* Use to set the default trace level for spans in a scope when span options do
* not provide `level`.
*
* **Details**
*
* The default value is `"Info"`. Span creation uses `options.level ??
* CurrentTraceLevel` before applying `MinimumTraceLevel`.
*
* @see {@link MinimumTraceLevel} for the threshold that decides whether spans at that level are sampled
*
* @category references
* @since 4.0.0
*/
export const const CurrentTraceLevel: Context.Reference<LogLevel>const CurrentTraceLevel: {
defaultValue: () => Shape;
of: (this: void, self: LogLevel) => LogLevel;
context: (self: LogLevel) => Context.Context<never>;
use: (f: (service: LogLevel) => Effect<A, E, R>) => Effect<A, E, R>;
useSync: (f: (service: LogLevel) => A) => Effect<A, never, never>;
Identifier: Identifier;
Service: Shape;
key: string;
stack: string | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
Context reference for controlling the current trace level for dynamic filtering.
When to use
Use to set the default trace level for spans in a scope when span options do
not provide level.
Details
The default value is "Info". Span creation uses options.level ??
CurrentTraceLevel before applying MinimumTraceLevel.
CurrentTraceLevel: import ContextContext.interface Reference<in out Shape>Service key with a lazily computed default value.
Details
When a Reference is requested from a Context that does not contain an
override, Context getters that resolve references return the cached default
value instead of failing.
Example (Defining a reference with a default value)
import { Context } from "effect"
// Define a reference with a default value
const LoggerRef: Context.Reference<{ log: (msg: string) => void }> =
Context.Reference("Logger", {
defaultValue: () => ({ log: (msg: string) => console.log(msg) })
})
// The reference can be used without explicit provision
const context = Context.empty()
const logger = Context.get(context, LoggerRef) // Uses default value
Creates a context key with a default value.
When to use
Use when you need to define a context key with a lazily computed default
value.
Details
Context.Reference allows you to create a key that can hold a value. You
can provide a default value for the service, which will automatically be used
when the context is accessed, or override it with a custom implementation
when needed. The default value is computed lazily and cached on the
reference.
Example (Creating references with default values)
import { Context } from "effect"
// Create a reference with a default value
const LoggerRef = Context.Reference("Logger", {
defaultValue: () => ({ log: (msg: string) => console.log(msg) })
})
// The reference provides the default value when accessed from an empty context
const context = Context.empty()
const logger = Context.get(context, LoggerRef)
// You can also override the default value
const customContext = Context.make(LoggerRef, {
log: (msg: string) => `Custom: ${msg}`
})
const customLogger = Context.get(customContext, LoggerRef)
Reference<type LogLevel = "All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None"Represents every level used by Effect logging, including concrete message
severities and the All and None sentinel levels.
When to use
Use to type values that may be either concrete log message severities or
logging configuration sentinels.
Details
The levels are ordered from most severe to least severe:
All - Special level that allows all messages
Fatal - System is unusable, immediate attention required
Error - Error conditions that should be investigated
Warn - Warning conditions that may indicate problems
Info - Informational messages about normal operation
Debug - Debug information useful during development
Trace - Very detailed trace information
None - Special level that suppresses all messages
Example (Using log levels)
import { Effect } from "effect"
// Using log levels with Effect logging
const program = Effect.gen(function*() {
yield* Effect.logFatal("System failure")
yield* Effect.logError("Database error")
yield* Effect.logWarning("High memory usage")
yield* Effect.logInfo("User logged in")
yield* Effect.logDebug("Processing request")
yield* Effect.logTrace("Variable state")
})
// Type-safe log level variables
const errorLevel = "Error" // LogLevel
const debugLevel = "Debug" // LogLevel
LogLevel> = import ContextContext.const Reference: <Service>(
key: string,
options: {
readonly defaultValue: () => Service
}
) => Reference<Service>
Creates a context key with a default value.
When to use
Use when you need to define a context key with a lazily computed default
value.
Details
Context.Reference allows you to create a key that can hold a value. You
can provide a default value for the service, which will automatically be used
when the context is accessed, or override it with a custom implementation
when needed. The default value is computed lazily and cached on the
reference.
Example (Creating references with default values)
import { Context } from "effect"
// Create a reference with a default value
const LoggerRef = Context.Reference("Logger", {
defaultValue: () => ({ log: (msg: string) => console.log(msg) })
})
// The reference provides the default value when accessed from an empty context
const context = Context.empty()
const logger = Context.get(context, LoggerRef)
// You can also override the default value
const customContext = Context.make(LoggerRef, {
log: (msg: string) => `Custom: ${msg}`
})
const customLogger = Context.get(customContext, LoggerRef)
Reference<type LogLevel = "All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None"Represents every level used by Effect logging, including concrete message
severities and the All and None sentinel levels.
When to use
Use to type values that may be either concrete log message severities or
logging configuration sentinels.
Details
The levels are ordered from most severe to least severe:
All - Special level that allows all messages
Fatal - System is unusable, immediate attention required
Error - Error conditions that should be investigated
Warn - Warning conditions that may indicate problems
Info - Informational messages about normal operation
Debug - Debug information useful during development
Trace - Very detailed trace information
None - Special level that suppresses all messages
Example (Using log levels)
import { Effect } from "effect"
// Using log levels with Effect logging
const program = Effect.gen(function*() {
yield* Effect.logFatal("System failure")
yield* Effect.logError("Database error")
yield* Effect.logWarning("High memory usage")
yield* Effect.logInfo("User logged in")
yield* Effect.logDebug("Processing request")
yield* Effect.logTrace("Variable state")
})
// Type-safe log level variables
const errorLevel = "Error" // LogLevel
const debugLevel = "Debug" // LogLevel
LogLevel>(
"effect/Tracer/CurrentTraceLevel",
{ defaultValue: () => LogLeveldefaultValue: () => "Info" }
)
/**
* Context reference for setting the minimum trace level threshold. Spans and their
* descendants below this level will have their sampling decision forced to
* false, preventing them from being exported.
*
* **When to use**
*
* Use to set the trace-level threshold that controls whether spans are sampled
* by default.
*
* **Details**
*
* The default value is `"All"`. Span creation compares the span level from
* `options.level ?? CurrentTraceLevel` against this threshold.
*
* **Gotchas**
*
* Explicit `options.sampled` bypasses threshold computation.
*
* @see {@link CurrentTraceLevel} for the default span level used when options do not specify one
*
* @category references
* @since 4.0.0
*/
export const const MinimumTraceLevel: Context.Reference<LogLevel>const MinimumTraceLevel: {
defaultValue: () => Shape;
of: (this: void, self: LogLevel) => LogLevel;
context: (self: LogLevel) => Context.Context<never>;
use: (f: (service: LogLevel) => Effect<A, E, R>) => Effect<A, E, R>;
useSync: (f: (service: LogLevel) => A) => Effect<A, never, never>;
Identifier: Identifier;
Service: Shape;
key: string;
stack: string | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
Context reference for setting the minimum trace level threshold. Spans and their
descendants below this level will have their sampling decision forced to
false, preventing them from being exported.
When to use
Use to set the trace-level threshold that controls whether spans are sampled
by default.
Details
The default value is "All". Span creation compares the span level from
options.level ?? CurrentTraceLevel against this threshold.
Gotchas
Explicit options.sampled bypasses threshold computation.
MinimumTraceLevel = import ContextContext.const Reference: <Service>(
key: string,
options: {
readonly defaultValue: () => Service
}
) => Reference<Service>
Creates a context key with a default value.
When to use
Use when you need to define a context key with a lazily computed default
value.
Details
Context.Reference allows you to create a key that can hold a value. You
can provide a default value for the service, which will automatically be used
when the context is accessed, or override it with a custom implementation
when needed. The default value is computed lazily and cached on the
reference.
Example (Creating references with default values)
import { Context } from "effect"
// Create a reference with a default value
const LoggerRef = Context.Reference("Logger", {
defaultValue: () => ({ log: (msg: string) => console.log(msg) })
})
// The reference provides the default value when accessed from an empty context
const context = Context.empty()
const logger = Context.get(context, LoggerRef)
// You can also override the default value
const customContext = Context.make(LoggerRef, {
log: (msg: string) => `Custom: ${msg}`
})
const customLogger = Context.get(customContext, LoggerRef)
Reference<
type LogLevel = "All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None"Represents every level used by Effect logging, including concrete message
severities and the All and None sentinel levels.
When to use
Use to type values that may be either concrete log message severities or
logging configuration sentinels.
Details
The levels are ordered from most severe to least severe:
All - Special level that allows all messages
Fatal - System is unusable, immediate attention required
Error - Error conditions that should be investigated
Warn - Warning conditions that may indicate problems
Info - Informational messages about normal operation
Debug - Debug information useful during development
Trace - Very detailed trace information
None - Special level that suppresses all messages
Example (Using log levels)
import { Effect } from "effect"
// Using log levels with Effect logging
const program = Effect.gen(function*() {
yield* Effect.logFatal("System failure")
yield* Effect.logError("Database error")
yield* Effect.logWarning("High memory usage")
yield* Effect.logInfo("User logged in")
yield* Effect.logDebug("Processing request")
yield* Effect.logTrace("Variable state")
})
// Type-safe log level variables
const errorLevel = "Error" // LogLevel
const debugLevel = "Debug" // LogLevel
LogLevel
>("effect/Tracer/MinimumTraceLevel", { defaultValue: () => LogLeveldefaultValue: () => "All" })
/**
* Defines the string key for the active tracer context reference.
*
* **When to use**
*
* Use when you need the raw context key for active tracer lookup in lower-level
* tracing code.
*
* @category references
* @since 4.0.0
*/
export const const TracerKey: "effect/Tracer"Defines the string key for the active tracer context reference.
When to use
Use when you need the raw context key for active tracer lookup in lower-level
tracing code.
TracerKey = "effect/Tracer"
/**
* Context reference for the active tracer service. By default it uses the
* native tracer, which creates `NativeSpan` instances.
*
* **Example** (Accessing the current tracer)
*
* ```ts
* import { Effect, Tracer } from "effect"
*
* // Access the current tracer from the context
* const program = Effect.gen(function*() {
* const tracer = yield* Effect.service(Tracer.Tracer)
* console.log("Using current tracer")
* })
*
* // Or use the built-in tracer effect
* const tracerEffect = Effect.gen(function*() {
* const tracer = yield* Effect.tracer
* console.log("Current tracer obtained")
* })
* ```
*
* @category references
* @since 2.0.0
*/
export const const Tracer: Context.Reference<Tracer>const Tracer: {
key: string;
Service: {
span: (this: Tracer, options: { readonly name: string; readonly parent: Option.Option<AnySpan>; readonly annotations: Context.Context<never>; readonly links: Array<SpanLink>; readonly startTime: bigint; readonly kind: SpanKind; readonly root: bo…;
context: (<X>(primitive: EffectPrimitive<X>, fiber: Fiber<any, any>) => X) | undefined;
};
defaultValue: () => Shape;
of: (this: void, self: Tracer) => Tracer;
context: (self: Tracer) => Context.Context<never>;
use: (f: (service: Tracer) => Effect<A, E, R>) => Effect<A, E, R>;
useSync: (f: (service: Tracer) => A) => Effect<A, never, never>;
Identifier: Identifier;
stack: string | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
A tracing backend used by Effect to create spans. Custom tracers implement
span to allocate a span from the supplied name, parent, annotations,
links, start time, kind, root flag, and sampling decision.
Context reference for the active tracer service. By default it uses the
native tracer, which creates NativeSpan instances.
Example (Accessing the current tracer)
import { Effect, Tracer } from "effect"
// Access the current tracer from the context
const program = Effect.gen(function*() {
const tracer = yield* Effect.service(Tracer.Tracer)
console.log("Using current tracer")
})
// Or use the built-in tracer effect
const tracerEffect = Effect.gen(function*() {
const tracer = yield* Effect.tracer
console.log("Current tracer obtained")
})
Tracer: import ContextContext.interface Reference<in out Shape>Service key with a lazily computed default value.
Details
When a Reference is requested from a Context that does not contain an
override, Context getters that resolve references return the cached default
value instead of failing.
Example (Defining a reference with a default value)
import { Context } from "effect"
// Define a reference with a default value
const LoggerRef: Context.Reference<{ log: (msg: string) => void }> =
Context.Reference("Logger", {
defaultValue: () => ({ log: (msg: string) => console.log(msg) })
})
// The reference can be used without explicit provision
const context = Context.empty()
const logger = Context.get(context, LoggerRef) // Uses default value
Creates a context key with a default value.
When to use
Use when you need to define a context key with a lazily computed default
value.
Details
Context.Reference allows you to create a key that can hold a value. You
can provide a default value for the service, which will automatically be used
when the context is accessed, or override it with a custom implementation
when needed. The default value is computed lazily and cached on the
reference.
Example (Creating references with default values)
import { Context } from "effect"
// Create a reference with a default value
const LoggerRef = Context.Reference("Logger", {
defaultValue: () => ({ log: (msg: string) => console.log(msg) })
})
// The reference provides the default value when accessed from an empty context
const context = Context.empty()
const logger = Context.get(context, LoggerRef)
// You can also override the default value
const customContext = Context.make(LoggerRef, {
log: (msg: string) => `Custom: ${msg}`
})
const customLogger = Context.get(customContext, LoggerRef)
Reference<Tracer> = import ContextContext.const Reference: <Service>(
key: string,
options: {
readonly defaultValue: () => Service
}
) => Reference<Service>
Creates a context key with a default value.
When to use
Use when you need to define a context key with a lazily computed default
value.
Details
Context.Reference allows you to create a key that can hold a value. You
can provide a default value for the service, which will automatically be used
when the context is accessed, or override it with a custom implementation
when needed. The default value is computed lazily and cached on the
reference.
Example (Creating references with default values)
import { Context } from "effect"
// Create a reference with a default value
const LoggerRef = Context.Reference("Logger", {
defaultValue: () => ({ log: (msg: string) => console.log(msg) })
})
// The reference provides the default value when accessed from an empty context
const context = Context.empty()
const logger = Context.get(context, LoggerRef)
// You can also override the default value
const customContext = Context.make(LoggerRef, {
log: (msg: string) => `Custom: ${msg}`
})
const customLogger = Context.get(customContext, LoggerRef)
Reference<Tracer>(const TracerKey: "effect/Tracer"Defines the string key for the active tracer context reference.
When to use
Use when you need the raw context key for active tracer lookup in lower-level
tracing code.
TracerKey, {
defaultValue: () => TracerdefaultValue: () =>
const make: (options: Tracer) => TracerCreates a Tracer value from a tracer implementation object.
When to use
Use to create a custom tracing backend value that Effect can use when
creating spans.
Details
make returns the supplied implementation object unchanged. The object must
satisfy the Tracer contract, including a span method that returns a
Span.
make({
Tracer.span(this: Tracer, options: { readonly name: string; readonly parent: Option.Option<AnySpan>; readonly annotations: Context.Context<never>; readonly links: Array<SpanLink>; readonly startTime: bigint; readonly kind: SpanKind; readonly root: boolean; readonly sampled: boolean }): NativeSpanspan: (options: {
readonly name: string
readonly parent: Option.Option<AnySpan>
readonly annotations: Context.Context<never>
readonly links: Array<SpanLink>
readonly startTime: bigint
readonly kind: SpanKind
readonly root: boolean
readonly sampled: boolean
}
options) => new constructor NativeSpan(options: {
readonly name: string;
readonly parent: Option.Option<AnySpan>;
readonly annotations: Context.Context<never>;
readonly links: Array<SpanLink>;
readonly startTime: bigint;
readonly kind: SpanKind;
readonly sampled: boolean;
}): NativeSpan
Default in-memory Span implementation used by the native tracer. It
generates span and trace identifiers, stores attributes, events, and links,
and records Started or Ended status.
Details
The constructor initializes the span with Started status, inherits the
parent trace id or generates a new one, and always generates a new span id.
Attributes, events, links, and status are then mutated through Span methods.
NativeSpan(options: {
readonly name: string
readonly parent: Option.Option<AnySpan>
readonly annotations: Context.Context<never>
readonly links: Array<SpanLink>
readonly startTime: bigint
readonly kind: SpanKind
readonly root: boolean
readonly sampled: boolean
}
options)
})
})