@open-mercato/telemetry 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8572.1.85986dc508

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.
@@ -27,14 +27,19 @@ function reportError(error, ctx) {
27
27
  const safeError = new Error(serialized.message);
28
28
  safeError.name = serialized.name;
29
29
  safeError.stack = serialized.stack;
30
- logger.error("Application error reported", { ...safeAttributes, err: safeError });
30
+ const output = ctx?.logger ?? logger;
31
+ try {
32
+ output.error("Application error reported", { ...safeAttributes, err: safeError });
33
+ } catch {
34
+ logger.error("Application error reported", { ...safeAttributes, err: safeError });
35
+ }
31
36
  counter("om.errors", 1, errorLabels(ctx?.module, code));
32
- reportToProvider(serialized, ctx?.module, code, safeAttributes);
37
+ reportToProvider(serialized, ctx?.module, code, safeAttributes, output);
33
38
  } finally {
34
39
  reporting = false;
35
40
  }
36
41
  }
37
- function reportToProvider(serialized, module, code, safeAttributes) {
42
+ function reportToProvider(serialized, module, code, safeAttributes, output) {
38
43
  try {
39
44
  const provider = getActiveProvider();
40
45
  if (!provider.reportError) return;
@@ -42,7 +47,11 @@ function reportToProvider(serialized, module, code, safeAttributes) {
42
47
  delete providerAttributes[CODE_ATTRIBUTE];
43
48
  provider.reportError(serialized, { module, code, attributes: providerAttributes });
44
49
  } catch (sinkError) {
45
- logger.warn("Telemetry provider error sink failed", { err: sinkError });
50
+ try {
51
+ output.warn("Telemetry provider error sink failed", { err: sinkError });
52
+ } catch {
53
+ logger.warn("Telemetry provider error sink failed", { err: sinkError });
54
+ }
46
55
  }
47
56
  }
48
57
  function errorLabels(module, code) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/facade/report-error.ts"],
4
- "sourcesContent": ["import type { Attributes, LogRecord } from '../types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'\nimport { currentSpan } from './tracer'\nimport { serializeError } from './serialize'\nimport { counter } from './meter'\nimport { redactAttributes } from './redact'\nimport { getActiveProvider } from '../provider/registry'\n\nconst logger = createLogger('telemetry')\n\n/**\n * The single attribute name the code is published under, on all three built-in\n * surfaces. One spelling, so a query written against the span also works against\n * the log record and the metric.\n */\nconst CODE_ATTRIBUTE = 'error.code'\n\nexport type ReportErrorContext = {\n /** Owning module, e.g. 'orders'. Used as a metric label. */\n module?: string\n /**\n * Stable, enumerated fingerprint for this failure reason, as `module.reason`\n * (`data_sync.item_failed`, `queue.job_failed`). NEVER an interpolated string:\n * it is a metric label, and it is what the backend groups on. A value that is\n * not that shape is dropped here rather than published \u2014 see `groupableCode`.\n *\n * Grouping is why this exists. Sentry fingerprints on the stack trace and New\n * Relic on the error class, so a funnel that synthesizes one error type at one\n * line \u2014 the integration-log tee \u2014 collapses every caller into a single issue\n * without a discriminator, and SigNoz has no error grouping of its own at all.\n */\n code?: string\n /** Low-cardinality, NO-PII attributes (ids ok, never names/content). */\n attributes?: Attributes\n}\n\n/**\n * Re-entrancy guard, not a rate limit. A plain module-level flag, which is\n * sufficient only because `reportError` runs synchronously end to end: a nested\n * call can therefore come from nothing but the reporting path itself \u2014 a provider\n * whose error sink reports its own failures, a log bridge that reports. One flag\n * turns that recursion into a no-op while keeping the original report intact. Add\n * an `await` anywhere in this funnel and the flag has to become async-context\n * scoped, or concurrent reports will suppress each other.\n *\n * Volume is deliberately NOT policed here: the backend (quotas, spike\n * protection), the collector (filter/sample processors) and the SDK's batch\n * processors already bound it, and each of them drops where the drop is visible\n * and adjustable. A fourth limiter in this function would be the only one that\n * loses an error irrecoverably at the source.\n */\nlet reporting = false\n\n/**\n * The error funnel. Additive \u2014 existing `console.error` calls stay valid; this\n * is the path that reaches the active backend. It:\n * 1. records the exception on the active span (errors-as-span-events),\n * 2. emits a structured error log (stack only \u2014 no PII payloads),\n * 3. increments the `om.errors` counter, labeled by `module` and `error.code`,\n * 4. hands the serialized error to the provider's own error sink when it has\n * one (issue-tracker-shaped backends), in ADDITION to the three above so no\n * path can lose signal.\n *\n * Every reported error is emitted; there is no sampling or suppression here.\n */\nexport function reportError(error: unknown, ctx?: ReportErrorContext): void {\n if (reporting) return\n reporting = true\n try {\n // Narrowed once, here, rather than at each caller: the property being\n // protected \u2014 a metric label is bounded and never redacted \u2014 belongs to this\n // funnel, and `code` reaches it from adapters and third-party modules. A\n // caller with a malformed code reports exactly as one with no code at all.\n const code = groupableCode(ctx?.code)\n const span = currentSpan()\n if (span) {\n span.recordException(error)\n span.setStatus('error')\n // Span-level, because `recordException` takes no attributes. With several\n // reports on one span the last code wins; the per-error code always\n // survives on the log record and the metric.\n if (code) span.setAttribute(CODE_ATTRIBUTE, code)\n }\n\n const serialized = serializeError(error)\n const attributes: Attributes = { ...(ctx?.attributes ?? {}) }\n if (ctx?.module) attributes.module = ctx.module\n if (code) attributes[CODE_ATTRIBUTE] = code\n const safeAttributes = redactAttributes(attributes)\n\n const safeError = new Error(serialized.message)\n safeError.name = serialized.name\n safeError.stack = serialized.stack\n logger.error('Application error reported', { ...safeAttributes, err: safeError })\n counter('om.errors', 1, errorLabels(ctx?.module, code))\n\n reportToProvider(serialized, ctx?.module, code, safeAttributes)\n } finally {\n reporting = false\n }\n}\n\n/**\n * Hand the error to the provider's own sink, when it has one.\n *\n * Guarded, and that is the whole point of the function: `reportError` is called\n * from `catch` blocks that still have work to do after it \u2014 the API dispatcher\n * records a duration metric, emits its lifecycle event and rethrows the original\n * error; the CRUD factory returns a 500 carrying its `x-request-id`. This hook is\n * implemented by third parties, so one that throws would take all of that with it\n * and replace the caller's error with the telemetry provider's. The interface\n * documents the hook as non-throwing; this is what makes that a property of the\n * funnel rather than a request to its implementors.\n */\nfunction reportToProvider(\n serialized: NonNullable<LogRecord['error']>,\n module: string | undefined,\n code: string | undefined,\n safeAttributes: Attributes,\n): void {\n try {\n const provider = getActiveProvider()\n if (!provider.reportError) return\n // `code` travels in the context. Repeating it in the attributes would land it\n // in a provider's tags AND its extra data for anyone following the README recipe.\n const providerAttributes: Attributes = { ...safeAttributes }\n delete providerAttributes[CODE_ATTRIBUTE]\n provider.reportError(serialized, { module, code, attributes: providerAttributes })\n } catch (sinkError) {\n logger.warn('Telemetry provider error sink failed', { err: sinkError as Error })\n }\n}\n\nfunction errorLabels(module?: string, code?: string): Attributes | undefined {\n if (!module && !code) return undefined\n const labels: Attributes = {}\n if (module) labels.module = module\n if (code) labels[CODE_ATTRIBUTE] = code\n return labels\n}\n"],
5
- "mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,sBAAsB;AAC/B,SAAS,eAAe;AACxB,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAElC,MAAM,SAAS,aAAa,WAAW;AAOvC,MAAM,iBAAiB;AAoCvB,IAAI,YAAY;AAcT,SAAS,YAAY,OAAgB,KAAgC;AAC1E,MAAI,UAAW;AACf,cAAY;AACZ,MAAI;AAKF,UAAM,OAAO,cAAc,KAAK,IAAI;AACpC,UAAM,OAAO,YAAY;AACzB,QAAI,MAAM;AACR,WAAK,gBAAgB,KAAK;AAC1B,WAAK,UAAU,OAAO;AAItB,UAAI,KAAM,MAAK,aAAa,gBAAgB,IAAI;AAAA,IAClD;AAEA,UAAM,aAAa,eAAe,KAAK;AACvC,UAAM,aAAyB,EAAE,GAAI,KAAK,cAAc,CAAC,EAAG;AAC5D,QAAI,KAAK,OAAQ,YAAW,SAAS,IAAI;AACzC,QAAI,KAAM,YAAW,cAAc,IAAI;AACvC,UAAM,iBAAiB,iBAAiB,UAAU;AAElD,UAAM,YAAY,IAAI,MAAM,WAAW,OAAO;AAC9C,cAAU,OAAO,WAAW;AAC5B,cAAU,QAAQ,WAAW;AAC7B,WAAO,MAAM,8BAA8B,EAAE,GAAG,gBAAgB,KAAK,UAAU,CAAC;AAChF,YAAQ,aAAa,GAAG,YAAY,KAAK,QAAQ,IAAI,CAAC;AAEtD,qBAAiB,YAAY,KAAK,QAAQ,MAAM,cAAc;AAAA,EAChE,UAAE;AACA,gBAAY;AAAA,EACd;AACF;AAcA,SAAS,iBACP,YACA,QACA,MACA,gBACM;AACN,MAAI;AACF,UAAM,WAAW,kBAAkB;AACnC,QAAI,CAAC,SAAS,YAAa;AAG3B,UAAM,qBAAiC,EAAE,GAAG,eAAe;AAC3D,WAAO,mBAAmB,cAAc;AACxC,aAAS,YAAY,YAAY,EAAE,QAAQ,MAAM,YAAY,mBAAmB,CAAC;AAAA,EACnF,SAAS,WAAW;AAClB,WAAO,KAAK,wCAAwC,EAAE,KAAK,UAAmB,CAAC;AAAA,EACjF;AACF;AAEA,SAAS,YAAY,QAAiB,MAAuC;AAC3E,MAAI,CAAC,UAAU,CAAC,KAAM,QAAO;AAC7B,QAAM,SAAqB,CAAC;AAC5B,MAAI,OAAQ,QAAO,SAAS;AAC5B,MAAI,KAAM,QAAO,cAAc,IAAI;AACnC,SAAO;AACT;",
4
+ "sourcesContent": ["import type { Attributes, LogRecord } from '../types'\nimport { createLogger, type Logger } from '@open-mercato/shared/lib/logger'\nimport { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'\nimport { currentSpan } from './tracer'\nimport { serializeError } from './serialize'\nimport { counter } from './meter'\nimport { redactAttributes } from './redact'\nimport { getActiveProvider } from '../provider/registry'\n\nconst logger = createLogger('telemetry')\n\n/**\n * The single attribute name the code is published under, on all three built-in\n * surfaces. One spelling, so a query written against the span also works against\n * the log record and the metric.\n */\nconst CODE_ATTRIBUTE = 'error.code'\n\nexport type ReportErrorContext = {\n logger?: Pick<Logger, 'error' | 'warn'>\n /** Owning module, e.g. 'orders'. Used as a metric label. */\n module?: string\n /**\n * Stable, enumerated fingerprint for this failure reason, as `module.reason`\n * (`data_sync.item_failed`, `queue.job_failed`). NEVER an interpolated string:\n * it is a metric label, and it is what the backend groups on. A value that is\n * not that shape is dropped here rather than published \u2014 see `groupableCode`.\n *\n * Grouping is why this exists. Sentry fingerprints on the stack trace and New\n * Relic on the error class, so a funnel that synthesizes one error type at one\n * line \u2014 the integration-log tee \u2014 collapses every caller into a single issue\n * without a discriminator, and SigNoz has no error grouping of its own at all.\n */\n code?: string\n /** Low-cardinality, NO-PII attributes (ids ok, never names/content). */\n attributes?: Attributes\n}\n\n/**\n * Re-entrancy guard, not a rate limit. A plain module-level flag, which is\n * sufficient only because `reportError` runs synchronously end to end: a nested\n * call can therefore come from nothing but the reporting path itself \u2014 a provider\n * whose error sink reports its own failures, a log bridge that reports. One flag\n * turns that recursion into a no-op while keeping the original report intact. Add\n * an `await` anywhere in this funnel and the flag has to become async-context\n * scoped, or concurrent reports will suppress each other.\n *\n * Volume is deliberately NOT policed here: the backend (quotas, spike\n * protection), the collector (filter/sample processors) and the SDK's batch\n * processors already bound it, and each of them drops where the drop is visible\n * and adjustable. A fourth limiter in this function would be the only one that\n * loses an error irrecoverably at the source.\n */\nlet reporting = false\n\n/**\n * The error funnel. Additive \u2014 existing `console.error` calls stay valid; this\n * is the path that reaches the active backend. It:\n * 1. records the exception on the active span (errors-as-span-events),\n * 2. emits a structured error log (stack only \u2014 no PII payloads),\n * 3. increments the `om.errors` counter, labeled by `module` and `error.code`,\n * 4. hands the serialized error to the provider's own error sink when it has\n * one (issue-tracker-shaped backends), in ADDITION to the three above so no\n * path can lose signal.\n *\n * Every reported error is emitted; there is no sampling or suppression here.\n */\nexport function reportError(error: unknown, ctx?: ReportErrorContext): void {\n if (reporting) return\n reporting = true\n try {\n // Narrowed once, here, rather than at each caller: the property being\n // protected \u2014 a metric label is bounded and never redacted \u2014 belongs to this\n // funnel, and `code` reaches it from adapters and third-party modules. A\n // caller with a malformed code reports exactly as one with no code at all.\n const code = groupableCode(ctx?.code)\n const span = currentSpan()\n if (span) {\n span.recordException(error)\n span.setStatus('error')\n // Span-level, because `recordException` takes no attributes. With several\n // reports on one span the last code wins; the per-error code always\n // survives on the log record and the metric.\n if (code) span.setAttribute(CODE_ATTRIBUTE, code)\n }\n\n const serialized = serializeError(error)\n const attributes: Attributes = { ...(ctx?.attributes ?? {}) }\n if (ctx?.module) attributes.module = ctx.module\n if (code) attributes[CODE_ATTRIBUTE] = code\n const safeAttributes = redactAttributes(attributes)\n\n const safeError = new Error(serialized.message)\n safeError.name = serialized.name\n safeError.stack = serialized.stack\n const output = ctx?.logger ?? logger\n try {\n output.error('Application error reported', { ...safeAttributes, err: safeError })\n } catch {\n logger.error('Application error reported', { ...safeAttributes, err: safeError })\n }\n counter('om.errors', 1, errorLabels(ctx?.module, code))\n\n reportToProvider(serialized, ctx?.module, code, safeAttributes, output)\n } finally {\n reporting = false\n }\n}\n\n/**\n * Hand the error to the provider's own sink, when it has one.\n *\n * Guarded, and that is the whole point of the function: `reportError` is called\n * from `catch` blocks that still have work to do after it \u2014 the API dispatcher\n * records a duration metric, emits its lifecycle event and rethrows the original\n * error; the CRUD factory returns a 500 carrying its `x-request-id`. This hook is\n * implemented by third parties, so one that throws would take all of that with it\n * and replace the caller's error with the telemetry provider's. The interface\n * documents the hook as non-throwing; this is what makes that a property of the\n * funnel rather than a request to its implementors.\n */\nfunction reportToProvider(\n serialized: NonNullable<LogRecord['error']>,\n module: string | undefined,\n code: string | undefined,\n safeAttributes: Attributes,\n output: Pick<Logger, 'warn'>,\n): void {\n try {\n const provider = getActiveProvider()\n if (!provider.reportError) return\n // `code` travels in the context. Repeating it in the attributes would land it\n // in a provider's tags AND its extra data for anyone following the README recipe.\n const providerAttributes: Attributes = { ...safeAttributes }\n delete providerAttributes[CODE_ATTRIBUTE]\n provider.reportError(serialized, { module, code, attributes: providerAttributes })\n } catch (sinkError) {\n try {\n output.warn('Telemetry provider error sink failed', { err: sinkError as Error })\n } catch {\n logger.warn('Telemetry provider error sink failed', { err: sinkError as Error })\n }\n }\n}\n\nfunction errorLabels(module?: string, code?: string): Attributes | undefined {\n if (!module && !code) return undefined\n const labels: Attributes = {}\n if (module) labels.module = module\n if (code) labels[CODE_ATTRIBUTE] = code\n return labels\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAiC;AAC1C,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB;AAC5B,SAAS,sBAAsB;AAC/B,SAAS,eAAe;AACxB,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAElC,MAAM,SAAS,aAAa,WAAW;AAOvC,MAAM,iBAAiB;AAqCvB,IAAI,YAAY;AAcT,SAAS,YAAY,OAAgB,KAAgC;AAC1E,MAAI,UAAW;AACf,cAAY;AACZ,MAAI;AAKF,UAAM,OAAO,cAAc,KAAK,IAAI;AACpC,UAAM,OAAO,YAAY;AACzB,QAAI,MAAM;AACR,WAAK,gBAAgB,KAAK;AAC1B,WAAK,UAAU,OAAO;AAItB,UAAI,KAAM,MAAK,aAAa,gBAAgB,IAAI;AAAA,IAClD;AAEA,UAAM,aAAa,eAAe,KAAK;AACvC,UAAM,aAAyB,EAAE,GAAI,KAAK,cAAc,CAAC,EAAG;AAC5D,QAAI,KAAK,OAAQ,YAAW,SAAS,IAAI;AACzC,QAAI,KAAM,YAAW,cAAc,IAAI;AACvC,UAAM,iBAAiB,iBAAiB,UAAU;AAElD,UAAM,YAAY,IAAI,MAAM,WAAW,OAAO;AAC9C,cAAU,OAAO,WAAW;AAC5B,cAAU,QAAQ,WAAW;AAC7B,UAAM,SAAS,KAAK,UAAU;AAC9B,QAAI;AACF,aAAO,MAAM,8BAA8B,EAAE,GAAG,gBAAgB,KAAK,UAAU,CAAC;AAAA,IAClF,QAAQ;AACN,aAAO,MAAM,8BAA8B,EAAE,GAAG,gBAAgB,KAAK,UAAU,CAAC;AAAA,IAClF;AACA,YAAQ,aAAa,GAAG,YAAY,KAAK,QAAQ,IAAI,CAAC;AAEtD,qBAAiB,YAAY,KAAK,QAAQ,MAAM,gBAAgB,MAAM;AAAA,EACxE,UAAE;AACA,gBAAY;AAAA,EACd;AACF;AAcA,SAAS,iBACP,YACA,QACA,MACA,gBACA,QACM;AACN,MAAI;AACF,UAAM,WAAW,kBAAkB;AACnC,QAAI,CAAC,SAAS,YAAa;AAG3B,UAAM,qBAAiC,EAAE,GAAG,eAAe;AAC3D,WAAO,mBAAmB,cAAc;AACxC,aAAS,YAAY,YAAY,EAAE,QAAQ,MAAM,YAAY,mBAAmB,CAAC;AAAA,EACnF,SAAS,WAAW;AAClB,QAAI;AACF,aAAO,KAAK,wCAAwC,EAAE,KAAK,UAAmB,CAAC;AAAA,IACjF,QAAQ;AACN,aAAO,KAAK,wCAAwC,EAAE,KAAK,UAAmB,CAAC;AAAA,IACjF;AAAA,EACF;AACF;AAEA,SAAS,YAAY,QAAiB,MAAuC;AAC3E,MAAI,CAAC,UAAU,CAAC,KAAM,QAAO;AAC7B,QAAM,SAAqB,CAAC;AAC5B,MAAI,OAAQ,QAAO,SAAS;AAC5B,MAAI,KAAM,QAAO,cAAc,IAAI;AACnC,SAAO;AACT;",
6
6
  "names": []
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/telemetry",
3
- "version": "0.11.1-develop.8557.1.e615240a3e",
3
+ "version": "0.11.1-develop.8572.1.85986dc508",
4
4
  "license": "MIT",
5
5
  "description": "Vendor-neutral spans, metrics, and error reporting backed by a pluggable OTLP provider. Off by default; the telemetry runtime is loaded only when explicitly enabled.",
6
6
  "type": "module",
@@ -38,7 +38,7 @@
38
38
  }
39
39
  },
40
40
  "dependencies": {
41
- "@open-mercato/shared": "0.11.1-develop.8557.1.e615240a3e"
41
+ "@open-mercato/shared": "0.11.1-develop.8572.1.85986dc508"
42
42
  },
43
43
  "peerDependencies": {
44
44
  "react": ">=18.0.0"
@@ -1,5 +1,6 @@
1
1
  import { reportError } from '../index'
2
2
  import {
3
+ createLogger,
3
4
  resetLoggerExtension,
4
5
  resetLoggerRegistry,
5
6
  } from '@open-mercato/shared/lib/logger'
@@ -295,3 +296,51 @@ describe('reportError policy', () => {
295
296
  expect(errorLogs(logs)).toHaveLength(1)
296
297
  })
297
298
  })
299
+
300
+
301
+ describe('reportError scoped local presentation', () => {
302
+ beforeEach(() => {
303
+ resetActiveProvider()
304
+ resetTelemetryInit()
305
+ resetTelemetryEnvCache()
306
+ resetLoggerExtension()
307
+ resetLoggerRegistry()
308
+ resetTelemetryRuntime()
309
+ })
310
+ afterEach(() => { delete process.env.TELEMETRY_BACKEND })
311
+
312
+ it('preserves every telemetry sink while presenting local errors and provider warnings as NDJSON', async () => {
313
+ const { provider, span, logs, metrics, reported } = recordingProvider({
314
+ withErrorSink: true, onReportError: () => { throw new Error('provider unavailable') },
315
+ })
316
+ await activate(provider)
317
+ const lines: string[] = []
318
+ const scoped = createLogger('telemetry', { write: record => {
319
+ lines.push(JSON.stringify({ level: record.level, message: record.message }))
320
+ } })
321
+ reportError(new Error('fixture rejected'), { module: 'backups', code: 'backups.command_failed', logger: scoped })
322
+ expect(lines.map(line => JSON.parse(line))).toEqual([
323
+ { level: 'error', message: 'Application error reported' },
324
+ { level: 'warn', message: 'Telemetry provider error sink failed' },
325
+ ])
326
+ expect(span.exceptions).toHaveLength(1)
327
+ expect(span.status).toBe('error')
328
+ expect(errorLogs(logs)).toHaveLength(1)
329
+ expect(metrics.some(point => point.name === 'om.errors')).toBe(true)
330
+ expect(reported).toHaveLength(1)
331
+ })
332
+
333
+ it('falls back to canonical logging without losing signals when an injected logger throws', async () => {
334
+ const { provider, span, logs, metrics, reported } = recordingProvider({ withErrorSink: true })
335
+ await activate(provider)
336
+ const throwing = () => { throw new Error('injected logger failed') }
337
+ expect(() => reportError(new Error('original failure'), {
338
+ module: 'backups', code: 'backups.command_failed', logger: { error: throwing, warn: throwing },
339
+ })).not.toThrow()
340
+ expect(span.exceptions).toHaveLength(1)
341
+ expect(errorLogs(logs)).toHaveLength(1)
342
+ expect(metrics.some(point => point.name === 'om.errors')).toBe(true)
343
+ expect(reported).toHaveLength(1)
344
+ })
345
+
346
+ })
@@ -1,5 +1,5 @@
1
1
  import type { Attributes, LogRecord } from '../types'
2
- import { createLogger } from '@open-mercato/shared/lib/logger'
2
+ import { createLogger, type Logger } from '@open-mercato/shared/lib/logger'
3
3
  import { groupableCode } from '@open-mercato/shared/lib/telemetry/error-code'
4
4
  import { currentSpan } from './tracer'
5
5
  import { serializeError } from './serialize'
@@ -17,6 +17,7 @@ const logger = createLogger('telemetry')
17
17
  const CODE_ATTRIBUTE = 'error.code'
18
18
 
19
19
  export type ReportErrorContext = {
20
+ logger?: Pick<Logger, 'error' | 'warn'>
20
21
  /** Owning module, e.g. 'orders'. Used as a metric label. */
21
22
  module?: string
22
23
  /**
@@ -92,10 +93,15 @@ export function reportError(error: unknown, ctx?: ReportErrorContext): void {
92
93
  const safeError = new Error(serialized.message)
93
94
  safeError.name = serialized.name
94
95
  safeError.stack = serialized.stack
95
- logger.error('Application error reported', { ...safeAttributes, err: safeError })
96
+ const output = ctx?.logger ?? logger
97
+ try {
98
+ output.error('Application error reported', { ...safeAttributes, err: safeError })
99
+ } catch {
100
+ logger.error('Application error reported', { ...safeAttributes, err: safeError })
101
+ }
96
102
  counter('om.errors', 1, errorLabels(ctx?.module, code))
97
103
 
98
- reportToProvider(serialized, ctx?.module, code, safeAttributes)
104
+ reportToProvider(serialized, ctx?.module, code, safeAttributes, output)
99
105
  } finally {
100
106
  reporting = false
101
107
  }
@@ -118,6 +124,7 @@ function reportToProvider(
118
124
  module: string | undefined,
119
125
  code: string | undefined,
120
126
  safeAttributes: Attributes,
127
+ output: Pick<Logger, 'warn'>,
121
128
  ): void {
122
129
  try {
123
130
  const provider = getActiveProvider()
@@ -128,7 +135,11 @@ function reportToProvider(
128
135
  delete providerAttributes[CODE_ATTRIBUTE]
129
136
  provider.reportError(serialized, { module, code, attributes: providerAttributes })
130
137
  } catch (sinkError) {
131
- logger.warn('Telemetry provider error sink failed', { err: sinkError as Error })
138
+ try {
139
+ output.warn('Telemetry provider error sink failed', { err: sinkError as Error })
140
+ } catch {
141
+ logger.warn('Telemetry provider error sink failed', { err: sinkError as Error })
142
+ }
132
143
  }
133
144
  }
134
145