@effect/opentelemetry 4.0.0-beta.7 → 4.0.0-beta.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/Logger.ts CHANGED
@@ -1,33 +1,93 @@
1
1
  /**
2
- * @since 1.0.0
2
+ * Connects Effect's logging system to the OpenTelemetry Logs SDK.
3
+ *
4
+ * This module provides a logger provider service, an Effect `Logger` that
5
+ * emits OpenTelemetry log records, and layers for installing that logger in an
6
+ * application. It is commonly used to send Effect logs to OTLP, console, or
7
+ * vendor-specific exporters through OpenTelemetry `LogRecordProcessor`s while
8
+ * keeping logs correlated with Effect fibers and spans. Emitted records include
9
+ * the current fiber id, span identifiers when a parent span is present, log
10
+ * annotations, log spans, severity text, and the matching OpenTelemetry
11
+ * severity number.
12
+ *
13
+ * Log export depends on the configured OpenTelemetry processors and exporters;
14
+ * this module creates the provider and logger, but does not choose an exporter.
15
+ * Use the `Resource` layer to attach service and deployment metadata to the
16
+ * provider rather than repeating that data on every log record. When using
17
+ * `layerLoggerProvider`, the provider is scoped and is force-flushed and shut
18
+ * down when the layer is released, with a configurable shutdown timeout. If you
19
+ * supply or manage an OpenTelemetry provider yourself, make sure it is flushed
20
+ * and shut down during application shutdown, especially when using batching
21
+ * processors that may otherwise drop buffered logs.
22
+ *
23
+ * @since 4.0.0
3
24
  */
25
+ import { SeverityNumber } from "@opentelemetry/api-logs"
4
26
  import * as Otel from "@opentelemetry/sdk-logs"
5
27
  import type { NonEmptyReadonlyArray } from "effect/Array"
6
28
  import * as Arr from "effect/Array"
7
29
  import * as Clock from "effect/Clock"
30
+ import * as Context from "effect/Context"
8
31
  import type * as Duration from "effect/Duration"
9
32
  import * as Effect from "effect/Effect"
10
33
  import * as Layer from "effect/Layer"
11
34
  import * as Logger from "effect/Logger"
12
- import * as LogLevel from "effect/LogLevel"
35
+ import type * as LogLevel from "effect/LogLevel"
13
36
  import * as Predicate from "effect/Predicate"
14
- import * as ServiceMap from "effect/ServiceMap"
37
+ import * as References from "effect/References"
15
38
  import * as Tracer from "effect/Tracer"
16
- import { unknownToAttributeValue } from "./internal/attributes.ts"
39
+ import { nanosToHrTime, unknownToAttributeValue } from "./internal/attributes.ts"
17
40
  import { Resource } from "./Resource.ts"
18
41
 
19
42
  /**
20
- * @since 1.0.0
21
- * @category Services
43
+ * Context service containing the OpenTelemetry `LoggerProvider` used to emit Effect log records.
44
+ *
45
+ * @category services
46
+ * @since 4.0.0
22
47
  */
23
- export class OtelLoggerProvider extends ServiceMap.Service<
48
+ export class OtelLoggerProvider extends Context.Service<
24
49
  OtelLoggerProvider,
25
50
  Otel.LoggerProvider
26
51
  >()("@effect/opentelemetry/Logger/OtelLoggerProvider") {}
27
52
 
28
53
  /**
29
- * @since 1.0.0
30
- * @category Constructors
54
+ * Maps an Effect `LogLevel` to the corresponding OpenTelemetry `SeverityNumber`.
55
+ *
56
+ * **Details**
57
+ *
58
+ * OpenTelemetry log severity numbers are in the range `1` through `24`. This
59
+ * function maps from Effect's log levels instead of using
60
+ * `LogLevel.getOrdinal`, whose internal sort ordinals, such as the `Info`
61
+ * ordinal `20000`, fall outside the OpenTelemetry logs data model and can be
62
+ * treated as `UNSPECIFIED` by validating backends.
63
+ *
64
+ * @category converting
65
+ * @since 4.0.0
66
+ */
67
+ export const logLevelToSeverityNumber = (level: LogLevel.LogLevel): SeverityNumber => {
68
+ switch (level) {
69
+ case "Trace":
70
+ return SeverityNumber.TRACE
71
+ case "Debug":
72
+ return SeverityNumber.DEBUG
73
+ case "Info":
74
+ return SeverityNumber.INFO
75
+ case "Warn":
76
+ return SeverityNumber.WARN
77
+ case "Error":
78
+ return SeverityNumber.ERROR
79
+ case "Fatal":
80
+ return SeverityNumber.FATAL
81
+ default:
82
+ return SeverityNumber.UNSPECIFIED
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Creates an Effect logger that emits log records through the configured OpenTelemetry logger provider.
88
+ *
89
+ * @category constructors
90
+ * @since 4.0.0
31
91
  */
32
92
  export const make: Effect.Effect<
33
93
  Logger.Logger<unknown, void>,
@@ -43,40 +103,46 @@ export const make: Effect.Effect<
43
103
  fiberId: options.fiber.id
44
104
  }
45
105
 
46
- const span = ServiceMap.getOrUndefined(options.fiber.services, Tracer.ParentSpan)
106
+ const span = Context.getOrUndefined(options.fiber.context, Tracer.ParentSpan)
47
107
 
48
108
  if (Predicate.isNotUndefined(span)) {
49
109
  attributes.spanId = span.spanId
50
110
  attributes.traceId = span.traceId
51
111
  }
52
112
 
53
- // TODO: add back after log spans / annotations
54
- // for (const [key, value] of options.annotations) {
55
- // attributes[key] = unknownToAttributeValue(value)
56
- // }
57
- // const now = options.date.getTime()
58
- // for (const span of options.spans) {
59
- // attributes[`logSpan.${span.label}`] = `${now - span.startTime}ms`
60
- // }
113
+ for (const [key, value] of Object.entries(options.fiber.getRef(References.CurrentLogAnnotations))) {
114
+ attributes[key] = unknownToAttributeValue(value)
115
+ }
116
+ const now = options.date.getTime()
117
+ for (const [label, startTime] of options.fiber.getRef(References.CurrentLogSpans)) {
118
+ attributes[`logSpan.${label}`] = `${now - startTime}ms`
119
+ }
61
120
 
62
121
  const message = Arr.ensure(options.message).map(unknownToAttributeValue)
122
+ const hrTime = nanosToHrTime(clock.currentTimeNanosUnsafe())
63
123
  otelLogger.emit({
64
124
  body: message.length === 1 ? message[0] : message,
65
125
  severityText: options.logLevel,
66
- severityNumber: LogLevel.getOrdinal(options.logLevel),
67
- timestamp: options.date,
68
- observedTimestamp: clock.currentTimeMillisUnsafe(),
126
+ severityNumber: logLevelToSeverityNumber(options.logLevel),
127
+ timestamp: hrTime,
128
+ observedTimestamp: hrTime,
69
129
  attributes
70
130
  })
71
131
  })
72
132
  })
73
133
 
74
134
  /**
75
- * @since 1.0.0
76
- * @category Layers
135
+ * Creates a layer that installs the OpenTelemetry-backed Effect logger, merging with existing loggers by default.
136
+ *
137
+ * @category layers
138
+ * @since 4.0.0
77
139
  */
78
140
  export const layer = (options: {
79
141
  /**
142
+ * Whether to merge the OpenTelemetry logger with existing loggers.
143
+ *
144
+ * **Details**
145
+ *
80
146
  * If set to `true`, the OpenTelemetry logger will be merged with existing
81
147
  * loggers in the application.
82
148
  *
@@ -92,8 +158,10 @@ export const layer = (options: {
92
158
  })
93
159
 
94
160
  /**
95
- * @since 1.0.0
96
- * @category Layers
161
+ * Creates a scoped OpenTelemetry logger provider from one or more log record processors, using the current `Resource` and flushing and shutting down the provider when the layer is released.
162
+ *
163
+ * @category layers
164
+ * @since 4.0.0
97
165
  */
98
166
  export const layerLoggerProvider = (
99
167
  processor: Otel.LogRecordProcessor | NonEmptyReadonlyArray<Otel.LogRecordProcessor>,
package/src/Metrics.ts CHANGED
@@ -1,5 +1,21 @@
1
1
  /**
2
- * @since 1.0.0
2
+ * Bridges Effect metrics into OpenTelemetry by exposing the current Effect
3
+ * metric snapshot as an OpenTelemetry `MetricProducer` and registering it with
4
+ * one or more SDK `MetricReader`s. Use this module when an application already
5
+ * records metrics with Effect and needs those counters, gauges, histograms,
6
+ * frequencies, or summaries exported through OTLP, Prometheus, or another
7
+ * OpenTelemetry-compatible reader/exporter.
8
+ *
9
+ * The `layer` constructor is the usual entry point, and is also used by the
10
+ * Node and Web SDK layers when `metricReader` configuration is supplied. Metric
11
+ * readers are acquired inside the layer scope and shut down when the scope is
12
+ * released, so periodic exporters need the runtime to stay alive long enough to
13
+ * collect and export data. The exporter or backend determines whether
14
+ * cumulative or delta aggregation is expected; this module defaults to
15
+ * cumulative temporality and can be configured with `temporality: "delta"` for
16
+ * backends that require interval-based values.
17
+ *
18
+ * @since 4.0.0
3
19
  */
4
20
  import type { MetricProducer, MetricReader } from "@opentelemetry/sdk-metrics"
5
21
  import type * as Arr from "effect/Array"
@@ -15,35 +31,36 @@ import { Resource } from "./Resource.ts"
15
31
  * Determines how metric values relate to the time interval over which they
16
32
  * are aggregated.
17
33
  *
18
- * - `cumulative`: Reports total since a fixed start time. Each data point
19
- * depends on all previous measurements. This is the default behavior.
34
+ * **Details**
20
35
  *
21
- * - `delta`: Reports changes since the last export. Each interval is
22
- * independent with no dependency on previous measurements.
36
+ * `cumulative` reports total since a fixed start time. Each data point depends
37
+ * on all previous measurements. This is the default behavior. `delta` reports
38
+ * changes since the last export. Each interval is independent with no
39
+ * dependency on previous measurements.
23
40
  *
24
- * @since 1.0.0
25
- * @category Models
41
+ * @category models
42
+ * @since 4.0.0
26
43
  */
27
44
  export type TemporalityPreference = "cumulative" | "delta"
28
45
 
29
46
  /**
30
47
  * Creates an OpenTelemetry metric producer from Effect metrics.
31
48
  *
32
- * @since 1.0.0
33
- * @category Constructors
49
+ * @category constructors
50
+ * @since 4.0.0
34
51
  */
35
52
  export const makeProducer = (temporality?: TemporalityPreference): Effect.Effect<MetricProducer, never, Resource> =>
36
53
  Effect.gen(function*() {
37
54
  const resource = yield* Resource
38
- const services = yield* Effect.services<never>()
55
+ const services = yield* Effect.context<never>()
39
56
  return new MetricProducerImpl(resource, services, temporality)
40
57
  })
41
58
 
42
59
  /**
43
60
  * Registers a metric producer with one or more metric readers.
44
61
  *
45
- * @since 1.0.0
46
- * @category Constructors
62
+ * @category constructors
63
+ * @since 4.0.0
47
64
  */
48
65
  export const registerProducer = (
49
66
  self: MetricProducer,
@@ -74,7 +91,8 @@ export const registerProducer = (
74
91
  /**
75
92
  * Creates a Layer that registers a metric producer with metric readers.
76
93
  *
77
- * @example
94
+ * **Example** (Creating a metrics layer with temporality)
95
+ *
78
96
  * ```ts
79
97
  * import { Metrics } from "@effect/opentelemetry"
80
98
  * import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics"
@@ -98,8 +116,8 @@ export const registerProducer = (
98
116
  * )
99
117
  * ```
100
118
  *
101
- * @since 1.0.0
102
- * @category Layers
119
+ * @category layers
120
+ * @since 4.0.0
103
121
  */
104
122
  export const layer = (
105
123
  evaluate: LazyArg<MetricReader | Arr.NonEmptyReadonlyArray<MetricReader>>,
package/src/NodeSdk.ts CHANGED
@@ -1,5 +1,27 @@
1
1
  /**
2
- * @since 1.0.0
2
+ * Provides an Effect layer for configuring OpenTelemetry in Node.js
3
+ * processes. The module wires the Effect tracer, metrics producer, and logger
4
+ * into OpenTelemetry SDK providers when span processors, metric readers, or log
5
+ * record processors are supplied, and it builds the shared resource from
6
+ * `OTEL_SERVICE_NAME`, `OTEL_RESOURCE_ATTRIBUTES`, and optional explicit
7
+ * service metadata.
8
+ *
9
+ * Use this module in Node services, workers, CLIs, or server runtimes that need
10
+ * Effect spans, metrics, and logs exported through OpenTelemetry processors and
11
+ * exporters. Telemetry is enabled only for the configured signal types, so an
12
+ * application can install tracing alone, metrics alone, logging alone, or any
13
+ * combination of them from the same layer.
14
+ *
15
+ * The layer is scoped. Tracer and logger providers are force-flushed and shut
16
+ * down when the scope is released, metric readers are shut down with the same
17
+ * lifecycle, and all shutdown waits are bounded by `shutdownTimeout` with a
18
+ * default of three seconds. Keep the layer scope alive for the lifetime of the
19
+ * process and release it during graceful shutdown so batched exporters have a
20
+ * chance to export final telemetry. When combining this layer with Node
21
+ * auto-instrumentations, register instrumentation before importing modules that
22
+ * should be patched, because many Node instrumentations hook module loading.
23
+ *
24
+ * @since 4.0.0
3
25
  */
4
26
  import type * as Otel from "@opentelemetry/api"
5
27
  import type { LoggerProviderConfig, LogRecordProcessor } from "@opentelemetry/sdk-logs"
@@ -18,8 +40,10 @@ import * as Resource from "./Resource.ts"
18
40
  import * as Tracer from "./Tracer.ts"
19
41
 
20
42
  /**
21
- * @since 1.0.0
22
- * @category Models
43
+ * Configuration for the Node OpenTelemetry layer, including optional tracing, metrics, logging, resource, and shutdown settings.
44
+ *
45
+ * @category models
46
+ * @since 4.0.0
23
47
  */
24
48
  export interface Configuration {
25
49
  readonly spanProcessor?: SpanProcessor | ReadonlyArray<SpanProcessor> | undefined
@@ -38,8 +62,10 @@ export interface Configuration {
38
62
  }
39
63
 
40
64
  /**
41
- * @since 1.0.0
42
- * @category Layers
65
+ * Creates a scoped Node OpenTelemetry tracer provider from one or more span processors and shuts it down when the layer is released.
66
+ *
67
+ * @category layers
68
+ * @since 4.0.0
43
69
  */
44
70
  export const layerTracerProvider = (
45
71
  processor: SpanProcessor | NonEmptyReadonlyArray<SpanProcessor>,
@@ -71,18 +97,24 @@ export const layerTracerProvider = (
71
97
  )
72
98
 
73
99
  /**
74
- * @since 1.0.0
75
- * @category Layers
100
+ * Creates a Node OpenTelemetry layer from configuration, enabling tracing, metrics, and logging only when their processors or readers are supplied.
101
+ *
102
+ * @category layers
103
+ * @since 4.0.0
76
104
  */
77
105
  export const layer: {
78
106
  /**
79
- * @since 1.0.0
80
- * @category Layers
107
+ * Creates a Node OpenTelemetry layer from configuration, enabling tracing, metrics, and logging only when their processors or readers are supplied.
108
+ *
109
+ * @category layers
110
+ * @since 4.0.0
81
111
  */
82
112
  (evaluate: LazyArg<Configuration>): Layer.Layer<Resource.Resource>
83
113
  /**
84
- * @since 1.0.0
85
- * @category Layers
114
+ * Creates a Node OpenTelemetry layer from configuration, enabling tracing, metrics, and logging only when their processors or readers are supplied.
115
+ *
116
+ * @category layers
117
+ * @since 4.0.0
86
118
  */
87
119
  <R, E>(evaluate: Effect.Effect<Configuration, E, R>): Layer.Layer<Resource.Resource, E, R>
88
120
  } = (
@@ -130,7 +162,9 @@ export const layer: {
130
162
  )
131
163
 
132
164
  /**
165
+ * Layer that provides an empty OpenTelemetry `Resource`.
166
+ *
167
+ * @category layers
133
168
  * @since 2.0.0
134
- * @category layer
135
169
  */
136
170
  export const layerEmpty: Layer.Layer<Resource.Resource> = Resource.layerEmpty
package/src/Resource.ts CHANGED
@@ -1,27 +1,48 @@
1
1
  /**
2
- * @since 1.0.0
2
+ * Provides the OpenTelemetry resource used by the Effect OpenTelemetry layers.
3
+ *
4
+ * A resource describes the entity that produces telemetry, such as a service,
5
+ * process, deployment, or browser application. The tracing, metrics, logging,
6
+ * and SDK layers use this module's `Resource` service to configure providers
7
+ * and identify emitted telemetry with service-level metadata.
8
+ *
9
+ * Use `layer` when service metadata is known in code, `layerFromEnv` when
10
+ * deploying with `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`, and
11
+ * `layerEmpty` when no resource attributes should be provided. Resource
12
+ * attributes are for stable process or service metadata, not per-span or
13
+ * per-log data. The explicit `layer` helper sets `service.name` and the
14
+ * `telemetry.sdk.*` attributes after merging custom attributes, so those keys
15
+ * are controlled by this integration. With `layerFromEnv`, `OTEL_SERVICE_NAME`
16
+ * overrides `service.name` from `OTEL_RESOURCE_ATTRIBUTES`, and additional
17
+ * attributes passed to the layer are merged last.
18
+ *
19
+ * @since 4.0.0
3
20
  */
4
21
  import type * as OtelApi from "@opentelemetry/api"
5
22
  import * as Resources from "@opentelemetry/resources"
6
23
  import * as OtelSemConv from "@opentelemetry/semantic-conventions"
7
24
  import * as Arr from "effect/Array"
8
25
  import * as Config from "effect/Config"
26
+ import * as Context from "effect/Context"
9
27
  import * as Effect from "effect/Effect"
10
28
  import * as Layer from "effect/Layer"
11
- import * as ServiceMap from "effect/ServiceMap"
12
29
 
13
30
  /**
14
- * @since 1.0.0
15
- * @category Services
31
+ * Context service containing the OpenTelemetry `Resource` associated with emitted telemetry.
32
+ *
33
+ * @category services
34
+ * @since 4.0.0
16
35
  */
17
- export class Resource extends ServiceMap.Service<
36
+ export class Resource extends Context.Service<
18
37
  Resource,
19
38
  Resources.Resource
20
39
  >()("@effect/opentelemetry/Resource") {}
21
40
 
22
41
  /**
23
- * @since 1.0.0
24
- * @category Layers
42
+ * Creates a `Resource` layer from service metadata and additional OpenTelemetry attributes.
43
+ *
44
+ * @category layers
45
+ * @since 4.0.0
25
46
  */
26
47
  export const layer = (config: {
27
48
  readonly serviceName: string
@@ -34,8 +55,10 @@ export const layer = (config: {
34
55
  )
35
56
 
36
57
  /**
37
- * @since 1.0.0
38
- * @category Configuration
58
+ * Converts resource configuration into OpenTelemetry attributes, adding service name, optional service version, and telemetry SDK metadata.
59
+ *
60
+ * @category configuration
61
+ * @since 4.0.0
39
62
  */
40
63
  export const configToAttributes = (options: {
41
64
  readonly serviceName: string
@@ -57,8 +80,10 @@ export const configToAttributes = (options: {
57
80
  }
58
81
 
59
82
  /**
60
- * @since 1.0.0
61
- * @category Layers
83
+ * Creates a `Resource` layer from OpenTelemetry environment variables, optionally merging additional attributes.
84
+ *
85
+ * @category layers
86
+ * @since 4.0.0
62
87
  */
63
88
  export const layerFromEnv = (
64
89
  additionalAttributes?:
@@ -70,7 +95,7 @@ export const layerFromEnv = (
70
95
  Effect.gen(function*() {
71
96
  const serviceName = yield* Config.option(Config.string("OTEL_SERVICE_NAME"))
72
97
  const attributes = yield* Config.string("OTEL_RESOURCE_ATTRIBUTES").pipe(
73
- Config.withDefault(() => ""),
98
+ Config.withDefault(""),
74
99
  Config.map((s) => {
75
100
  const attrs = s.split(",")
76
101
  return Arr.reduce(attrs, {} as OtelApi.Attributes, (acc, attr) => {
@@ -94,8 +119,10 @@ export const layerFromEnv = (
94
119
  )
95
120
 
96
121
  /**
97
- * @since 1.0.0
98
- * @category Layers
122
+ * Layer that provides an empty OpenTelemetry resource.
123
+ *
124
+ * @category layers
125
+ * @since 4.0.0
99
126
  */
100
127
  export const layerEmpty = Layer.succeed(
101
128
  Resource,