@easyweb/logging 1.1.0 → 1.2.0

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
@@ -133,10 +133,51 @@ the existing `requestId`.
133
133
  It is inert unless configured: it starts only when `OTEL_EXPORTER_OTLP_ENDPOINT`
134
134
  or `OTEL_TRACES_EXPORTER` is set and non-empty, and `OTEL_SDK_DISABLED=true`
135
135
  always wins. The service name is `OTEL_SERVICE_NAME`, else `SERVICE_NAME`, else
136
- `unknown-service`. Exporter, endpoint and sampler come from the standard
137
- `OTEL_*` variables. `/health`, `/livez` and `/api/heartbeat` are not traced.
136
+ `unknown-service`. `OTEL_*` variables are read when the process starts, before
137
+ dotenv loads a service's `.env`, so setting them there has no effect: put them
138
+ on the command line or in the pod env. Exporter, endpoint and sampler come from the standard
139
+ `OTEL_*` variables. `/health`, `/livez` and `/api/heartbeat` are not traced. Logs are never exported, and metrics only through their own gate (below). Query-string values are redacted in span attributes for the
140
+ instrumentation libraries' own default keys (`sig`, `Signature`, `AWSAccessKeyId`,
141
+ `X-Goog-Signature`, `X-Amz-Signature`, `X-Amz-Credential`, `X-Amz-Security-Token`)
142
+ plus `token`, `code`, `state` and `refresh_token`; keys are percent-decoded before
143
+ matching but matched exact-case, and a token in the URL path is not redacted. Redis statements carry the command name only, and `pg`,
144
+ `undici` and outgoing `http` make no span outside a request.
138
145
  Note that `OTEL_TRACES_EXPORTER=none` registers no tracer provider, so spans are
139
146
  non-recording and carry no `trace_id`.
140
147
 
141
- `npm run check:telemetry` builds and proves the `trace_id` injection against
142
- `dist/`; it cannot be a jest test because jest bypasses the require hooks.
148
+ ## Metrics (OpenTelemetry, 1.2.0)
149
+
150
+ Metrics start only when `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` is non-empty (and
151
+ `OTEL_SDK_DISABLED` is not `true`). Either signal can run alone: with metrics only
152
+ the SDK builds no trace pipeline and exports nothing to `/v1/traces`. The reader is
153
+ periodic OTLP/HTTP protobuf, cumulative, every `OTEL_METRIC_EXPORT_INTERVAL` ms
154
+ (default 30000). Decision: `docs/platform/ADR-0012`.
155
+
156
+ Only three auto instruments are kept, each with a fixed attribute allowlist:
157
+ `http.server.request.duration` (method, route, status), `http.client.request.duration`
158
+ (`server.address`, method, status) and `db.client.operation.duration` (operation,
159
+ collection). `server.address` is `other` unless the host is a known vendor host
160
+ (`KNOWN_HOSTS`); a listed internal service (short name, `name.ns`, or
161
+ `name.ns.svc.cluster.local`, ns `easyweb-prod` or `easyweb-observability`) keeps its
162
+ name, and any other cluster-looking host is `other`. Every other
163
+ instrumentation instrument is dropped at the exporter. Our own meters
164
+ (`@easyweb/events`, `@easyweb/logging/jobs`, `project`, `deployment`) pass unchanged.
165
+
166
+ `pg` records its duration only inside a span context (`requireParentSpan`), so DB
167
+ metrics cover request-path calls only. Outgoing `http` and `undici` durations are
168
+ recorded with or without a parent.
169
+
170
+ ```ts
171
+ import { getMeter, EVENT_BUCKETS_S, PUBLISH_BUCKETS_S, observeQueue, observeWorker } from "@easyweb/logging";
172
+
173
+ const h = getMeter("project").createHistogram("easyweb.publish.duration", { unit: "s", advice: { explicitBucketBoundaries: PUBLISH_BUCKETS_S } });
174
+ observeWorker(worker, "emails"); // easyweb.job.process.duration, easyweb.job.wait.duration
175
+ // One sample per attempt: a retried job records an `error` sample for each failed try.
176
+ observeQueue(queue, "emails"); // easyweb.job.added, easyweb.job.count (cached, refreshed every 30 s)
177
+ ```
178
+
179
+ `getMeter` is a no-op meter when metrics are off. `observeWorker` and `observeQueue`
180
+ take structural types, so this package does not depend on `bullmq`.
181
+
182
+ `npm run check:telemetry` builds and proves the `trace_id` injection, the
183
+ traces-only and the metrics-only redacted exports, and a refused metrics endpoint against `dist/`; it cannot be a jest test because jest bypasses the require hooks.
package/dist/index.d.ts CHANGED
@@ -4,4 +4,6 @@ export * from "./middleware";
4
4
  export * from "./redact";
5
5
  export * from "./serialize";
6
6
  export * from "./transport";
7
+ export { getMeter, EVENT_BUCKETS_S, PUBLISH_BUCKETS_S } from "./metrics";
8
+ export { observeQueue, observeWorker } from "./jobs";
7
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,UAAU,CAAC;AACzB,cAAc,cAAc,CAAC;AAC7B,cAAc,UAAU,CAAC;AACzB,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,WAAW,CAAC;AACzE,OAAO,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAC"}
package/dist/index.js CHANGED
@@ -14,10 +14,18 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.observeWorker = exports.observeQueue = exports.PUBLISH_BUCKETS_S = exports.EVENT_BUCKETS_S = exports.getMeter = void 0;
17
18
  __exportStar(require("./context"), exports);
18
19
  __exportStar(require("./logger"), exports);
19
20
  __exportStar(require("./middleware"), exports);
20
21
  __exportStar(require("./redact"), exports);
21
22
  __exportStar(require("./serialize"), exports);
22
23
  __exportStar(require("./transport"), exports);
24
+ var metrics_1 = require("./metrics");
25
+ Object.defineProperty(exports, "getMeter", { enumerable: true, get: function () { return metrics_1.getMeter; } });
26
+ Object.defineProperty(exports, "EVENT_BUCKETS_S", { enumerable: true, get: function () { return metrics_1.EVENT_BUCKETS_S; } });
27
+ Object.defineProperty(exports, "PUBLISH_BUCKETS_S", { enumerable: true, get: function () { return metrics_1.PUBLISH_BUCKETS_S; } });
28
+ var jobs_1 = require("./jobs");
29
+ Object.defineProperty(exports, "observeQueue", { enumerable: true, get: function () { return jobs_1.observeQueue; } });
30
+ Object.defineProperty(exports, "observeWorker", { enumerable: true, get: function () { return jobs_1.observeWorker; } });
23
31
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,2CAAyB;AACzB,+CAA6B;AAC7B,2CAAyB;AACzB,8CAA4B;AAC5B,8CAA4B"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,2CAAyB;AACzB,+CAA6B;AAC7B,2CAAyB;AACzB,8CAA4B;AAC5B,8CAA4B;AAC5B,qCAAyE;AAAhE,mGAAA,QAAQ,OAAA;AAAE,0GAAA,eAAe,OAAA;AAAE,4GAAA,iBAAiB,OAAA;AACrD,+BAAqD;AAA5C,oGAAA,YAAY,OAAA;AAAE,qGAAA,aAAa,OAAA"}
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ interface Emitter {
2
+ on(event: string, listener: (...args: any[]) => void): unknown;
3
+ }
4
+ export interface ObservedQueue extends Emitter {
5
+ getJobCounts(...states: string[]): Promise<Record<string, number>>;
6
+ }
7
+ /**
8
+ * Duration and queue wait of every attempt. A retried job records one sample per attempt:
9
+ * BullMQ emits `failed` each time but sets `finishedOn` only on the final failure, so an
10
+ * attempt without it ends now. Job names are code constants, never data.
11
+ */
12
+ export declare function observeWorker(worker: Emitter, queue: string): void;
13
+ /** Jobs added (seen by the process that owns this Queue object), and a per-state backlog gauge read from a cache a background refresh fills. */
14
+ export declare function observeQueue(queue: ObservedQueue, name: string): void;
15
+ export {};
16
+ //# sourceMappingURL=jobs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jobs.d.ts","sourceRoot":"","sources":["../src/jobs.ts"],"names":[],"mappings":"AAOA,UAAU,OAAO;IAGf,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE,KAAK,IAAI,GAAG,OAAO,CAAC;CAChE;AAQD,MAAM,WAAW,aAAc,SAAQ,OAAO;IAC5C,YAAY,CAAC,GAAG,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;CACpE;AAOD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAclE;AAED,gJAAgJ;AAChJ,wBAAgB,YAAY,CAAC,KAAK,EAAE,aAAa,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAqBrE"}
package/dist/jobs.js ADDED
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.observeWorker = observeWorker;
4
+ exports.observeQueue = observeQueue;
5
+ const metrics_1 = require("./metrics");
6
+ const telemetry_1 = require("./telemetry");
7
+ const STATES = ["waiting", "active", "delayed", "failed"];
8
+ const REFRESH_MS = 30000;
9
+ const meter = () => (0, metrics_1.getMeter)("@easyweb/logging/jobs");
10
+ /**
11
+ * Duration and queue wait of every attempt. A retried job records one sample per attempt:
12
+ * BullMQ emits `failed` each time but sets `finishedOn` only on the final failure, so an
13
+ * attempt without it ends now. Job names are code constants, never data.
14
+ */
15
+ function observeWorker(worker, queue) {
16
+ const m = meter();
17
+ const advice = { explicitBucketBoundaries: metrics_1.EVENT_BUCKETS_S };
18
+ const proc = m.createHistogram("easyweb.job.process.duration", { unit: "s", advice });
19
+ const wait = m.createHistogram("easyweb.job.wait.duration", { unit: "s", advice });
20
+ const record = (outcome) => (job) => {
21
+ if (!job || typeof job.processedOn !== "number")
22
+ return;
23
+ const base = { "easyweb.queue": queue, "easyweb.job": job.name ?? "unknown" };
24
+ const end = typeof job.finishedOn === "number" ? job.finishedOn : Date.now();
25
+ proc.record((end - job.processedOn) / 1000, { ...base, "easyweb.outcome": outcome });
26
+ if (typeof job.timestamp === "number")
27
+ wait.record((job.processedOn - job.timestamp) / 1000, base);
28
+ };
29
+ worker.on("completed", record("ok"));
30
+ worker.on("failed", record("error"));
31
+ }
32
+ /** Jobs added (seen by the process that owns this Queue object), and a per-state backlog gauge read from a cache a background refresh fills. */
33
+ function observeQueue(queue, name) {
34
+ const m = meter();
35
+ const added = m.createCounter("easyweb.job.added");
36
+ queue.on("waiting", (job) => added.add(1, { "easyweb.queue": name, "easyweb.job": job?.name ?? "unknown" }));
37
+ let counts = {};
38
+ const refresh = () => {
39
+ // A rejection, or a throw before a promise exists, keeps the last value.
40
+ Promise.resolve().then(() => queue.getJobCounts(...STATES)).then((c) => { counts = c; }, () => { });
41
+ };
42
+ if ((0, telemetry_1.shouldStartMetrics)(process.env)) {
43
+ refresh();
44
+ setInterval(refresh, REFRESH_MS).unref();
45
+ }
46
+ m.createObservableGauge("easyweb.job.count").addCallback((r) => {
47
+ for (const state of STATES) {
48
+ const v = counts[state];
49
+ if (typeof v === "number")
50
+ r.observe(v, { "easyweb.queue": name, "easyweb.state": state });
51
+ }
52
+ });
53
+ }
54
+ //# sourceMappingURL=jobs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jobs.js","sourceRoot":"","sources":["../src/jobs.ts"],"names":[],"mappings":";;AAiCA,sCAcC;AAGD,oCAqBC;AAtED,uCAAsD;AACtD,2CAAiD;AAqBjD,MAAM,MAAM,GAAG,CAAC,SAAS,EAAE,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;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M,EAAE,CAAC;YAC3B,MAAM,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;YACxB,IAAI,OAAO,CAAC,KAAK,QAAQ;gBAAE,CAAC,CAAC,OAAO,CAAC,CAAC,EAAE,EAAE,eAAe,EAAE,IAAI,EAAE,eAAe,EAAE,KAAK,EAAE,CAAC,CAAC;QAC7F,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { type Meter } from "@opentelemetry/api";
2
+ import type { PushMetricExporter, ResourceMetrics, ViewOptions } from "@opentelemetry/sdk-metrics";
3
+ /** A no-op meter until the SDK registers a provider (metrics off, or not started yet). */
4
+ export declare function getMeter(name: string): Meter;
5
+ export declare const EVENT_BUCKETS_S: number[];
6
+ export declare const PUBLISH_BUCKETS_S: number[];
7
+ export declare const OWN_METER_NAMES: string[];
8
+ export declare const METRIC_ATTRIBUTE_ALLOWLIST: Record<string, string[]>;
9
+ export declare const KNOWN_HOSTS: Set<string>;
10
+ export declare function boundServerAddress(host: string): string;
11
+ export declare function metricViews(): ViewOptions[];
12
+ /** Keeps our own meters and the allowlisted instruments; every other scope or instrument is dropped. */
13
+ export declare function keepAllowedMetrics(rm: ResourceMetrics): ResourceMetrics;
14
+ export declare function restrictExporter(inner: PushMetricExporter): PushMetricExporter;
15
+ //# sourceMappingURL=metrics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics.d.ts","sourceRoot":"","sources":["../src/metrics.ts"],"names":[],"mappings":"AAAA,OAAO,EAAW,KAAK,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,KAAK,EAAwB,kBAAkB,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAMzH,0FAA0F;AAC1F,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAE5C;AAED,eAAO,MAAM,eAAe,UAAgE,CAAC;AAC7F,eAAO,MAAM,iBAAiB,UAAgE,CAAC;AAG/F,eAAO,MAAM,eAAe,UAAwE,CAAC;AAGrG,eAAO,MAAM,0BAA0B,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,CAI/D,CAAC;AAKF,eAAO,MAAM,WAAW,aAStB,CAAC;AAaH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CASvD;AAMD,wBAAgB,WAAW,IAAI,WAAW,EAAE,CAa3C;AAED,wGAAwG;AACxG,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,eAAe,GAAG,eAAe,CAOvE;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,kBAAkB,GAAG,kBAAkB,CAS9E"}
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.KNOWN_HOSTS = exports.METRIC_ATTRIBUTE_ALLOWLIST = exports.OWN_METER_NAMES = exports.PUBLISH_BUCKETS_S = exports.EVENT_BUCKETS_S = void 0;
4
+ exports.getMeter = getMeter;
5
+ exports.boundServerAddress = boundServerAddress;
6
+ exports.metricViews = metricViews;
7
+ exports.keepAllowedMetrics = keepAllowedMetrics;
8
+ exports.restrictExporter = restrictExporter;
9
+ const api_1 = require("@opentelemetry/api");
10
+ // Like telemetry.ts, this file must never import pino, ./logger or ./index: index
11
+ // re-exports it, and the SDK is require()d lazily inside metricViews().
12
+ // ADR-0012: only a fixed set of instruments and attributes may reach Prometheus.
13
+ /** A no-op meter until the SDK registers a provider (metrics off, or not started yet). */
14
+ function getMeter(name) {
15
+ return api_1.metrics.getMeter(name);
16
+ }
17
+ exports.EVENT_BUCKETS_S = [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300];
18
+ exports.PUBLISH_BUCKETS_S = [5, 10, 30, 60, 120, 300, 600, 1200, 1800, 3600, 7200, 21600];
19
+ // Meters that pass every instrument and attribute unchanged (they are ours).
20
+ exports.OWN_METER_NAMES = ["@easyweb/events", "@easyweb/logging/jobs", "project", "deployment"];
21
+ // The auto instruments we keep, and the only attributes each may carry.
22
+ exports.METRIC_ATTRIBUTE_ALLOWLIST = {
23
+ "http.server.request.duration": ["http.request.method", "http.route", "http.response.status_code"],
24
+ "http.client.request.duration": ["server.address", "http.request.method", "http.response.status_code"],
25
+ "db.client.operation.duration": ["db.operation.name", "db.collection.name"],
26
+ };
27
+ // Vendor hosts the services call, read from their configs. server.address is an
28
+ // attribute a customer can influence (a site URL scraped, a webhook), so anything
29
+ // not listed becomes "other". Internal cluster hosts reduce to their service label.
30
+ exports.KNOWN_HOSTS = new Set([
31
+ "api.anthropic.com", "openrouter.ai", "api.moonshot.ai", "api.voyageai.com", "api.dataforseo.com", "api.pexels.com", "images.pexels.com",
32
+ "api.cloudflare.com",
33
+ "api.doku.com", "api-sandbox.doku.com", "sandbox.doku.com",
34
+ "api.paddle.com", "sandbox-api.paddle.com",
35
+ "api.resend.com", "api.apify.com",
36
+ "api.rdash.id", "api.sandbox-rdash.id", "rdash-proxy.easyweb.id",
37
+ "www.googleapis.com", "oauth2.googleapis.com", "searchconsole.googleapis.com", "meet.googleapis.com",
38
+ "graph.facebook.com", "api.linkedin.com",
39
+ ]);
40
+ // Internal services, as the configmaps address them: the short name, name.ns, or the
41
+ // full cluster name. Only a listed service in a known namespace keeps its own label,
42
+ // so a customer-supplied *.svc.cluster.local URL cannot mint label values.
43
+ const INTERNAL_SERVICES = new Set([
44
+ "auth", "user", "subscription", "billing", "payment", "project", "sandbox", "notification",
45
+ "ai", "template", "media", "brand", "widget", "deployment", "domain", "moderation", "analytics", "admin",
46
+ "support", "memory", "design", "mcp", "marketing", "content", "blogging", "insight", "booking", "shop", "helpcenter", "partner",
47
+ "marketing-admin", "gitea", "umami", "prometheus", "tempo", "loki", "rabbitmq",
48
+ ]);
49
+ const INTERNAL_NAMESPACES = new Set(["easyweb-prod", "easyweb-observability"]);
50
+ function boundServerAddress(host) {
51
+ const h = host.toLowerCase();
52
+ if (exports.KNOWN_HOSTS.has(h))
53
+ return h;
54
+ const [svc = "", ns, ...rest] = h.split(".");
55
+ if (!INTERNAL_SERVICES.has(svc))
56
+ return "other";
57
+ if (ns === undefined)
58
+ return svc;
59
+ if (!INTERNAL_NAMESPACES.has(ns))
60
+ return "other";
61
+ if (rest.length === 0 || rest.join(".") === "svc.cluster.local")
62
+ return svc;
63
+ return "other";
64
+ }
65
+ // Views only rewrite the three instruments we keep. A wildcard DROP view cannot sit
66
+ // beside them: sdk-metrics collapses every view that matches one instrument onto the
67
+ // first storage registered, so the drop would swallow the allowlisted stream too. The
68
+ // instruments nobody listed are removed at the exporter instead (restrictExporter).
69
+ function metricViews() {
70
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
71
+ const { createAllowListAttributesProcessor } = require("@opentelemetry/sdk-metrics");
72
+ const bound = {
73
+ process: (attrs) => {
74
+ const host = attrs["server.address"];
75
+ return typeof host === "string" ? { ...attrs, "server.address": boundServerAddress(host) } : attrs;
76
+ },
77
+ };
78
+ return Object.entries(exports.METRIC_ATTRIBUTE_ALLOWLIST).map(([instrumentName, keys]) => ({
79
+ instrumentName,
80
+ attributesProcessors: [createAllowListAttributesProcessor(keys), ...(keys.includes("server.address") ? [bound] : [])],
81
+ }));
82
+ }
83
+ /** Keeps our own meters and the allowlisted instruments; every other scope or instrument is dropped. */
84
+ function keepAllowedMetrics(rm) {
85
+ return {
86
+ ...rm,
87
+ scopeMetrics: rm.scopeMetrics
88
+ .map((sm) => exports.OWN_METER_NAMES.includes(sm.scope.name) ? sm : { ...sm, metrics: sm.metrics.filter((m) => m.descriptor.name in exports.METRIC_ATTRIBUTE_ALLOWLIST) })
89
+ .filter((sm) => sm.metrics.length > 0),
90
+ };
91
+ }
92
+ function restrictExporter(inner) {
93
+ const out = {
94
+ export: (rm, done) => inner.export(keepAllowedMetrics(rm), done),
95
+ forceFlush: () => inner.forceFlush(),
96
+ shutdown: () => inner.shutdown(),
97
+ };
98
+ if (inner.selectAggregationTemporality)
99
+ out.selectAggregationTemporality = (t) => inner.selectAggregationTemporality(t);
100
+ if (inner.selectAggregation)
101
+ out.selectAggregation = (t) => inner.selectAggregation(t);
102
+ return out;
103
+ }
104
+ //# sourceMappingURL=metrics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"metrics.js","sourceRoot":"","sources":["../src/metrics.ts"],"names":[],"mappings":";;;AAQA,4BAEC;AAwCD,gDASC;AAMD,kCAaC;AAGD,gDAOC;AAED,4CASC;AAnGD,4CAAyD;AAGzD,kFAAkF;AAClF,wEAAwE;AACxE,iFAAiF;AAEjF,0FAA0F;AAC1F,SAAgB,QAAQ,CAAC,IAAY;IACnC,OAAO,aAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAEY,QAAA,eAAe,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAChF,QAAA,iBAAiB,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC;AAE/F,6EAA6E;AAChE,QAAA,eAAe,GAAG,CAAC,iBAAiB,EAAE,uBAAuB,EAAE,SAAS,EAAE,YAAY,CAAC,CAAC;AAErG,wEAAwE;AAC3D,QAAA,0BAA0B,GAA6B;IAClE,8BAA8B,EAAE,CAAC,qBAAqB,EAAE,YAAY,EAAE,2BAA2B,CAAC;IAClG,8BAA8B,EAAE,CAAC,gBAAgB,EAAE,qBAAqB,EAAE,2BAA2B,CAAC;IACtG,8BAA8B,EAAE,CAAC,mBAAmB,EAAE,oBAAoB,CAAC;CAC5E,CAAC;AAEF,gFAAgF;AAChF,kFAAkF;AAClF,oFAA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F,OAAO,GAAG,CAAC;AACb,CAAC"}
@@ -1,8 +1,12 @@
1
- import { NodeSDK } from "@opentelemetry/sdk-node";
1
+ import type { NodeSDK } from "@opentelemetry/sdk-node";
2
2
  import type { Instrumentation } from "@opentelemetry/instrumentation";
3
+ export declare function shouldStartMetrics(env: NodeJS.ProcessEnv): boolean;
3
4
  export declare function shouldStartTelemetry(env: NodeJS.ProcessEnv): boolean;
5
+ export declare function metricExportIntervalMs(env: NodeJS.ProcessEnv): number;
4
6
  export declare function telemetryServiceName(env: NodeJS.ProcessEnv): string;
5
7
  export declare function isProbePath(url: string | undefined): boolean;
8
+ export declare const REDACTED_QUERY_PARAMS: string[];
9
+ export declare function redactQuery(query: string): string;
6
10
  export declare function telemetryInstrumentations(): Instrumentation[];
7
11
  export declare function createTelemetrySdk(env: NodeJS.ProcessEnv): NodeSDK | null;
8
12
  //# sourceMappingURL=telemetry.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AActE,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,OAAO,CAGpE;AAED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,MAAM,CAEnE;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAI5D;AAED,wBAAgB,yBAAyB,IAAI,eAAe,EAAE,CAU7D;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,OAAO,GAAG,IAAI,CAQzE"}
1
+ {"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAiBtE,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,OAAO,CAGlE;AAED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,OAAO,CAEpE;AAED,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,MAAM,CAGrE;AAED,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,MAAM,CAEnE;AAED,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAI5D;AAMD,eAAO,MAAM,qBAAqB,UAGjC,CAAC;AAUF,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CASjD;AAED,wBAAgB,yBAAyB,IAAI,eAAe,EAAE,CA+C7D;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,OAAO,GAAG,IAAI,CAiCzE"}
package/dist/telemetry.js CHANGED
@@ -1,26 +1,37 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.REDACTED_QUERY_PARAMS = void 0;
4
+ exports.shouldStartMetrics = shouldStartMetrics;
3
5
  exports.shouldStartTelemetry = shouldStartTelemetry;
6
+ exports.metricExportIntervalMs = metricExportIntervalMs;
4
7
  exports.telemetryServiceName = telemetryServiceName;
5
8
  exports.isProbePath = isProbePath;
9
+ exports.redactQuery = redactQuery;
6
10
  exports.telemetryInstrumentations = telemetryInstrumentations;
7
11
  exports.createTelemetrySdk = createTelemetrySdk;
8
- const sdk_node_1 = require("@opentelemetry/sdk-node");
9
- const instrumentation_http_1 = require("@opentelemetry/instrumentation-http");
10
- const instrumentation_express_1 = require("@opentelemetry/instrumentation-express");
11
- const instrumentation_undici_1 = require("@opentelemetry/instrumentation-undici");
12
- const instrumentation_pg_1 = require("@opentelemetry/instrumentation-pg");
13
- const instrumentation_ioredis_1 = require("@opentelemetry/instrumentation-ioredis");
14
- const instrumentation_amqplib_1 = require("@opentelemetry/instrumentation-amqplib");
15
- const instrumentation_pino_1 = require("@opentelemetry/instrumentation-pino");
12
+ // The SDK and instrumentation packages are require()d lazily, after the gate:
13
+ // importing them costs ~100 ms and ~36 MB per process even when telemetry is off.
16
14
  // Deliberately imports nothing from ./logger or ./index: this file must load
17
15
  // before pino, http, pg, ... so the SDK can patch them as they are required.
18
16
  const PROBE_PATHS = new Set(["/health", "/livez", "/api/heartbeat"]);
19
- function shouldStartTelemetry(env) {
17
+ function shouldStartTraces(env) {
20
18
  if (env["OTEL_SDK_DISABLED"] === "true")
21
19
  return false;
22
20
  return Boolean(env["OTEL_EXPORTER_OTLP_ENDPOINT"] || env["OTEL_TRACES_EXPORTER"]);
23
21
  }
22
+ // Metrics have their own gate (ADR-0012): a traces endpoint alone never starts them.
23
+ function shouldStartMetrics(env) {
24
+ if (env["OTEL_SDK_DISABLED"] === "true")
25
+ return false;
26
+ return Boolean(env["OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"]);
27
+ }
28
+ function shouldStartTelemetry(env) {
29
+ return shouldStartTraces(env) || shouldStartMetrics(env);
30
+ }
31
+ function metricExportIntervalMs(env) {
32
+ const n = Number(env["OTEL_METRIC_EXPORT_INTERVAL"]);
33
+ return Number.isInteger(n) && n > 0 ? n : 30000;
34
+ }
24
35
  function telemetryServiceName(env) {
25
36
  return env["OTEL_SERVICE_NAME"] || env["SERVICE_NAME"] || "unknown-service";
26
37
  }
@@ -30,25 +41,114 @@ function isProbePath(url) {
30
41
  const path = url.split("?")[0] ?? "";
31
42
  return PROBE_PATHS.has(path);
32
43
  }
44
+ // Superset of the installed instrumentation-http and instrumentation-undici default
45
+ // lists (passing the option REPLACES the library default, so they are repeated here;
46
+ // a test fails when an upgrade adds a key) plus our own. Matched exactly,
47
+ // case-sensitive, like the library matchers.
48
+ exports.REDACTED_QUERY_PARAMS = [
49
+ "sig", "Signature", "AWSAccessKeyId", "X-Goog-Signature", "X-Amz-Signature", "X-Amz-Credential", "X-Amz-Security-Token",
50
+ "token", "code", "state", "refresh_token",
51
+ ];
52
+ function decodeKey(k) {
53
+ try {
54
+ return decodeURIComponent(k.replace(/\+/g, " "));
55
+ }
56
+ catch {
57
+ return k;
58
+ }
59
+ }
60
+ function redactQuery(query) {
61
+ const q = query.startsWith("?") ? query.slice(1) : query;
62
+ return q
63
+ .split("&")
64
+ .map((pair) => {
65
+ const [k = ""] = pair.split("=");
66
+ return exports.REDACTED_QUERY_PARAMS.includes(decodeKey(k)) ? `${k}=REDACTED` : pair;
67
+ })
68
+ .join("&");
69
+ }
33
70
  function telemetryInstrumentations() {
71
+ /* eslint-disable @typescript-eslint/no-require-imports */
72
+ const { HttpInstrumentation } = require("@opentelemetry/instrumentation-http");
73
+ const { ExpressInstrumentation } = require("@opentelemetry/instrumentation-express");
74
+ const { UndiciInstrumentation } = require("@opentelemetry/instrumentation-undici");
75
+ const { PgInstrumentation } = require("@opentelemetry/instrumentation-pg");
76
+ const { IORedisInstrumentation } = require("@opentelemetry/instrumentation-ioredis");
77
+ const { AmqplibInstrumentation } = require("@opentelemetry/instrumentation-amqplib");
78
+ const { PinoInstrumentation } = require("@opentelemetry/instrumentation-pino");
79
+ /* eslint-enable @typescript-eslint/no-require-imports */
34
80
  return [
35
- new instrumentation_http_1.HttpInstrumentation({ ignoreIncomingRequestHook: (req) => isProbePath(req.url) }),
36
- new instrumentation_express_1.ExpressInstrumentation(),
37
- new instrumentation_undici_1.UndiciInstrumentation(),
38
- new instrumentation_pg_1.PgInstrumentation(),
39
- new instrumentation_ioredis_1.IORedisInstrumentation(),
40
- new instrumentation_amqplib_1.AmqplibInstrumentation(),
41
- new instrumentation_pino_1.PinoInstrumentation(),
81
+ new HttpInstrumentation({
82
+ ignoreIncomingRequestHook: (req) => isProbePath(req.url),
83
+ requireParentforOutgoingSpans: true,
84
+ redactedQueryParamsServer: exports.REDACTED_QUERY_PARAMS,
85
+ redactedQueryParams: exports.REDACTED_QUERY_PARAMS,
86
+ }),
87
+ new ExpressInstrumentation(),
88
+ // undici has no redaction option; it records url.full and url.query with only
89
+ // its built-in list, so the request hook overwrites both.
90
+ new UndiciInstrumentation({
91
+ requireParentforSpans: true,
92
+ requestHook: (span, request) => {
93
+ const q = request.path.indexOf("?");
94
+ if (q < 0)
95
+ return;
96
+ const query = redactQuery(request.path.slice(q));
97
+ span.setAttribute("url.query", query);
98
+ span.setAttribute("url.full", `${request.origin}${request.path.slice(0, q)}?${query}`);
99
+ },
100
+ }),
101
+ new PgInstrumentation({ requireParentSpan: true }),
102
+ // Command name only: arguments carry login emails, client IPs and BullMQ job data.
103
+ new IORedisInstrumentation({ dbStatementSerializer: (cmd) => cmd }),
104
+ new AmqplibInstrumentation(),
105
+ new PinoInstrumentation({
106
+ // Traces only: no OTLP log records from every pino line.
107
+ disableLogSending: true,
108
+ // Only sampled lines carry ids; an unsampled trace id is a dead link.
109
+ logHook: (span, record) => {
110
+ if ((span.spanContext().traceFlags & 1) === 0) {
111
+ delete record["trace_id"];
112
+ delete record["span_id"];
113
+ delete record["trace_flags"];
114
+ }
115
+ },
116
+ }),
42
117
  ];
43
118
  }
44
119
  function createTelemetrySdk(env) {
45
120
  if (!shouldStartTelemetry(env))
46
121
  return null;
122
+ const traces = shouldStartTraces(env);
123
+ const metrics = shouldStartMetrics(env);
124
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
125
+ const { NodeSDK: Sdk } = require("@opentelemetry/sdk-node");
126
+ let metricReaders = [];
127
+ let views = [];
128
+ if (metrics) {
129
+ /* eslint-disable @typescript-eslint/no-require-imports */
130
+ const { PeriodicExportingMetricReader, AggregationTemporality } = require("@opentelemetry/sdk-metrics");
131
+ const { OTLPMetricExporter } = require("@opentelemetry/exporter-metrics-otlp-proto");
132
+ const { metricViews, restrictExporter } = require("./metrics");
133
+ /* eslint-enable @typescript-eslint/no-require-imports */
134
+ // The endpoint comes from OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, read by the exporter.
135
+ metricReaders = [new PeriodicExportingMetricReader({
136
+ exporter: restrictExporter(new OTLPMetricExporter({ temporalityPreference: AggregationTemporality.CUMULATIVE })),
137
+ exportIntervalMillis: metricExportIntervalMs(env),
138
+ })];
139
+ views = metricViews();
140
+ }
47
141
  // No traceExporter: OTEL_TRACES_EXPORTER, OTEL_EXPORTER_OTLP_* and
48
- // OTEL_TRACES_SAMPLER* are read from the environment by the SDK.
49
- return new sdk_node_1.NodeSDK({
142
+ // OTEL_TRACES_SAMPLER* are read from the environment by the SDK. The empty
143
+ // arrays stop the SDK defaulting logs (always) and metrics or traces (when their
144
+ // gate is closed) to an otlp exporter on localhost.
145
+ return new Sdk({
50
146
  serviceName: telemetryServiceName(env),
51
147
  instrumentations: telemetryInstrumentations(),
148
+ metricReaders,
149
+ views,
150
+ logRecordProcessors: [],
151
+ ...(traces ? {} : { spanProcessors: [] }),
52
152
  });
53
153
  }
54
154
  //# sourceMappingURL=telemetry.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../src/telemetry.ts"],"names":[],"mappings":";;AAeA,oDAGC;AAED,oDAEC;AAED,kCAIC;AAED,8DAUC;AAED,gDAQC;AAlDD,sDAAkD;AAElD,8EAA0E;AAC1E,oFAAgF;AAChF,kFAA8E;AAC9E,0EAAsE;AACtE,oFAAgF;AAChF,oFAAgF;AAChF,8EAA0E;AAE1E,6EAA6E;AAC7E,6EAA6E;AAE7E,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAErE,SAAgB,oBAAoB,CAAC,GAAsB;IACzD,IAAI,GAAG,CAAC,mBAAmB,CAAC,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IACtD,OAAO,OAAO,CAAC,GAAG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,EAAE,kBAAkB,EAAE,GAAG,OAAO,CAAC,4CAA4C,CAAgE,CAAC;QACpJ,MAAM,EAAE,WAAW,EAAE,gBAAgB,EAAE,GAAG,OAAO,CAAC,WAAW,CAA+B,CAAC;QAC7F,yDAAyD;QACzD,qFAAqF;QACrF,aAAa,GAAG,CAAC,IAAI,6BAA6B,CAAC;gBACjD,QAAQ,EAAE,gBAAgB,CAAC,IAAI,kBAAkB,CAAC,EAAE,qBAAqB,EAAE,sBAAsB,CAAC,UAAU,EAAE,CAAC,CAAC;gBAChH,oBAAoB,EAAE,sBAAsB,CAAC,GAAG,CAAC;aAClD,CAAC,CAAC,CAAC;QACJ,KAAK,GAAG,WAAW,EAAE,CAAC;IACxB,CAAC;IACD,mEAAmE;IACnE,2EAA2E;IAC3E,iFAAiF;IACjF,oDAAoD;IACpD,OAAO,IAAI,GAAG,CAAC;QACb,WAAW,EAAE,oBAAoB,CAAC,GAAG,CAAC;QACtC,gBAAgB,EAAE,yBAAyB,EAAE;QAC7C,aAAa;QACb,KAAK;QACL,mBAAmB,EAAE,EAAE;QACvB,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,EAAE,EAAE,CAAC;KAC1C,CAAC,CAAC;AACL,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@easyweb/logging",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Shared structured logging for Easyweb microservices: one pino configuration, request-scoped context over AsyncLocalStorage, an HTTP access log, and the redaction every service needs before its logs leave the pod",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -28,7 +28,7 @@
28
28
  "test": "jest",
29
29
  "typecheck": "tsc --noEmit",
30
30
  "typecheck:test": "tsc -p tsconfig.test.json --noEmit",
31
- "check:telemetry": "npm run build && node scripts/check-telemetry.js"
31
+ "check:telemetry": "npm run build && node scripts/check-telemetry.js && node scripts/check-telemetry-export.js"
32
32
  },
33
33
  "keywords": [
34
34
  "microservices",
@@ -68,6 +68,7 @@
68
68
  },
69
69
  "dependencies": {
70
70
  "@opentelemetry/api": "^1.10.0",
71
+ "@opentelemetry/exporter-metrics-otlp-proto": "^0.301.2",
71
72
  "@opentelemetry/instrumentation": "^0.301.2",
72
73
  "@opentelemetry/instrumentation-amqplib": "^0.72.0",
73
74
  "@opentelemetry/instrumentation-express": "^0.73.0",
@@ -76,6 +77,7 @@
76
77
  "@opentelemetry/instrumentation-pg": "^0.78.0",
77
78
  "@opentelemetry/instrumentation-pino": "^0.71.0",
78
79
  "@opentelemetry/instrumentation-undici": "^0.35.1",
80
+ "@opentelemetry/sdk-metrics": "^3.1.1",
79
81
  "@opentelemetry/sdk-node": "^0.301.2"
80
82
  }
81
83
  }