Skip to content

Logging

Effect logging emits structured records as Effects—run them with try inside effect code. The active runtime configuration (minimum level, annotations, log spans, and logger destinations) travels with the fiber and determines what gets formatted and where it goes.

Built-in observability: Logging, Metrics, and TracingBuilt-in observability: Logging, Metrics, and Tracing
Built-in observability: Logging, Metrics, and Tracing

Emitting structured records

effect function reportProgress() {
  try log("export started", { format: "csv", stage: "prepare" })
  try logInfo("export completed", { rows: 240 })
}
 
effect function stringify(value: unknown) {
  return try Effect.try(() => JSON.stringify(value))
}
 
// Run in an effect function:
//   const records: unknown[] = []
//   const capture = Logger.make(({ logLevel, message }) => { records.push([logLevel, message]) })
//   provide Logger.layer([capture]) { try reportProgress() }
//   {
//     const jsonValue = records
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
[["Info",["export started",{"format":"csv","stage":"prepare"}]],["Info",["export completed",{"rows":240}]]]

log and logInfo emit at Info severity and accept multiple message strings or structured objects. Default output attaches timestamp, severity, and fiber ID automatically. When logging a failure, pass the Cause value alongside your message rather than flattening it to a string so stack traces and defects stay intact.

Selecting severity thresholds

effect function diagnostics() {
  provide References.MinimumLogLevel = "Debug" {
    try logTrace("entered parser")
    try logDebug("parsed header")
    try logInfo("input accepted")
    try logWarning("using fallback settings")
    try logError("destination unavailable")
    try logFatal("application cannot start")
  }
}
// Run in an effect function:
//   const records: unknown[] = []
//   const capture = Logger.make(({ logLevel, message }) => { records.push([logLevel, message]) })
//   provide Logger.layer([capture]) { try diagnostics() }
//   {
//     const jsonValue = records
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
[["Debug",["parsed header"]],["Info",["input accepted"]],["Warn",["using fallback settings"]],["Error",["destination unavailable"]],["Fatal",["application cannot start"]]]

The default References.MinimumLogLevel is "Info", which drops Debug and Trace records. Overriding it to "Debug" inside a provide block enables Debug for that block (and its child fibers) while keeping Trace suppressed. Severity is purely metadata: logFatal records a fatal event without failing or terminating the fiber.

Annotating logs and scoped regions

effect function annotatedExport() {
  try annotateLogs(effect {
    try logInfo("preparing")
    try annotateLogs(logInfo("writing"), "stage", "write")
  }, { operation: "weekly-export", format: "csv" })
  try logInfo("outside annotated operation")
}
 
effect function scopedAnnotations() {
  try scoped(effect {
    try annotateLogsScoped({ component: "importer" })
    try logInfo("reading input")
    try logInfo("validating rows")
  })
  try logInfo("outside importer scope")
}
// Run in an effect function:
//   const records: unknown[] = []
//   const capture = Logger.make(({ message, fiber }) => { records.push([message, fiber.getRef(References.CurrentLogAnnotations)]) })
//   provide Logger.layer([capture]) {
//     try annotatedExport()
//     try scopedAnnotations()
//   }
//   {
//     const jsonValue = records
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
[[["preparing"],{"operation":"weekly-export","format":"csv"}],[["writing"],{"operation":"weekly-export","format":"csv","stage":"write"}],[["outside annotated operation"],{}],[["reading input"],{"component":"importer"}],[["validating rows"],{"component":"importer"}],[["outside importer scope"],{}]]

annotateLogs attaches key-value metadata to every log emitted inside its program, including nested calls and forked children. annotateLogsScoped binds annotations to the enclosing runtime Scope; plain { ... } braces do not introduce a Scope, so wrap the region in try scoped(effect { ... }).

Measuring log spans

effect function timedExport() {
  try withLogSpan(effect {
    try logInfo("opening output")
    try sleep("30 millis")
    try logInfo("output written")
  }, "write-output")
}
// Run in an effect function:
//   const records: unknown[] = []
//   const capture = Logger.make(({ message, fiber, date }) => { records.push([message, fiber.getRef(References.CurrentLogSpans).map(([label, start]) => [label, date.getTime() - start])]) })
//   provide TestClock.layer() {
//     try TestClock.setTime(0)
//     provide Logger.layer([capture]) {
//       const worker = fork timedExport()
//       try TestClock.adjust("30 millis")
//       join worker
//     }
//   }
//   {
//     const jsonValue = records
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
[[["opening output"],[["write-output",0]]],[["output written"],[["write-output",30]]]]

withLogSpan tags every log record inside its body with the elapsed milliseconds since the span started. Log spans enrich log entries only; for parent-child trees and OTLP export, use tracing spans (withSpan).

Disabling and configuring logging

const Silent = Layer.succeed(References.MinimumLogLevel, "None")
const LogLevel = Config.LogLevel("LOG_LEVEL")
 
const ConfiguredLevel = Layer.unwrap(effect {
  const minimum = try LogLevel
  return Layer.succeed(References.MinimumLogLevel, minimum)
})
 
effect function quiet() {
  provide Silent { try logInfo("suppressed") }
}
 
effect function configured() {
  provide ConfiguredLevel { try logDebug("configuration loaded") }
}
// Run in an effect function:
//   const records: unknown[] = []
//   const capture = Logger.make(({ logLevel, message }) => { records.push([logLevel, message]) })
//   provide Logger.layer([capture]) {
//     try quiet()
//     provide ConfigProvider.layer(ConfigProvider.fromUnknown({ LOG_LEVEL: "Debug" })) { try configured() }
//   }
//   {
//     const jsonValue = records
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
[["Debug",["configuration loaded"]]]

Setting MinimumLogLevel to "None" silences logging for its region. Config.LogLevel("LOG_LEVEL") validates the level when ConfiguredLevel builds, failing fast at startup on invalid values. Install logging layers once at the application entry point (or in a shared ManagedRuntime).

Defining a custom output handler

effect function captureLogs() {
  const records: Array<{ level: string; message: unknown }> = []
  const capture = Logger.make(({ logLevel, message }) => {
    records.push({ level: logLevel, message })
  })
  provide Logger.layer([capture, Logger.tracerLogger]) {
    try logInfo("batch accepted", { count: 3 })
    try logWarning("one retry required")
  }
  return records
}
// Run in an effect function:
//   {
//     const jsonValue = try captureLogs()
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
[{"level":"Info","message":["batch accepted",{"count":3}]},{"level":"Warn","message":["one retry required"]}]

Logger.make wraps a synchronous callback receiving { logLevel, message, cause, fiber, date }. Because it executes synchronously during log emission, keep it non-blocking (for example, in-memory capture in tests); route asynchronous shipping through an exporter layer instead.

Choosing text, structured, and JSON formats

const TextLogs = Logger.layer([Logger.consoleLogFmt, Logger.tracerLogger])
const PrettyLogs = Logger.layer([Logger.consolePretty(), Logger.tracerLogger])
const ObjectLogs = Logger.layer([Logger.consoleStructured, Logger.tracerLogger])
const JsonLogs = Logger.layer([Logger.consoleJson, Logger.tracerLogger])
 
effect function jsonExample() {
  provide JsonLogs { try logInfo("started", { workers: 4 }) }
}
// Run in an effect function:
//   const lines: string[] = []
//   const original = try Console.Console
//   try provideService(jsonExample(), Console.Console, { ...original, log: (line: string) => { lines.push(line) } })
//   const records = try Effect.forEach(lines, (line) => Effect.try(() => JSON.parse(line)))
//   {
//     const jsonValue = records.map((record) => [record.level, record.message])
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
[["INFO",["started",{"workers":4}]]]
Console loggerPure formatterOutput shape
Logger.defaultLoggerLogger.formatSimpleReadable single-line text
Logger.consoleLogFmtLogger.formatLogFmtCompact key=value logfmt
Logger.consolePretty()—Colorized multi-line output for local terminals
Logger.consoleStructuredLogger.formatStructuredStructured JS object (message, level, timestamp, annotations, cause, spans, fiber)
Logger.consoleJsonLogger.formatJsonSerialized JSON string for log aggregators

Use the format* loggers when delivering formatted payloads to a custom sink rather than Console.

Sending records to multiple destinations

effect function consoleAndCapture() {
  const auditMessages: unknown[] = []
  const audit = Logger.make(({ message }) => { auditMessages.push(message) })
  const destinations = Logger.layer([
    Logger.defaultLogger,
    audit,
    Logger.tracerLogger
  ])
  provide destinations { try logInfo("job finished") }
  return auditMessages
}
// Run in an effect function:
//   const lines: unknown[][] = []
//   const original = try Console.Console
//   const audit = try provideService(consoleAndCapture(), Console.Console, { ...original, log: (...args: ReadonlyArray<unknown>) => { lines.push([...args]) } })
//   try Console.log(try stringify(audit), lines.length, (try stringify(lines)).includes("job finished"))
[["job finished"]] 1 true

Every active logger receives each record passing the severity threshold. Logger.layer([...]) replaces the active logger set; pass { mergeWithExisting: true } to append instead. Keep Logger.tracerLogger in the list so logs emitted inside a tracing span are also recorded as span events.


The matching Effect page: effect.website/docs/v4/observability/logging