@devopsplaybook.io/otel-utils 1.10.0 → 1.11.0-beta.43.27704ef

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/README.md CHANGED
@@ -14,24 +14,25 @@ Requires Node.js 22 or newer (`engines` in `package.json`).
14
14
 
15
15
  All classes accept a `ConfigOTelInterface` object. The fields mirror environment variables in the consuming application (for example `common-utils`' `ConfigBase`); the library itself does not read `process.env`.
16
16
 
17
- | Field | Type | Default | Description |
18
- | --------------------------------------------------------- | ----------------------------------- | ---------- | --------------------------------------------------- |
19
- | `SERVICE_ID` | `string` | — | Service identifier (required, non-empty) |
20
- | `VERSION` | `string` | — | Service version (required, non-empty) |
21
- | `OPENTELEMETRY_COLLECTOR_HTTP_TRACES` | `string?` | — | OTLP HTTP endpoint for traces |
22
- | `OPENTELEMETRY_COLLECTOR_HTTP_METRICS` | `string?` | — | OTLP HTTP endpoint for metrics |
23
- | `OPENTELEMETRY_COLLECTOR_HTTP_LOGS` | `string?` | — | OTLP HTTP endpoint for logs |
24
- | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_INTERVAL_SECONDS` | `number?` | `60` | Log export interval in seconds (clamped to ≥ 1) |
25
- | `OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_INTERVAL_SECONDS` | `number?` | `60` | Metrics export interval in seconds (clamped to ≥ 1) |
26
- | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_QUEUE_SIZE` | `number?` | `2048` | Max log records buffered before export |
27
- | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_BATCH_SIZE` | `number?` | `512` | Max log records per export batch |
28
- | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_TIMEOUT_MILLIS` | `number?` | `30000` | Log export timeout in milliseconds |
29
- | `OPENTELEMETRY_CONSOLE_LOG_MODE` | `"always" \| "fallback" \| "never"` | `"always"` | Console mirroring mode for `ModuleLogger` |
30
- | `OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER` | `string?` | — | Bearer token for collector auth |
17
+ | Field | Type | Default | Description |
18
+ | --------------------------------------------------------- | --------------------------------------------------- | ---------- | --------------------------------------------------------- |
19
+ | `SERVICE_ID` | `string` | — | Service identifier (required, non-empty) |
20
+ | `VERSION` | `string` | — | Service version (required, non-empty) |
21
+ | `OPENTELEMETRY_COLLECTOR_HTTP_TRACES` | `string?` | — | OTLP HTTP endpoint for traces |
22
+ | `OPENTELEMETRY_COLLECTOR_HTTP_METRICS` | `string?` | — | OTLP HTTP endpoint for metrics |
23
+ | `OPENTELEMETRY_COLLECTOR_HTTP_LOGS` | `string?` | — | OTLP HTTP endpoint for logs |
24
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_INTERVAL_SECONDS` | `number?` | `60` | Log export interval in seconds (clamped to ≥ 1) |
25
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_METRICS_INTERVAL_SECONDS` | `number?` | `60` | Metrics export interval in seconds (clamped to ≥ 1) |
26
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_QUEUE_SIZE` | `number?` | `2048` | Max log records buffered before export |
27
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_BATCH_SIZE` | `number?` | `512` | Max log records per export batch |
28
+ | `OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_TIMEOUT_MILLIS` | `number?` | `30000` | Log export timeout in milliseconds |
29
+ | `OPENTELEMETRY_CONSOLE_LOG_MODE` | `"always" \| "fallback" \| "never"` | `"always"` | Console mirroring mode for `ModuleLogger` |
30
+ | `OPENTELEMETRY_LOG_LEVEL` | `"trace" \| "debug" \| "info" \| "warn" \| "error"` | `"info"` | Minimum level emitted to OTel and mirrored to the console |
31
+ | `OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER` | `string?` | — | Bearer token for collector auth |
31
32
 
32
33
  `SERVICE_ID` and `VERSION` must be non-empty strings. `StandardTracer`/`StandardMeter` constructors and `StandardLogger.initOTel` fail fast with `[otel-utils] SERVICE_ID must be a non-empty string` / `[otel-utils] VERSION must be a non-empty string` otherwise. A failed re-initialisation of `StandardLogger` keeps the previous provider in place.
33
34
 
34
- Numeric export intervals below 1 s (including `0` and negative values from an empty environment variable) are clamped to 1 s; `NaN`/`Infinity` fall back to the 60 s default. Non-positive or non-integer batch values fall back to their defaults.
35
+ Numeric export intervals below 1 s (including `0` and negative values from an empty environment variable) are clamped to 1 s; `NaN`/`Infinity` fall back to the 60 s default. Non-positive or non-integer batch values fall back to their defaults. An invalid `OPENTELEMETRY_LOG_LEVEL` logs one `console.warn` and falls back to `"info"`; an invalid `OPENTELEMETRY_CONSOLE_LOG_MODE` logs one `console.warn` and falls back to `"always"`.
35
36
 
36
37
  When a collector endpoint is not provided, the corresponding signal (traces, logs, or metrics) is initialized with no export: traces and metrics still have a local provider but no data is sent, and `StandardLogger` creates no provider (its `getLogger()` returns `undefined`).
37
38
 
@@ -82,7 +83,9 @@ moduleLog.info("Hello world");
82
83
 
83
84
  - `initOTel(config)` — Initializes the logger provider and optional OTLP exporter, and registers the provider globally when a logs endpoint is configured and no other logger provider is registered. Returns `Promise<void>`; a previous provider is flushed and shut down first. Queued in call order with `shutdown()` — see [Provider lifecycle](#provider-lifecycle).
84
85
  - `getLogger()` — Returns the underlying OTel `Logger` or `undefined` (also `undefined` after `shutdown()`).
85
- - `createModuleLogger(moduleName)` — Creates a `ModuleLogger` scoped to a module name.
86
+ - `getConsoleMode()` — Returns the current console mirroring mode (`always` by default).
87
+ - `getLogLevel()` — Returns the current minimum log level (`info` by default).
88
+ - `createModuleLogger(moduleName)` — Creates a `ModuleLogger` scoped to a module name. The logger reads `getConsoleMode()` and `getLogLevel()` at emit time, so it follows the configured mode and level even when it is created before `initOTel()`, and a re-initialisation changes the behaviour of existing loggers.
86
89
  - `shutdown()` — Flushes buffered log records and shuts the logger provider down. Idempotent. No-op when no logs endpoint is configured. Queued in call order with `initOTel()`.
87
90
  - `forceFlush()` — Flushes buffered log records to the collector without shutting the provider down; resolves immediately when no logger provider exists. Use it at checkpoints in short-lived jobs and serverless handlers.
88
91
 
@@ -111,7 +114,7 @@ await logger.initOTel({
111
114
 
112
115
  ### ModuleLogger
113
116
 
114
- Scoped logger that prefixes all output with a module name. Every record carries a `log.module` attribute in addition to the `[module] message` body. Records are emitted to the OTel logger when one is available, and can additionally be mirrored to the console, controlled by `OPENTELEMETRY_CONSOLE_LOG_MODE`:
117
+ Scoped logger that prefixes all output with a module name. Every record carries a `log.module` attribute in addition to the `[module] message` body. Records are emitted to the OTel logger when one is available, filtered by `OPENTELEMETRY_LOG_LEVEL`, and can additionally be mirrored to the console, controlled by `OPENTELEMETRY_CONSOLE_LOG_MODE`:
115
118
 
116
119
  | Mode | Behaviour |
117
120
  | ------------------ | ------------------------------------------------------------------------------------------ |
@@ -119,10 +122,20 @@ Scoped logger that prefixes all output with a module name. Every record carries
119
122
  | `fallback` | Mirror only when no OTel logger is configured (`OPENTELEMETRY_COLLECTOR_HTTP_LOGS` unset). |
120
123
  | `never` | Never write to the console; records only go to OTel. |
121
124
 
122
- Mirroring is level-aware: `info` uses `console.log`, `warn` uses `console.warn` and `error` uses `console.error` (stderr), so stderr-based alerting sees warnings and errors. An invalid mode value logs one `console.warn` and falls back to `always`. With `never`, a `ModuleLogger` writes nothing to the console even when no OTel logger is configured.
125
+ The console mode is read when a record is emitted, not when the logger is created: a `ModuleLogger` created before `initOTel()` follows the configured mode after initialisation, and re-initialising with a different mode changes the behaviour of existing loggers. `createModuleLogger()` does not snapshot the mode; passing `{ consoleMode }` to `new ModuleLogger(module, standardLogger, options)` overrides it explicitly for tests and advanced use.
126
+
127
+ Mirroring is level-aware: `info` uses `console.log`, `warn` uses `console.warn`, `error` uses `console.error` (stderr), and `debug`/`trace` use `console.debug`. An invalid mode value logs one `console.warn` and falls back to `always`. With `never`, a `ModuleLogger` writes nothing to the console even when no OTel logger is configured.
128
+
129
+ Console lines carry the actionable details: `[<level>] [<module>] <message>`, followed by ` — <error.name>: <error.message>` when an error is attached and ` trace.id=<traceId> span.id=<spanId>` when a span is passed as context. The stack follows on a new line inside the same console call. For example, `log.error("request failed", error, span)` writes `[error] [api] request failed — Error: db down trace.id=… span.id=…` followed by the stack. The OTel record is unchanged (`[<module>] <message>` body plus `exception.*`, `trace.id` and `span.id` attributes); only the console line gains these details. The configured authorization token is never written to the console.
130
+
131
+ `OPENTELEMETRY_LOG_LEVEL` sets the minimum level for **both** OTel emission and console mirroring. The default `info` keeps the existing output and drops only the new `debug` and `trace` records; `trace` lets every level through, `warn` drops `info` and below, and `error` emits only errors. An invalid value logs one `console.warn` and falls back to `info`.
132
+
133
+ **Container deployments:** `always` duplicates log volume — every record is written to stdout/stderr _and_ exported over OTLP, so with stdout collection the same log is stored twice. When a containerized service's stdout is collected, use `fallback`: the console then receives records only when no OTLP logs endpoint is configured (`OPENTELEMETRY_COLLECTOR_HTTP_LOGS` unset). The `always` default is unchanged.
123
134
 
124
135
  ```typescript
125
136
  const log = logger.createModuleLogger("api");
137
+ log.trace("entering handler"); // filtered at the default info level
138
+ log.debug("resolved tenant", activeSpan); // filtered at the default info level
126
139
  log.info("request received");
127
140
  log.warn("rate limit approaching");
128
141
  log.error("connection failed", new Error("timeout"));
@@ -132,11 +145,13 @@ log.info("processing complete", activeSpan); // attach trace context
132
145
 
133
146
  **Methods:**
134
147
 
148
+ - `trace(message, context?)` — Log at TRACE level; mirrored through `console.debug`.
149
+ - `debug(message, context?)` — Log at DEBUG level; mirrored through `console.debug`.
135
150
  - `info(message, context?)` — Log at INFO level.
136
151
  - `warn(message, context?)` — Log at WARN level.
137
152
  - `error(message, error?, context?)` — Log at ERROR level. `error` accepts any value: `Error` instances are kept as-is, strings become `new Error(string)` and other values are serialised with `JSON.stringify` (falling back to `String`). `exception.type` and `exception.message` are always set; `exception.stacktrace` is set only when the error has a stack. `null`/`undefined` add no exception attributes. A `Span` passed as the second argument is treated as the context, so `error("failed", span)` and `error("failed", err, span)` both work.
138
153
 
139
- When a `Span` is passed as `context`, the log record includes `span.id` and `trace.id` attributes for trace correlation.
154
+ When a `Span` is passed as `context`, the log record includes `span.id` and `trace.id` attributes for trace correlation, and the console line appends `trace.id=… span.id=…`.
140
155
 
141
156
  ### StandardMeter
142
157
 
@@ -7,10 +7,13 @@ export interface ModuleLoggerOptions {
7
7
  export declare class ModuleLogger {
8
8
  private module;
9
9
  private standardLogger;
10
- private consoleMode;
10
+ private consoleModeOverride?;
11
11
  constructor(module: string, standardLogger: StandardLoggerInterface, options?: ModuleLoggerOptions);
12
+ trace(message: string, context?: Span): void;
13
+ debug(message: string, context?: Span): void;
12
14
  info(message: string, context?: Span): void;
13
15
  warn(message: string, context?: Span): void;
14
16
  error(message: string, error?: unknown, context?: Span): void;
15
17
  private display;
18
+ private formatConsoleLine;
16
19
  }
@@ -2,12 +2,24 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ModuleLogger = void 0;
4
4
  const api_1 = require("@opentelemetry/api");
5
+ const MIN_SEVERITY = {
6
+ trace: api_1.SeverityNumber.TRACE,
7
+ debug: api_1.SeverityNumber.DEBUG,
8
+ info: api_1.SeverityNumber.INFO,
9
+ warn: api_1.SeverityNumber.WARN,
10
+ error: api_1.SeverityNumber.ERROR,
11
+ };
5
12
  class ModuleLogger {
6
13
  constructor(module, standardLogger, options = {}) {
7
- var _a;
8
14
  this.module = module;
9
15
  this.standardLogger = standardLogger;
10
- this.consoleMode = (_a = options.consoleMode) !== null && _a !== void 0 ? _a : "always";
16
+ this.consoleModeOverride = options.consoleMode;
17
+ }
18
+ trace(message, context) {
19
+ this.display("trace", message, api_1.SeverityNumber.TRACE, null, context);
20
+ }
21
+ debug(message, context) {
22
+ this.display("debug", message, api_1.SeverityNumber.DEBUG, null, context);
11
23
  }
12
24
  info(message, context) {
13
25
  this.display("info", message, api_1.SeverityNumber.INFO, null, context);
@@ -23,6 +35,10 @@ class ModuleLogger {
23
35
  this.display("error", message, api_1.SeverityNumber.ERROR, normalizeError(error), context);
24
36
  }
25
37
  display(level, message, severityNumber = api_1.SeverityNumber.INFO, error, context) {
38
+ var _a;
39
+ if (severityNumber < MIN_SEVERITY[this.standardLogger.getLogLevel()]) {
40
+ return;
41
+ }
26
42
  const attributes = {
27
43
  "log.type": "custom",
28
44
  "log.module": this.module,
@@ -40,10 +56,10 @@ class ModuleLogger {
40
56
  attributes["trace.id"] = spanCtx.traceId;
41
57
  }
42
58
  const logger = this.standardLogger.getLogger();
43
- const mirrorToConsole = this.consoleMode === "always" ||
44
- (this.consoleMode === "fallback" && !logger);
59
+ const consoleMode = (_a = this.consoleModeOverride) !== null && _a !== void 0 ? _a : this.standardLogger.getConsoleMode();
60
+ const mirrorToConsole = consoleMode === "always" || (consoleMode === "fallback" && !logger);
45
61
  if (mirrorToConsole) {
46
- writeToConsole(level, `[${level}] [${this.module}] ${message}`);
62
+ writeToConsole(level, this.formatConsoleLine(level, message, error, context));
47
63
  }
48
64
  if (!logger) {
49
65
  return;
@@ -55,6 +71,20 @@ class ModuleLogger {
55
71
  attributes,
56
72
  });
57
73
  }
74
+ formatConsoleLine(level, message, error, context) {
75
+ let line = `[${level}] [${this.module}] ${message}`;
76
+ if (error) {
77
+ line += ` — ${error.name}: ${error.message}`;
78
+ }
79
+ if (context) {
80
+ const spanCtx = context.spanContext();
81
+ line += ` trace.id=${spanCtx.traceId} span.id=${spanCtx.spanId}`;
82
+ }
83
+ if ((error === null || error === void 0 ? void 0 : error.stack) !== undefined) {
84
+ line += `\n${error.stack}`;
85
+ }
86
+ return line;
87
+ }
58
88
  }
59
89
  exports.ModuleLogger = ModuleLogger;
60
90
  function normalizeError(value) {
@@ -98,6 +128,9 @@ function writeToConsole(level, line) {
98
128
  else if (level === "warn") {
99
129
  console.warn(line);
100
130
  }
131
+ else if (level === "debug" || level === "trace") {
132
+ console.debug(line);
133
+ }
101
134
  else {
102
135
  console.log(line);
103
136
  }
@@ -1,5 +1,5 @@
1
1
  import { type Logger as OTelLogger } from "@opentelemetry/api";
2
- import type { ConfigOTelInterface } from "./models/ConfigOTelInterface";
2
+ import type { ConfigOTelInterface, ConsoleLogMode, LogLevel } from "./models/ConfigOTelInterface";
3
3
  import { ModuleLogger } from "./ModuleLogger";
4
4
  import type { StandardLoggerInterface } from "./models/StandardLoggerInterface";
5
5
  export declare class StandardLogger implements StandardLoggerInterface {
@@ -10,10 +10,13 @@ export declare class StandardLogger implements StandardLoggerInterface {
10
10
  private ownsGlobalProvider;
11
11
  private operationQueue;
12
12
  private consoleMode;
13
+ private logLevel;
13
14
  initOTel(config: ConfigOTelInterface): Promise<void>;
14
15
  shutdown(): Promise<void>;
15
16
  forceFlush(): Promise<void>;
16
17
  getLogger(): OTelLogger | undefined;
18
+ getConsoleMode(): ConsoleLogMode;
19
+ getLogLevel(): LogLevel;
17
20
  createModuleLogger(moduleName: string): ModuleLogger;
18
21
  private enqueue;
19
22
  private doInitOTel;
@@ -14,6 +14,7 @@ class StandardLogger {
14
14
  this.ownsGlobalProvider = false;
15
15
  this.operationQueue = Promise.resolve();
16
16
  this.consoleMode = "always";
17
+ this.logLevel = "info";
17
18
  }
18
19
  initOTel(config) {
19
20
  return this.enqueue(() => this.doInitOTel(config));
@@ -29,10 +30,14 @@ class StandardLogger {
29
30
  getLogger() {
30
31
  return this.logger;
31
32
  }
33
+ getConsoleMode() {
34
+ return this.consoleMode;
35
+ }
36
+ getLogLevel() {
37
+ return this.logLevel;
38
+ }
32
39
  createModuleLogger(moduleName) {
33
- return new ModuleLogger_1.ModuleLogger(moduleName, this, {
34
- consoleMode: this.consoleMode,
35
- });
40
+ return new ModuleLogger_1.ModuleLogger(moduleName, this);
36
41
  }
37
42
  enqueue(operation) {
38
43
  const result = this.operationQueue.then(operation, operation);
@@ -44,6 +49,7 @@ class StandardLogger {
44
49
  // the working provider in place.
45
50
  (0, configValidation_1.validateServiceIdentity)(config);
46
51
  this.consoleMode = (0, configValidation_1.normalizeConsoleLogMode)(config.OPENTELEMETRY_CONSOLE_LOG_MODE);
52
+ this.logLevel = (0, configValidation_1.normalizeLogLevel)(config.OPENTELEMETRY_LOG_LEVEL);
47
53
  // Re-initialisation flushes and unregisters the previous provider first.
48
54
  if (this.loggerProvider) {
49
55
  await this.releaseProvider();
@@ -1,4 +1,5 @@
1
1
  export type ConsoleLogMode = "always" | "fallback" | "never";
2
+ export type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
2
3
  export interface ConfigOTelInterface {
3
4
  SERVICE_ID: string;
4
5
  VERSION: string;
@@ -11,5 +12,6 @@ export interface ConfigOTelInterface {
11
12
  OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_MAX_BATCH_SIZE?: number;
12
13
  OPENTELEMETRY_COLLECTOR_EXPORT_LOGS_TIMEOUT_MILLIS?: number;
13
14
  OPENTELEMETRY_CONSOLE_LOG_MODE?: ConsoleLogMode;
15
+ OPENTELEMETRY_LOG_LEVEL?: LogLevel;
14
16
  OPENTELEMETRY_COLLECT_AUTHORIZATION_HEADER?: string;
15
17
  }
@@ -1,4 +1,7 @@
1
1
  import type { Logger } from "@opentelemetry/api";
2
+ import type { ConsoleLogMode, LogLevel } from "./ConfigOTelInterface";
2
3
  export interface StandardLoggerInterface {
3
4
  getLogger(): Logger | undefined;
5
+ getConsoleMode(): ConsoleLogMode;
6
+ getLogLevel(): LogLevel;
4
7
  }
@@ -1,5 +1,6 @@
1
- import type { ConfigOTelInterface, ConsoleLogMode } from "../models/ConfigOTelInterface";
1
+ import type { ConfigOTelInterface, ConsoleLogMode, LogLevel } from "../models/ConfigOTelInterface";
2
2
  export declare function validateServiceIdentity(config: Pick<ConfigOTelInterface, "SERVICE_ID" | "VERSION">): void;
3
3
  export declare function normalizeExportIntervalSeconds(value: number | undefined, defaultSeconds: number): number;
4
4
  export declare function normalizePositiveInteger(value: number | undefined, defaultValue: number): number;
5
5
  export declare function normalizeConsoleLogMode(value: unknown): ConsoleLogMode;
6
+ export declare function normalizeLogLevel(value: unknown): LogLevel;
@@ -4,6 +4,7 @@ exports.validateServiceIdentity = validateServiceIdentity;
4
4
  exports.normalizeExportIntervalSeconds = normalizeExportIntervalSeconds;
5
5
  exports.normalizePositiveInteger = normalizePositiveInteger;
6
6
  exports.normalizeConsoleLogMode = normalizeConsoleLogMode;
7
+ exports.normalizeLogLevel = normalizeLogLevel;
7
8
  function validateServiceIdentity(config) {
8
9
  if (typeof config.SERVICE_ID !== "string" ||
9
10
  config.SERVICE_ID.trim() === "") {
@@ -34,3 +35,16 @@ function normalizeConsoleLogMode(value) {
34
35
  }
35
36
  return "always";
36
37
  }
38
+ function normalizeLogLevel(value) {
39
+ if (value === "trace" ||
40
+ value === "debug" ||
41
+ value === "info" ||
42
+ value === "warn" ||
43
+ value === "error") {
44
+ return value;
45
+ }
46
+ if (value !== undefined) {
47
+ console.warn(`[otel-utils] Invalid OPENTELEMETRY_LOG_LEVEL value "${String(value)}"; expected "trace", "debug", "info", "warn" or "error". Defaulting to "info".`);
48
+ }
49
+ return "info";
50
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devopsplaybook.io/otel-utils",
3
- "version": "1.10.0",
3
+ "version": "1.11.0-beta.43.27704ef",
4
4
  "description": "Utility to simplify integration with Open Telemetry",
5
5
  "keywords": [
6
6
  "Open",