Logging is an important aspect of software development, especially for debugging and monitoring the behavior of your applications. In this section, we’ll explore Effect’s logging utilities and see how they compare to traditional logging methods.
Advantages Over Traditional Logging
Effect’s logging utilities provide several benefits over conventional logging approaches:
Dynamic Log Level Control: With Effect’s logging, you have the ability to change the log level dynamically. This means you can control which log messages get displayed based on their severity. For example, you can configure your application to log only warnings or errors, which can be extremely helpful in production environments to reduce noise.
Custom Logging Output: Effect’s logging utilities allow you to change how logs are handled. You can direct log messages to various destinations, such as a service or a file, using a custom logger. This flexibility ensures that logs are stored and processed in a way that best suits your application’s requirements.
Fine-Grained Logging: Effect enables fine-grained control over logging on a per-part basis of your program. You can set different log levels for different parts of your application, tailoring the level of detail to each specific component. This can be invaluable for debugging and troubleshooting, as you can focus on the information that matters most.
Environment-Based Logging: Effect’s logging utilities can be combined with deployment environments to achieve granular logging strategies. For instance, during development, you might choose to log everything at a trace level and above for detailed debugging. In contrast, your production version could be configured to log only errors or critical issues, minimizing the impact on performance and noise in production logs.
Additional Features: Effect’s logging utilities come with additional features such as the ability to measure time spans, alter log levels on a per-effect basis, and integrate spans for performance monitoring.
log
The Effect.log function allows you to log a message at the default INFO level.
Example (Logging a Simple Message)
The default logger in Effect adds several useful details to each log entry:
Annotation
Description
timestamp
The timestamp when the log message was generated.
level
The log level at which the message is logged (e.g., INFO, ERROR).
fiber
The identifier of the fiber executing the program.
message
The log message content, which can include multiple strings or values.
span
(Optional) The duration of a span in milliseconds, providing insight into the timing of operations.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
For added context, you can also include one or more Cause instances in your logs,
which provide detailed error information under an additional cause annotation:
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
By default, DEBUG messages are not displayed. To enable DEBUG logs, you can adjust the logging configuration using Logger.withMinimumLogLevel, setting the minimum level to LogLevel.Debug.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
timestamp=... level=INFO message=done <-- 3 seconds later
15
*/
logWarning
The WARN log level is displayed by default. This level is intended for potential issues or warnings that do not immediately disrupt the flow of the program but should be monitored.
Creates an Effect that represents a recoverable error.
When to Use
Use this function to explicitly signal an error in an Effect. The error
will keep propagating unless it is handled. You can handle the error with
functions like
catchAll
or
catchTag
.
@see ― succeed to create an effect that represents a successful value.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Transforms an Effect into one that encapsulates both success and failure
using the Either data type.
Details
either takes an effect that could potentially fail and converts it
into an effect that always succeeds but with the result inside an Either.
The Either can either be a Left (representing failure) or a Right
(representing success). This allows you to handle both cases explicitly
without causing the effect to fail.
The resulting effect cannot fail because failure is now represented inside
the Either type.
@see ― option for a version that uses Option instead.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
Creates an Effect that represents a recoverable error.
When to Use
Use this function to explicitly signal an error in an Effect. The error
will keep propagating unless it is handled. You can handle the error with
functions like
catchAll
or
catchTag
.
@see ― succeed to create an effect that represents a successful value.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Transforms an Effect into one that encapsulates both success and failure
using the Either data type.
Details
either takes an effect that could potentially fail and converts it
into an effect that always succeeds but with the result inside an Either.
The Either can either be a Left (representing failure) or a Right
(representing success). This allows you to handle both cases explicitly
without causing the effect to fail.
The resulting effect cannot fail because failure is now represented inside
the Either type.
@see ― option for a version that uses Option instead.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
Creates an Effect that represents a recoverable error.
When to Use
Use this function to explicitly signal an error in an Effect. The error
will keep propagating unless it is handled. You can handle the error with
functions like
catchAll
or
catchTag
.
@see ― succeed to create an effect that represents a successful value.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Transforms an Effect into one that encapsulates both success and failure
using the Either data type.
Details
either takes an effect that could potentially fail and converts it
into an effect that always succeeds but with the result inside an Either.
The Either can either be a Left (representing failure) or a Right
(representing success). This allows you to handle both cases explicitly
without causing the effect to fail.
The resulting effect cannot fail because failure is now represented inside
the Either type.
@see ― option for a version that uses Option instead.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
You can enhance your log outputs by adding custom annotations using the Effect.annotateLogs function. This allows you to attach extra metadata to each log entry, making it easier to trace and add context to your logs.
Enhance your log outputs by incorporating custom annotations with the Effect.annotateLogs function.
This function allows you to append additional metadata to each log entry of an effect, enhancing traceability and context.
Adding a Single Annotation
You can apply a single annotation as a key/value pair to all log entries within an effect.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
constannotateLogs: (key:string, value:unknown) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+3overloads)
Augments log outputs by appending custom annotations to log entries generated
within an effect. This function provides a way to add more context and detail
to log messages, making them more informative and easier to trace.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.log("message1")
yield* Effect.log("message2")
}).pipe(Effect.annotateLogs("key", "value")) // Annotation as key/value pair
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
In this example, all logs generated within the program will include the annotation key=value.
Adding Multiple Annotations
You can also apply multiple annotations at once by passing an object with key/value pairs. Each key/value pair will be added to every log entry within the effect.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
constannotateLogs: (values:Record<string, unknown>) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+3overloads)
Augments log outputs by appending custom annotations to log entries generated
within an effect. This function provides a way to add more context and detail
to log messages, making them more informative and easier to trace.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.log("message1")
yield* Effect.log("message2")
}).pipe(Effect.annotateLogs("key", "value")) // Annotation as key/value pair
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
In this case, each log will contain both key1=value1 and key2=value2.
Scoped Annotations
If you want to limit the scope of your annotations so that they only apply to certain log entries, you can use Effect.annotateLogsScoped. This function confines the annotations to logs produced within a specific scope.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Applies log annotations with a limited scope, restricting their appearance to
specific sections of your effect computations. Use
annotateLogsScoped to add metadata to logs that only appear within a
defined Scope, making it easier to manage context-specific logging.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
constscoped: <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, Exclude<R, Scope>>
Scopes all resources used in this workflow to the lifetime of the workflow,
ensuring that their finalizers are run as soon as this workflow completes
execution, whether by success, failure, or interruption.
@since ― 2.0.0
scoped,
10
// Outside scope, no annotations
11
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect.
constandThen: <Effect.Effect<void, never, never>>(f:Effect.Effect<void, never, never>) => <A, E, R>(self:Effect.Effect<A, E, R>) =>Effect.Effect<void, E, R> (+3overloads)
Chains two actions, where the second action can depend on the result of the
first.
Use andThen when you need to run multiple actions in sequence, with the
second action depending on the result of the first. This is useful for
combining effects or handling computations that must happen in order.
Details
The second action can be:
A constant value (similar to
as
)
A function returning a value (similar to
map
)
A Promise
A function returning a Promise
An Effect
A function returning an Effect (similar to
flatMap
)
Note:andThen works well with both Option and Either types,
treating them as effects.
@example
// Title: Applying a Discount Based on Fetched Amount
import { pipe, Effect } from"effect"
// Function to apply a discount safely to a transaction amount
constapplyDiscount= (
total:number,
discountRate:number
):Effect.Effect<number, Error> =>
discountRate ===0
? Effect.fail(newError("Discount rate cannot be zero"))
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
Effect provides built-in support for log spans, which allow you to measure and log the duration of specific tasks or sections of your code. This feature is helpful for tracking how long certain operations take, giving you better insights into the performance of your application.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
constwithLogSpan: (label:string) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+1overload)
Adds a log span to your effects, which tracks and logs the duration of
operations or tasks. This is useful for performance monitoring and debugging
time-sensitive processes.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.sleep("1 second")
yield* Effect.log("The job is finished!")
}).pipe(Effect.withLogSpan("myspan"))
// Effect.runFork(program)
// timestamp=... level=INFO fiber=#0 message="The job is finished!" myspan=1011ms
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
timestamp=... level=INFO fiber=#0 message="The job is finished!" myspan=1011ms
18
*/
Disabling Default Logging
Sometimes, perhaps during test execution, you might want to disable default logging in your application. Effect provides several ways to turn off logging when needed. In this section, we’ll look at different methods to disable logging in the Effect framework.
Example (Using Logger.withMinimumLogLevel)
One convenient way to disable logging is by using the Logger.withMinimumLogLevel function. This allows you to set the minimum log level to None, effectively turning off all log output.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
@since ― 2.0.0
sleep("100 millis")
6
var console:Console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
@since ― 2.0.0
sleep("100 millis")
6
var console:Console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
@since ― 2.0.0
sleep("100 millis")
6
var console:Console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
Executes the effect using the provided Scheduler or using the global
Scheduler if not provided
runFork(
constprogram:Effect.Effect<void, never, never>
program)
16
/*
17
Output:
18
task done
19
*/
Loading the Log Level from Configuration
To dynamically load the log level from a configuration and apply it to your program, you can use the Logger.minimumLogLevel layer. This allows your application to adjust its logging behavior based on external configuration.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Use andThen when you need to run multiple actions in sequence, with the
second action depending on the result of the first. This is useful for
combining effects or handling computations that must happen in order.
Details
The second action can be:
A constant value (similar to
as
)
A function returning a value (similar to
map
)
A Promise
A function returning a Promise
An Effect
A function returning an Effect (similar to
flatMap
)
Note:andThen works well with both Option and Either types,
treating them as effects.
@example
// Title: Applying a Discount Based on Fetched Amount
import { pipe, Effect } from"effect"
// Function to apply a discount safely to a transaction amount
constapplyDiscount= (
total:number,
discountRate:number
):Effect.Effect<number, Error> =>
discountRate ===0
? Effect.fail(newError("Discount rate cannot be zero"))
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
In this section, you’ll learn how to define a custom logger and set it as the default logger in your application. Custom loggers give you control over how log messages are handled, such as routing them to external services, writing to files, or formatting logs in a specific way.
Defining a Custom Logger
You can define your own logger using the Logger.make function. This function allows you to specify how log messages should be processed.
Example (Defining a Simple Custom Logger)
1
import {
import Logger
Logger } from"effect"
2
3
// Custom logger that outputs log messages to the console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
To replace the default logger with your custom logger, you can use the Logger.replace function. After creating a layer that replaces the default logger, you provide it to your program using Effect.provide.
Example (Replacing the Default Logger with a Custom Logger)
1
import {
import Effect
@since ― 2.0.0
@since ― 2.0.0
@since ― 2.0.0
Effect,
import Logger
Logger,
import LogLevel
LogLevel } from"effect"
2
21 collapsed lines
3
// Custom logger that outputs log messages to the console
The console module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
A global console instance configured to write to process.stdout and
process.stderr. The global console can be used without importing the node:console module.
Warning: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(newError('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
constname='Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console class:
constout=getStreamSomehow();
consterr=getStreamSomehow();
constmyConsole=new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(newError('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
Prints to stdout with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3)
(the arguments are all passed to util.format()).
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to Use
gen allows you to write code that looks and behaves like synchronous
code, but it can handle asynchronous tasks, errors, and complex control flow
(like loops and conditions). It helps make asynchronous code more readable
and easier to manage.
The generator functions work similarly to async/await but with more
explicit control over the execution of effects. You can yield* values from
effects and return the final result at the end.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
// timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users"
// []
@since ― 2.0.0
provide(
constlayer:Layer<never, never, never>
layer)
32
)
33
)
When you run the above program, the following log messages are printed to the console:
Terminal window
[INFO] start
[DEBUG] task1 done
[DEBUG] task2 done
[INFO] done
Built-in Loggers
Effect provides several built-in loggers that you can use depending on your logging needs. These loggers offer different formats, each suited for different environments or purposes, such as development, production, or integration with external logging services.
logFmt (default)
The logFmt logger outputs logs in a human-readable key-value format. This format is often used in development and production for its simplicity and readability in the console.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
constannotateLogs: (values:Record<string, unknown>) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+3overloads)
Augments log outputs by appending custom annotations to log entries generated
within an effect. This function provides a way to add more context and detail
to log messages, making them more informative and easier to trace.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.log("message1")
yield* Effect.log("message2")
}).pipe(Effect.annotateLogs("key", "value")) // Annotation as key/value pair
constwithLogSpan: (label:string) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+1overload)
Adds a log span to your effects, which tracks and logs the duration of
operations or tasks. This is useful for performance monitoring and debugging
time-sensitive processes.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.sleep("1 second")
yield* Effect.log("The job is finished!")
}).pipe(Effect.withLogSpan("myspan"))
// Effect.runFork(program)
// timestamp=... level=INFO fiber=#0 message="The job is finished!" myspan=1011ms
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
The pretty logger enhances log output by using color and indentation for better readability, making it particularly useful during development when visually scanning logs in the console.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
constannotateLogs: (values:Record<string, unknown>) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+3overloads)
Augments log outputs by appending custom annotations to log entries generated
within an effect. This function provides a way to add more context and detail
to log messages, making them more informative and easier to trace.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.log("message1")
yield* Effect.log("message2")
}).pipe(Effect.annotateLogs("key", "value")) // Annotation as key/value pair
constwithLogSpan: (label:string) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+1overload)
Adds a log span to your effects, which tracks and logs the duration of
operations or tasks. This is useful for performance monitoring and debugging
time-sensitive processes.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.sleep("1 second")
yield* Effect.log("The job is finished!")
}).pipe(Effect.withLogSpan("myspan"))
// Effect.runFork(program)
// timestamp=... level=INFO fiber=#0 message="The job is finished!" myspan=1011ms
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
// timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users"
// []
@since ― 2.0.0
provide(
import Logger
Logger.
constpretty:Layer<never, never, never>
The pretty logger utilizes the capabilities of the console API to generate
visually engaging and color-enhanced log outputs. This feature is
particularly useful for improving the readability of log messages during
development and debugging processes.
The structured logger provides highly structured logs. This format is useful for situations that require detailed traceability of events, often in environments where logs are processed and analyzed by automated systems.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
constannotateLogs: (values:Record<string, unknown>) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+3overloads)
Augments log outputs by appending custom annotations to log entries generated
within an effect. This function provides a way to add more context and detail
to log messages, making them more informative and easier to trace.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.log("message1")
yield* Effect.log("message2")
}).pipe(Effect.annotateLogs("key", "value")) // Annotation as key/value pair
constwithLogSpan: (label:string) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+1overload)
Adds a log span to your effects, which tracks and logs the duration of
operations or tasks. This is useful for performance monitoring and debugging
time-sensitive processes.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.sleep("1 second")
yield* Effect.log("The job is finished!")
}).pipe(Effect.withLogSpan("myspan"))
// Effect.runFork(program)
// timestamp=... level=INFO fiber=#0 message="The job is finished!" myspan=1011ms
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.
// timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users"
// []
@since ― 2.0.0
provide(
import Logger
Logger.
conststructured:Layer<never, never, never>
The structured logger provides detailed log outputs, structured in a way that
retains comprehensive traceability of the events, suitable for deeper
analysis and troubleshooting.
Logs one or more messages or error causes at the current log level, which is INFO by default.
This function allows logging multiple items at once and can include detailed error information using Cause instances.
To adjust the log level, use the Logger.withMinimumLogLevel function.
constannotateLogs: (values:Record<string, unknown>) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+3overloads)
Augments log outputs by appending custom annotations to log entries generated
within an effect. This function provides a way to add more context and detail
to log messages, making them more informative and easier to trace.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.log("message1")
yield* Effect.log("message2")
}).pipe(Effect.annotateLogs("key", "value")) // Annotation as key/value pair
constwithLogSpan: (label:string) => <A, E, R>(effect:Effect.Effect<A, E, R>) =>Effect.Effect<A, E, R> (+1overload)
Adds a log span to your effects, which tracks and logs the duration of
operations or tasks. This is useful for performance monitoring and debugging
time-sensitive processes.
@example
import { Effect } from"effect"
constprogram= Effect.gen(function*() {
yield* Effect.sleep("1 second")
yield* Effect.log("The job is finished!")
}).pipe(Effect.withLogSpan("myspan"))
// Effect.runFork(program)
// timestamp=... level=INFO fiber=#0 message="The job is finished!" myspan=1011ms
The foundational function for running effects, returning a "fiber" that can
be observed or interrupted.
When to Use
runFork is used to run an effect in the background by creating a
fiber. It is the base function for all other run functions. It starts a fiber
that can be observed or interrupted.
Unless you specifically need a Promise or synchronous operation,
runFork is a good default choice.