@cloudjun/otel-kit 0.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.
Files changed (47) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +346 -0
  4. package/README.md +346 -0
  5. package/dist/error-record.d.ts +41 -0
  6. package/dist/error-record.js +107 -0
  7. package/dist/error-record.js.map +1 -0
  8. package/dist/error-telemetry.d.ts +50 -0
  9. package/dist/error-telemetry.js +70 -0
  10. package/dist/error-telemetry.js.map +1 -0
  11. package/dist/http/client-ip.d.ts +45 -0
  12. package/dist/http/client-ip.js +112 -0
  13. package/dist/http/client-ip.js.map +1 -0
  14. package/dist/http/http-logger.middleware.d.ts +120 -0
  15. package/dist/http/http-logger.middleware.js +371 -0
  16. package/dist/http/http-logger.middleware.js.map +1 -0
  17. package/dist/index.d.ts +15 -0
  18. package/dist/index.js +38 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/init-observability.d.ts +88 -0
  21. package/dist/init-observability.js +368 -0
  22. package/dist/init-observability.js.map +1 -0
  23. package/dist/metrics.d.ts +19 -0
  24. package/dist/metrics.js +25 -0
  25. package/dist/metrics.js.map +1 -0
  26. package/dist/nest/otel-error.interceptor.d.ts +41 -0
  27. package/dist/nest/otel-error.interceptor.js +71 -0
  28. package/dist/nest/otel-error.interceptor.js.map +1 -0
  29. package/dist/nest/real-ip.middleware.d.ts +29 -0
  30. package/dist/nest/real-ip.middleware.js +63 -0
  31. package/dist/nest/real-ip.middleware.js.map +1 -0
  32. package/dist/nest.d.ts +6 -0
  33. package/dist/nest.js +14 -0
  34. package/dist/nest.js.map +1 -0
  35. package/dist/register.d.ts +2 -0
  36. package/dist/register.js +15 -0
  37. package/dist/register.js.map +1 -0
  38. package/dist/trace-context.d.ts +10 -0
  39. package/dist/trace-context.js +26 -0
  40. package/dist/trace-context.js.map +1 -0
  41. package/dist/tracing.d.ts +47 -0
  42. package/dist/tracing.js +54 -0
  43. package/dist/tracing.js.map +1 -0
  44. package/dist/winston/otel-log-transport.d.ts +20 -0
  45. package/dist/winston/otel-log-transport.js +41 -0
  46. package/dist/winston/otel-log-transport.js.map +1 -0
  47. package/package.json +125 -0
package/README.md ADDED
@@ -0,0 +1,346 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/sistinafibel/otel-kit/main/assets/banner-dark.svg">
4
+ <img alt="otel-kit — Zero-config OpenTelemetry for Node.js" src="https://raw.githubusercontent.com/sistinafibel/otel-kit/main/assets/banner-light.svg" width="640">
5
+ </picture>
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a href="https://www.npmjs.com/package/@cloudjun/otel-kit"><img alt="npm version" src="https://img.shields.io/npm/v/%40cloudjun%2Fotel-kit?logo=npm&color=cb3837"></a>
10
+ <a href="https://github.com/sistinafibel/otel-kit/actions/workflows/ci.yml"><img alt="CI" src="https://github.com/sistinafibel/otel-kit/actions/workflows/ci.yml/badge.svg"></a>
11
+ <img alt="Node.js" src="https://img.shields.io/badge/node-%3E%3D22-3c873a?logo=node.js&logoColor=white">
12
+ <a href="LICENSE"><img alt="MIT License" src="https://img.shields.io/badge/license-MIT-blue.svg"></a>
13
+ </p>
14
+
15
+ <p align="center"><b>English</b> · <a href="README.ko.md">한국어</a></p>
16
+
17
+ **otel-kit** takes the tedious part of adding OpenTelemetry to a Node.js service off your hands. One import and the standard `OTEL_*` environment variables wire up all three signals: **traces, logs and metrics**.
18
+
19
+ The pieces that are fiddly to build yourself are already here — error capture, spans for background jobs, a Winston OTLP transport, HTTP request logging and client IP resolution behind proxies — with defaults chosen so nothing private leaks by accident. NestJS wrappers are included if you need them.
20
+
21
+ Send the data anywhere that speaks OTLP/HTTP: **SigNoz**, **Grafana (Tempo / Loki / Mimir)**, the **OpenTelemetry Collector**, or your own endpoint.
22
+
23
+ <details>
24
+ <summary><b>Terms used in this README</b></summary>
25
+
26
+ <br>
27
+
28
+ | Term | What it means |
29
+ | --- | --- |
30
+ | Trace | The full path one request takes through your services |
31
+ | Span | One unit of work inside a trace, such as "DB query, 12ms" |
32
+ | Signal | A kind of data OpenTelemetry handles: traces, logs or metrics |
33
+ | Instrumentation | Code that hooks into a library and creates spans for you |
34
+ | Exporter | The part that actually ships collected data to a backend |
35
+ | Collector | A server that receives data from many services, processes it and forwards it |
36
+
37
+ </details>
38
+
39
+ ## Why otel-kit?
40
+
41
+ Wiring up the OpenTelemetry SDK by hand is a lot of work. You install a dozen packages, configure exporters, samplers and resources, keep track of a different environment variable per signal, and get the shutdown ordering right so nothing is lost on exit. otel-kit settles all of that once and reuses it in every service.
42
+
43
+ - **One call, three signals.** `initObservability()` sets up trace, log and metric providers. Only the signals that actually have an endpoint are turned on, so you can ignore the ones you don't use.
44
+ - **No config format to learn.** It honors the standard OpenTelemetry variables — `OTEL_SERVICE_NAME`, `OTEL_EXPORTER_OTLP_*`, `OTEL_TRACES_SAMPLER` and friends. There is nothing otel-kit-specific to memorize.
45
+ - **Safe defaults.** The HTTP logger records no request bodies, no query strings and no client IPs until you opt in. Secret-looking keys are masked even inside nested objects, and error objects are serialized with depth and size limits.
46
+ - **You decide what to trust.** `X-Forwarded-For` can be forged, so it is ignored until you say how many proxies sit in front of your app.
47
+ - **Shutdown stays yours.** otel-kit never installs its own `SIGTERM` handler. You call `await observability.shutdown()` wherever it belongs in your app.
48
+ - **Framework agnostic.** The core helpers work with plain `http`, Express or Fastify. On NestJS, the `/nest` entry point adds a middleware and an interceptor.
49
+
50
+ ## What it does and doesn't do
51
+
52
+ **It does**
53
+
54
+ - Initialize the OpenTelemetry SDK and flush what's pending on shutdown
55
+ - Instrument HTTP server and client requests automatically
56
+ - Record errors in the same shape on both log fields and spans
57
+ - Ship Winston logs over OTLP
58
+ - Write one structured log line per request, with sensitive values masked
59
+ - Resolve the client IP based on how many proxies you trust
60
+
61
+ **It doesn't**
62
+
63
+ - Ship a backend. You still need somewhere to store and view the data
64
+ - Instrument libraries like your database or Redis. Pass the instrumentation packages you need via `extraInstrumentations`
65
+ - Emit runtime metrics such as CPU or memory. It sets up the tooling; the metrics are yours to define
66
+ - Touch `console.log` or the NestJS default logger. Only Winston logs are forwarded
67
+ - Handle termination signals for you
68
+
69
+ ## Requirements
70
+
71
+ | | |
72
+ | --- | --- |
73
+ | Node.js | 22 or newer |
74
+ | Backend | Anything that accepts OTLP/HTTP protobuf (SigNoz, OTel Collector, Grafana...) |
75
+ | Optional | `winston` 3.x for the log transport; `@nestjs/common` 10 to 12 and `rxjs` 7.x for the NestJS helpers |
76
+
77
+ ## Installation
78
+
79
+ ```bash
80
+ npm install @cloudjun/otel-kit @opentelemetry/api
81
+ ```
82
+
83
+ There is a reason `@opentelemetry/api` is installed alongside. It holds the process-wide tracer, meter and logger registries, so exactly one copy must exist in your dependency tree. That is why otel-kit declares it as a peer dependency — a dependency the consuming app installs itself — which npm 7 and newer add automatically with the command above.
84
+
85
+ If you combine otel-kit with other instrumentation packages, run `npm ls @opentelemetry/api` to confirm it isn't duplicated. Two copies means spans land in two different registries, and traces break apart.
86
+
87
+ ## Quick start
88
+
89
+ ### 1. Point it at your backend
90
+
91
+ ```dotenv
92
+ OTEL_SERVICE_NAME=my-api
93
+ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
94
+ OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production,service.version=1.2.3
95
+ ```
96
+
97
+ ### 2. Load it before anything else
98
+
99
+ OpenTelemetry has to be initialised **before** the modules it instruments (`http`, frameworks, DB drivers) are loaded, because a module that is already loaded can no longer be hooked.
100
+
101
+ The simplest way is the preload entry point:
102
+
103
+ ```bash
104
+ node --require @cloudjun/otel-kit/register dist/main.js
105
+ # or
106
+ NODE_OPTIONS="--require=@cloudjun/otel-kit/register" node dist/main.js
107
+ ```
108
+
109
+ Prefer to pass options in code? Put the setup in its own file and make it the **first import** of your entry point:
110
+
111
+ ```ts
112
+ // instrumentation.ts
113
+ import { initObservability } from '@cloudjun/otel-kit';
114
+
115
+ export const observability = initObservability({
116
+ defaultServiceName: 'my-api',
117
+ resourceAttributes: { 'service.version': process.env.APP_VERSION ?? 'unknown' },
118
+ });
119
+ ```
120
+
121
+ ```ts
122
+ // main.ts
123
+ import { observability } from './instrumentation'; // must stay first
124
+ import { NestFactory } from '@nestjs/core';
125
+ ```
126
+
127
+ `initObservability()` runs once per process. With no OTLP endpoint configured, or with `OTEL_SDK_DISABLED=true`, it returns a handle that does nothing at all — so local development works without a collector and without code changes.
128
+
129
+ ### 3. Flush on shutdown
130
+
131
+ ```ts
132
+ process.on('SIGTERM', async () => {
133
+ await server.close();
134
+ await observability.shutdown(); // sends any spans, logs and metrics still pending
135
+ process.exit(0);
136
+ });
137
+ ```
138
+
139
+ That is it. HTTP server and client requests are now traced. Logs, metrics and the error helpers are covered below — or jump straight to the [runnable example](examples/basic), which includes a local collector.
140
+
141
+ ## Configuration
142
+
143
+ Everything is driven by standard OpenTelemetry environment variables.
144
+
145
+ | Variable | Purpose | Default |
146
+ | --- | --- | --- |
147
+ | `OTEL_SERVICE_NAME` | Service name attached to every signal | the `defaultServiceName` option, otherwise `unknown_service` |
148
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | Base URL; `/v1/traces`, `/v1/logs` and `/v1/metrics` are appended for you | none (the SDK stays off) |
149
+ | `OTEL_EXPORTER_OTLP_{TRACES,LOGS,METRICS}_ENDPOINT` | Per-signal URL, path included | falls back to the base URL |
150
+ | `OTEL_EXPORTER_OTLP_HEADERS` | Auth and other headers, e.g. `signoz-ingestion-key=...` | none |
151
+ | `OTEL_EXPORTER_OTLP_PROTOCOL` | Only `http/protobuf` is supported; anything else fails at startup | `http/protobuf` |
152
+ | `OTEL_{TRACES,LOGS,METRICS}_EXPORTER` | Set to `none` to turn that signal off | `otlp` |
153
+ | `OTEL_RESOURCE_ATTRIBUTES` | Extra resource attributes, comma separated | none |
154
+ | `OTEL_TRACES_SAMPLER` / `OTEL_TRACES_SAMPLER_ARG` | Sampling strategy and its argument, e.g. `parentbased_traceidratio` + `0.2` | `parentbased_always_on` |
155
+ | `OTEL_METRIC_EXPORT_INTERVAL` / `OTEL_METRIC_EXPORT_TIMEOUT` | How often metrics are exported and the time limit per export, in milliseconds. An explicit timeout must not exceed the interval; the default one is capped at the interval automatically | `60000` / `30000` |
156
+ | `OTEL_SDK_DISABLED` | `true` turns everything into a no-op | `false` |
157
+ | `OTEL_LOG_LEVEL` | The SDK's own diagnostic log level (`error`, `warn`, `info`, `debug`, ...) | `error` |
158
+
159
+ ### SigNoz
160
+
161
+ Self-hosted:
162
+
163
+ ```dotenv
164
+ OTEL_EXPORTER_OTLP_ENDPOINT=http://signoz-otel-collector:4318
165
+ ```
166
+
167
+ SigNoz Cloud:
168
+
169
+ ```dotenv
170
+ OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.<region>.signoz.cloud:443
171
+ OTEL_EXPORTER_OTLP_HEADERS=signoz-ingestion-key=<ingestion-key>
172
+ ```
173
+
174
+ ### Sampling
175
+
176
+ By default every request is recorded. Under heavy traffic you can keep a fraction instead:
177
+
178
+ ```dotenv
179
+ OTEL_TRACES_SAMPLER=parentbased_traceidratio
180
+ OTEL_TRACES_SAMPLER_ARG=0.2
181
+ ```
182
+
183
+ Keep in mind that this approach — head sampling — decides the moment a request **starts**, before the outcome is known, so failed requests are dropped at the same rate as everything else. If you can't afford to lose errors, pair the ratio sampler with tail sampling in your collector (which decides after the request finishes), or pass your own `sampler` option.
184
+
185
+ ### Programmatic options
186
+
187
+ ```ts
188
+ initObservability({
189
+ defaultServiceName?: string; // used when OTEL_SERVICE_NAME is unset
190
+ resourceAttributes?: Record<string, string | number | boolean>;
191
+ sampler?: Sampler; // takes precedence over OTEL_TRACES_SAMPLER
192
+ extraInstrumentations?: Instrumentation[]; // e.g. @opentelemetry/instrumentation-pg
193
+ enableTraces?: boolean; enableLogs?: boolean; enableMetrics?: boolean;
194
+ metricExportIntervalMs?: number; metricExportTimeoutMs?: number;
195
+ });
196
+ // -> { enabled, signals: { traces, logs, metrics }, forceFlush(), shutdown() }
197
+ ```
198
+
199
+ ## Usage
200
+
201
+ ### Errors: log fields and span status in one call
202
+
203
+ ```ts
204
+ import { captureError } from '@cloudjun/otel-kit';
205
+
206
+ try {
207
+ await paymentGateway.charge(order);
208
+ } catch (error) {
209
+ logger.error('Payment failed', captureError(error, {
210
+ errorCode: 'PAYMENT_CHARGE_FAILED', // few distinct values, good for alerts and grouping
211
+ orderId: order.id, // fine on logs and spans, keep it out of metric labels
212
+ }));
213
+ throw error;
214
+ }
215
+ ```
216
+
217
+ `captureError` does two things at once. It returns a record you can drop straight into a log (`exception.type`, `exception.message`, `exception.stacktrace`, plus whatever meta you passed), and it records the exception and an `ERROR` status on the span that is currently open. The record is bounded in depth and size, so even a circular or very large error object serializes safely. If you only need one half, use `recordErrorOnSpan` (span only) or `toErrorLogRecord` (record only).
218
+
219
+ The exception message and stack trace always land on the span as an exception event; `includeStatusDescription` only affects the span's *status description*. If an error message might contain secrets, sanitise it before throwing.
220
+
221
+ ### Background work: polling, queues, cron
222
+
223
+ Work that isn't an HTTP request isn't instrumented automatically, so wrap it in a span yourself:
224
+
225
+ ```ts
226
+ import { runWithSpan, SpanKind } from '@cloudjun/otel-kit';
227
+
228
+ await runWithSpan('orders.sync', () => syncOrders(), {
229
+ kind: SpanKind.CONSUMER,
230
+ attributes: { 'messaging.destination.name': 'orders' },
231
+ errorType: 'ORDER_SYNC_FAILED',
232
+ });
233
+ ```
234
+
235
+ The span closes on its own when the work finishes. Errors are recorded on the span and then re-thrown unchanged, so your surrounding error handling behaves exactly as before.
236
+
237
+ ### Logs: Winston OTLP transport
238
+
239
+ ```ts
240
+ import winston from 'winston';
241
+ import { createOtelLogTransport } from '@cloudjun/otel-kit';
242
+
243
+ const transports: winston.transport[] = [new winston.transports.Console()];
244
+ const otel = createOtelLogTransport('info');
245
+ if (otel) transports.push(otel); // null when the logs signal is disabled
246
+
247
+ export const logger = winston.createLogger({ transports });
248
+ ```
249
+
250
+ Anything logged while a span is open automatically carries `trace_id` and `span_id`, which lets you jump from a log line to its trace. Only Winston logs are forwarded; `console.*` and the NestJS default logger are left alone.
251
+
252
+ ### HTTP request logging
253
+
254
+ ```ts
255
+ import { createHttpLoggerMiddleware } from '@cloudjun/otel-kit';
256
+
257
+ app.use(createHttpLoggerMiddleware({
258
+ logger, // anything with log/warn/error(message, context)
259
+ logBody: false, // default: request bodies are never logged
260
+ stripQuery: true, // default: query strings are removed
261
+ logClientIp: false // default: no IPs
262
+ }));
263
+ ```
264
+
265
+ Each response produces one structured line with the method, route, status code, duration, `trace_id` and user agent.
266
+
267
+ Turn on `logBody` and request bodies are included too — but keys known to hold passwords, auth tokens or personal data are masked, nested objects included, with caps on depth, entry count and string length. Add keys specific to your project through `extraSensitiveKeys`.
268
+
269
+ The `user` field picks only `id` (or `idx`), `role` and `isAnon` off `req.user` by default. If your user object has a different shape, pass `getUser` and return a small summary. Returning the whole object puts all of it in your logs.
270
+
271
+ ### Client IP behind proxies
272
+
273
+ ```ts
274
+ import { createRealIpMiddleware } from '@cloudjun/otel-kit';
275
+
276
+ // Set this only if you know the hop count exactly (e.g. CDN + ingress = 2)
277
+ app.use(createRealIpMiddleware({ trustedProxyCount: 2 }));
278
+ ```
279
+
280
+ Clients can put whatever they like in `X-Forwarded-For`, so the header is ignored entirely until you set `trustedProxyCount`.
281
+
282
+ Once you do, otel-kit counts that many entries **from the end** of the list and treats that address as the real client. Each proxy appends its view to the right, so a forged value always stays on the left and falls out of range. The result is exposed as `req.realIp` and, optionally, as span attributes.
283
+
284
+ ### Metrics
285
+
286
+ ```ts
287
+ import { getMeter } from '@cloudjun/otel-kit';
288
+
289
+ const meter = getMeter('orders');
290
+ const failures = meter.createCounter('orders.sync.failures');
291
+ failures.add(1, { 'error.type': 'RATE_LIMITED' });
292
+ ```
293
+
294
+ otel-kit sets up the `MeterProvider` and the exporter, but it doesn't invent metrics for you. Define the ones you need as above, or pass the instrumentation packages for your libraries via `extraInstrumentations`.
295
+
296
+ ### NestJS
297
+
298
+ ```ts
299
+ import { Module } from '@nestjs/common';
300
+ import { APP_INTERCEPTOR } from '@nestjs/core';
301
+ import { OTEL_ERROR_INTERCEPTOR_OPTIONS, OtelErrorInterceptor } from '@cloudjun/otel-kit/nest';
302
+
303
+ @Module({
304
+ providers: [
305
+ { provide: APP_INTERCEPTOR, useClass: OtelErrorInterceptor },
306
+ { provide: OTEL_ERROR_INTERCEPTOR_OPTIONS, useValue: { recordHttp4xx: false } },
307
+ ],
308
+ })
309
+ export class AppModule {}
310
+ ```
311
+
312
+ `OtelErrorInterceptor` records unhandled exceptions on the request span. 4xx `HttpException`s are usually the client's doing, so they are skipped by default — the `recordHttp4xx: false` above just spells that default out. Flip it to `true` if you want 4xx counted as errors.
313
+
314
+ `RealIpMiddleware` and `REAL_IP_OPTIONS` wrap `createRealIpMiddleware` so it can be registered through `MiddlewareConsumer`. Flushing on shutdown fits naturally into `OnApplicationShutdown` together with `app.enableShutdownHooks()`.
315
+
316
+ ## API overview
317
+
318
+ | Entry point | Export | Purpose |
319
+ | --- | --- | --- |
320
+ | `@cloudjun/otel-kit` | `initObservability`, `getObservability`, `isOtelExportEnabled` | Bootstrap, current handle, signal status |
321
+ | | `captureError`, `recordErrorOnSpan`, `toErrorLogRecord` | Consistent error records |
322
+ | | `runWithSpan` | Spans for non-HTTP work |
323
+ | | `createOtelLogTransport` | Winston logs over OTLP |
324
+ | | `createHttpLoggerMiddleware`, `maskSensitiveData`, `DEFAULT_SENSITIVE_KEYS` | Request logging and redaction |
325
+ | | `getClientIp`, `extractIPv4`, `createRealIpMiddleware` | Trusted-proxy IP resolution |
326
+ | | `getMeter`, `getActiveTraceId`, `getActiveSpanId` | Metrics and current trace context |
327
+ | | `SpanKind`, `SpanStatusCode` and types | Re-exported from `@opentelemetry/api` |
328
+ | `@cloudjun/otel-kit/nest` | `OtelErrorInterceptor`, `OTEL_ERROR_INTERCEPTOR_OPTIONS`, `RealIpMiddleware`, `REAL_IP_OPTIONS` | NestJS wrappers |
329
+ | `@cloudjun/otel-kit/register` | `observability` | Preload entry point for `--require` |
330
+
331
+ ## Examples
332
+
333
+ - [examples/basic](examples/basic): a plain `http` server, Winston, and an OpenTelemetry Collector started with Docker Compose. Three commands and you can watch spans, logs and metrics arrive.
334
+
335
+ ## Contributing
336
+
337
+ Bug reports, feature ideas and pull requests are all welcome. [CONTRIBUTING.md](CONTRIBUTING.md) covers the development setup and workflow, and [SECURITY.md](SECURITY.md) explains how to report a vulnerability privately.
338
+
339
+ ```bash
340
+ npm ci
341
+ npm run typecheck && npm run build && npm run test:ci
342
+ ```
343
+
344
+ ## License
345
+
346
+ [MIT](LICENSE) © sistinafibel
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Error 를 OpenTelemetry 시맨틱 컨벤션 필드로 평탄화한다.
3
+ *
4
+ * 결과 객체를 winston 메타 또는 NestJS Logger 의 두 번째 인자로 그대로 넘기면
5
+ * 백엔드(SigNoz·Grafana 등)가 예외 필드를 표준 이름으로 인식한다.
6
+ *
7
+ * 필드 규약:
8
+ * - `exception.type` Error 클래스명 (예: `TypeError`, `PrismaClientKnownRequestError`)
9
+ * - `exception.message` 에러 메시지
10
+ * - `exception.stacktrace` 스택 트레이스 (있을 때만)
11
+ * - `exception.cause` `error.cause` 가 있으면 그 요약 (있을 때만)
12
+ * - `error.type` 저카디널리티 분류 키. `meta.errorCode` 가 있으면 그 값, 없으면 Error 클래스명.
13
+ * 알림 규칙·대시보드 group by 의 1차 키로 쓴다
14
+ * - 나머지 `meta` 필드는 그대로 통과한다 (`channelId`, `correlationId` 등)
15
+ */
16
+ /** 평탄화 시 함께 넘길 메타. `errorCode` 는 `error.type` 으로 옮겨진다 */
17
+ export interface IErrorLogMeta {
18
+ /** 프로젝트 정의 에러 코드 (SCREAMING_SNAKE 권장, 예: `MQ_CONNECTION_FAILED`) */
19
+ errorCode?: string;
20
+ [key: string]: unknown;
21
+ }
22
+ /** 평탄화 결과. OTel 시맨틱 컨벤션 예외 필드 + 통과된 메타 */
23
+ export interface IErrorLogRecord {
24
+ 'exception.type': string;
25
+ 'exception.message': string;
26
+ 'exception.stacktrace'?: string;
27
+ 'exception.cause'?: string;
28
+ 'error.type': string;
29
+ [key: string]: unknown;
30
+ }
31
+ /**
32
+ * Error(또는 임의의 throw 된 값)를 로그 속성 객체로 변환한다.
33
+ *
34
+ * @param error catch 한 값. Error 인스턴스가 아니어도 된다
35
+ * @param meta 함께 기록할 컨텍스트. `errorCode` 는 `error.type` 으로 매핑된다
36
+ * @returns 시맨틱 컨벤션 필드가 채워진 평면 객체 (새 객체, 입력은 변경하지 않음)
37
+ *
38
+ * @example
39
+ * logger.error('RabbitMQ 연결 실패', toErrorLogRecord(err, { errorCode: 'MQ_CONNECTION_FAILED', attempt }));
40
+ */
41
+ export declare function toErrorLogRecord(error: unknown, meta?: IErrorLogMeta): IErrorLogRecord;
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ /**
3
+ * Error 를 OpenTelemetry 시맨틱 컨벤션 필드로 평탄화한다.
4
+ *
5
+ * 결과 객체를 winston 메타 또는 NestJS Logger 의 두 번째 인자로 그대로 넘기면
6
+ * 백엔드(SigNoz·Grafana 등)가 예외 필드를 표준 이름으로 인식한다.
7
+ *
8
+ * 필드 규약:
9
+ * - `exception.type` Error 클래스명 (예: `TypeError`, `PrismaClientKnownRequestError`)
10
+ * - `exception.message` 에러 메시지
11
+ * - `exception.stacktrace` 스택 트레이스 (있을 때만)
12
+ * - `exception.cause` `error.cause` 가 있으면 그 요약 (있을 때만)
13
+ * - `error.type` 저카디널리티 분류 키. `meta.errorCode` 가 있으면 그 값, 없으면 Error 클래스명.
14
+ * 알림 규칙·대시보드 group by 의 1차 키로 쓴다
15
+ * - 나머지 `meta` 필드는 그대로 통과한다 (`channelId`, `correlationId` 등)
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.toErrorLogRecord = toErrorLogRecord;
19
+ /** Error 가 아닌 값의 분류 키 */
20
+ const NON_ERROR_TYPE = 'NonError';
21
+ const MAX_EXCEPTION_MESSAGE_LENGTH = 8_192;
22
+ const MAX_EXCEPTION_STACK_LENGTH = 32_768;
23
+ const MAX_SERIALIZED_NODES = 100;
24
+ function truncate(value, maxLength) {
25
+ return value.length > maxLength ? `${value.slice(0, maxLength)}[Truncated]` : value;
26
+ }
27
+ function safeToString(value) {
28
+ try {
29
+ return String(value);
30
+ }
31
+ catch {
32
+ return '[Unserializable]';
33
+ }
34
+ }
35
+ /** 순환 참조·BigInt·getter 예외가 있어도 예외를 던지지 않는 제한된 문자열화 */
36
+ function safeStringify(value) {
37
+ if (typeof value === 'string') {
38
+ return truncate(value, MAX_EXCEPTION_MESSAGE_LENGTH);
39
+ }
40
+ const seen = new WeakSet();
41
+ let nodes = 0;
42
+ try {
43
+ const serialized = JSON.stringify(value, (_key, inner) => {
44
+ if (typeof inner === 'bigint') {
45
+ return inner.toString();
46
+ }
47
+ if (typeof inner === 'object' && inner !== null) {
48
+ if (seen.has(inner)) {
49
+ return '[Circular]';
50
+ }
51
+ seen.add(inner);
52
+ nodes += 1;
53
+ if (nodes > MAX_SERIALIZED_NODES) {
54
+ return '[Truncated]';
55
+ }
56
+ }
57
+ return inner;
58
+ });
59
+ return truncate(serialized ?? safeToString(value), MAX_EXCEPTION_MESSAGE_LENGTH);
60
+ }
61
+ catch {
62
+ return truncate(safeToString(value), MAX_EXCEPTION_MESSAGE_LENGTH);
63
+ }
64
+ }
65
+ /** `error.cause` 를 한 줄 요약으로 만든다 (중첩 cause 는 첫 단계만) */
66
+ function describeCause(cause) {
67
+ if (cause instanceof Error) {
68
+ return truncate(`${safeToString(cause.name)}: ${safeToString(cause.message)}`, MAX_EXCEPTION_MESSAGE_LENGTH);
69
+ }
70
+ return safeStringify(cause);
71
+ }
72
+ /**
73
+ * Error(또는 임의의 throw 된 값)를 로그 속성 객체로 변환한다.
74
+ *
75
+ * @param error catch 한 값. Error 인스턴스가 아니어도 된다
76
+ * @param meta 함께 기록할 컨텍스트. `errorCode` 는 `error.type` 으로 매핑된다
77
+ * @returns 시맨틱 컨벤션 필드가 채워진 평면 객체 (새 객체, 입력은 변경하지 않음)
78
+ *
79
+ * @example
80
+ * logger.error('RabbitMQ 연결 실패', toErrorLogRecord(err, { errorCode: 'MQ_CONNECTION_FAILED', attempt }));
81
+ */
82
+ function toErrorLogRecord(error, meta = {}) {
83
+ const { errorCode, ...rest } = meta;
84
+ const normalizedErrorCode = typeof errorCode === 'string' && errorCode.trim() ? errorCode.trim() : undefined;
85
+ if (error instanceof Error) {
86
+ const cause = error.cause;
87
+ // name 이 문자열이 아니거나 비어 있어도 항상 유효한 분류 키가 되도록 정규화한다
88
+ const exceptionType = safeToString(error.name) || 'Error';
89
+ return {
90
+ ...rest,
91
+ 'exception.type': exceptionType,
92
+ 'exception.message': truncate(safeToString(error.message), MAX_EXCEPTION_MESSAGE_LENGTH),
93
+ ...(error.stack
94
+ ? { 'exception.stacktrace': truncate(safeToString(error.stack), MAX_EXCEPTION_STACK_LENGTH) }
95
+ : {}),
96
+ ...(cause !== undefined ? { 'exception.cause': describeCause(cause) } : {}),
97
+ 'error.type': normalizedErrorCode ?? exceptionType,
98
+ };
99
+ }
100
+ return {
101
+ ...rest,
102
+ 'exception.type': NON_ERROR_TYPE,
103
+ 'exception.message': safeStringify(error),
104
+ 'error.type': normalizedErrorCode ?? NON_ERROR_TYPE,
105
+ };
106
+ }
107
+ //# sourceMappingURL=error-record.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-record.js","sourceRoot":"","sources":["../src/error-record.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Error 를 OpenTelemetry 시맨틱 컨벤션 필드로 평탄화한다.\n *\n * 결과 객체를 winston 메타 또는 NestJS Logger 의 두 번째 인자로 그대로 넘기면\n * 백엔드(SigNoz·Grafana 등)가 예외 필드를 표준 이름으로 인식한다.\n *\n * 필드 규약:\n * - `exception.type` Error 클래스명 (예: `TypeError`, `PrismaClientKnownRequestError`)\n * - `exception.message` 에러 메시지\n * - `exception.stacktrace` 스택 트레이스 (있을 때만)\n * - `exception.cause` `error.cause` 가 있으면 그 요약 (있을 때만)\n * - `error.type` 저카디널리티 분류 키. `meta.errorCode` 가 있으면 그 값, 없으면 Error 클래스명.\n * 알림 규칙·대시보드 group by 의 1차 키로 쓴다\n * - 나머지 `meta` 필드는 그대로 통과한다 (`channelId`, `correlationId` 등)\n */\n\n/** 평탄화 시 함께 넘길 메타. `errorCode` 는 `error.type` 으로 옮겨진다 */\nexport interface IErrorLogMeta {\n /** 프로젝트 정의 에러 코드 (SCREAMING_SNAKE 권장, 예: `MQ_CONNECTION_FAILED`) */\n errorCode?: string;\n [key: string]: unknown;\n}\n\n/** 평탄화 결과. OTel 시맨틱 컨벤션 예외 필드 + 통과된 메타 */\nexport interface IErrorLogRecord {\n 'exception.type': string;\n 'exception.message': string;\n 'exception.stacktrace'?: string;\n 'exception.cause'?: string;\n 'error.type': string;\n [key: string]: unknown;\n}\n\n/** Error 가 아닌 값의 분류 키 */\nconst NON_ERROR_TYPE = 'NonError';\n\nconst MAX_EXCEPTION_MESSAGE_LENGTH = 8_192;\nconst MAX_EXCEPTION_STACK_LENGTH = 32_768;\nconst MAX_SERIALIZED_NODES = 100;\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length > maxLength ? `${value.slice(0, maxLength)}[Truncated]` : value;\n}\n\nfunction safeToString(value: unknown): string {\n try {\n return String(value);\n } catch {\n return '[Unserializable]';\n }\n}\n\n/** 순환 참조·BigInt·getter 예외가 있어도 예외를 던지지 않는 제한된 문자열화 */\nfunction safeStringify(value: unknown): string {\n if (typeof value === 'string') {\n return truncate(value, MAX_EXCEPTION_MESSAGE_LENGTH);\n }\n const seen = new WeakSet<object>();\n let nodes = 0;\n try {\n const serialized = JSON.stringify(value, (_key, inner) => {\n if (typeof inner === 'bigint') {\n return inner.toString();\n }\n if (typeof inner === 'object' && inner !== null) {\n if (seen.has(inner)) {\n return '[Circular]';\n }\n seen.add(inner);\n nodes += 1;\n if (nodes > MAX_SERIALIZED_NODES) {\n return '[Truncated]';\n }\n }\n return inner;\n });\n return truncate(serialized ?? safeToString(value), MAX_EXCEPTION_MESSAGE_LENGTH);\n } catch {\n return truncate(safeToString(value), MAX_EXCEPTION_MESSAGE_LENGTH);\n }\n}\n\n/** `error.cause` 를 한 줄 요약으로 만든다 (중첩 cause 는 첫 단계만) */\nfunction describeCause(cause: unknown): string {\n if (cause instanceof Error) {\n return truncate(`${safeToString(cause.name)}: ${safeToString(cause.message)}`, MAX_EXCEPTION_MESSAGE_LENGTH);\n }\n return safeStringify(cause);\n}\n\n/**\n * Error(또는 임의의 throw 된 값)를 로그 속성 객체로 변환한다.\n *\n * @param error catch 한 값. Error 인스턴스가 아니어도 된다\n * @param meta 함께 기록할 컨텍스트. `errorCode` 는 `error.type` 으로 매핑된다\n * @returns 시맨틱 컨벤션 필드가 채워진 평면 객체 (새 객체, 입력은 변경하지 않음)\n *\n * @example\n * logger.error('RabbitMQ 연결 실패', toErrorLogRecord(err, { errorCode: 'MQ_CONNECTION_FAILED', attempt }));\n */\nexport function toErrorLogRecord(error: unknown, meta: IErrorLogMeta = {}): IErrorLogRecord {\n const { errorCode, ...rest } = meta;\n const normalizedErrorCode =\n typeof errorCode === 'string' && errorCode.trim() ? errorCode.trim() : undefined;\n\n if (error instanceof Error) {\n const cause = (error as Error & { cause?: unknown }).cause;\n // name 이 문자열이 아니거나 비어 있어도 항상 유효한 분류 키가 되도록 정규화한다\n const exceptionType = safeToString(error.name) || 'Error';\n return {\n ...rest,\n 'exception.type': exceptionType,\n 'exception.message': truncate(safeToString(error.message), MAX_EXCEPTION_MESSAGE_LENGTH),\n ...(error.stack\n ? { 'exception.stacktrace': truncate(safeToString(error.stack), MAX_EXCEPTION_STACK_LENGTH) }\n : {}),\n ...(cause !== undefined ? { 'exception.cause': describeCause(cause) } : {}),\n 'error.type': normalizedErrorCode ?? exceptionType,\n };\n }\n\n return {\n ...rest,\n 'exception.type': NON_ERROR_TYPE,\n 'exception.message': safeStringify(error),\n 'error.type': normalizedErrorCode ?? NON_ERROR_TYPE,\n };\n}\n"]}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * 활성 span 에 오류를 표준 방식으로 기록하는 헬퍼.
3
+ *
4
+ * `toErrorLogRecord` 가 만드는 로그 필드와 같은 규약(`exception.*`, `error.type`)을 span 에도 적용해
5
+ * 로그와 트레이스에서 같은 키로 오류를 찾을 수 있게 한다.
6
+ */
7
+ import { Attributes, Span } from '@opentelemetry/api';
8
+ import { IErrorLogMeta, IErrorLogRecord } from './error-record';
9
+ /**
10
+ * `recordErrorOnSpan` 옵션.
11
+ *
12
+ * @property errorType `error.type` 속성으로 기록할 저카디널리티 분류 코드. 없으면 Error 클래스명을 쓴다
13
+ * @property attributes 함께 기록할 추가 span 속성
14
+ * @property includeStatusDescription span **status description** 에 exception message 를 넣을지 여부 (기본 false).
15
+ * 주의: 이 옵션과 무관하게 `span.recordException` 은 항상 message 와 stack 을 exception 이벤트로 기록한다.
16
+ * 오류 메시지에 비밀값이 섞일 수 있다면 throw 하기 전에 메시지를 정제해야 한다
17
+ * @property span 기록 대상 span. 생략하면 현재 활성 span 을 쓴다
18
+ */
19
+ export interface IRecordErrorOnSpanOptions {
20
+ errorType?: string;
21
+ attributes?: Attributes;
22
+ includeStatusDescription?: boolean;
23
+ span?: Span;
24
+ }
25
+ /**
26
+ * 오류를 지정 span 또는 활성 span 에 기록한다.
27
+ *
28
+ * 기록 내용: exception 이벤트(name · message · stack), `error.type` 속성, 추가 속성, ERROR 상태.
29
+ * Error 가 아닌 값(문자열 · 객체 등)은 `toErrorLogRecord` 로 정규화한 뒤 기록한다.
30
+ *
31
+ * @param error catch 한 값. Error 인스턴스가 아니어도 된다
32
+ * @param options 분류 코드 · 추가 속성 · 대상 span
33
+ * @returns 기록할 span 이 있어 실제로 기록했으면 true, 활성 span 이 없으면 false
34
+ */
35
+ export declare function recordErrorOnSpan(error: unknown, options?: IRecordErrorOnSpanOptions): boolean;
36
+ /**
37
+ * span 기록과 구조화 로그 레코드 생성을 한 번에 수행한다.
38
+ *
39
+ * `meta.errorCode` 가 로그의 `error.type` 과 span 의 `error.type` 에 같은 값으로 들어가므로
40
+ * 알림 규칙과 대시보드에서 하나의 키로 묶인다. 활성 span 이 없어도 로그 레코드는 정상 반환한다.
41
+ *
42
+ * @param error catch 한 값
43
+ * @param meta 로그에 함께 남길 컨텍스트. `errorCode` 는 `error.type` 으로 매핑된다
44
+ * @param spanOptions span 기록 옵션 (`errorType` 은 `meta.errorCode` 에서 결정되므로 제외)
45
+ * @returns winston · Nest Logger 의 메타 인자로 그대로 넘길 수 있는 평면 객체
46
+ *
47
+ * @example
48
+ * logger.error('CHZZK 채널 조회 실패', captureError(error, { errorCode: 'CHZZK_CHANNEL_FETCH_FAILED', channelId }));
49
+ */
50
+ export declare function captureError(error: unknown, meta?: IErrorLogMeta, spanOptions?: Omit<IRecordErrorOnSpanOptions, 'errorType'>): IErrorLogRecord;
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.recordErrorOnSpan = recordErrorOnSpan;
4
+ exports.captureError = captureError;
5
+ /**
6
+ * 활성 span 에 오류를 표준 방식으로 기록하는 헬퍼.
7
+ *
8
+ * `toErrorLogRecord` 가 만드는 로그 필드와 같은 규약(`exception.*`, `error.type`)을 span 에도 적용해
9
+ * 로그와 트레이스에서 같은 키로 오류를 찾을 수 있게 한다.
10
+ */
11
+ const api_1 = require("@opentelemetry/api");
12
+ const error_record_1 = require("./error-record");
13
+ /**
14
+ * 오류를 지정 span 또는 활성 span 에 기록한다.
15
+ *
16
+ * 기록 내용: exception 이벤트(name · message · stack), `error.type` 속성, 추가 속성, ERROR 상태.
17
+ * Error 가 아닌 값(문자열 · 객체 등)은 `toErrorLogRecord` 로 정규화한 뒤 기록한다.
18
+ *
19
+ * @param error catch 한 값. Error 인스턴스가 아니어도 된다
20
+ * @param options 분류 코드 · 추가 속성 · 대상 span
21
+ * @returns 기록할 span 이 있어 실제로 기록했으면 true, 활성 span 이 없으면 false
22
+ */
23
+ function recordErrorOnSpan(error, options = {}) {
24
+ const span = options.span ?? api_1.trace.getActiveSpan();
25
+ if (!span) {
26
+ return false;
27
+ }
28
+ const record = (0, error_record_1.toErrorLogRecord)(error, { errorCode: options.errorType });
29
+ if (error instanceof Error) {
30
+ span.recordException(error);
31
+ }
32
+ else {
33
+ span.recordException({
34
+ name: record['exception.type'],
35
+ message: record['exception.message'],
36
+ stack: record['exception.stacktrace'],
37
+ });
38
+ }
39
+ span.setAttribute('error.type', record['error.type']);
40
+ if (options.attributes) {
41
+ span.setAttributes(options.attributes);
42
+ }
43
+ span.setStatus({
44
+ code: api_1.SpanStatusCode.ERROR,
45
+ ...(options.includeStatusDescription
46
+ ? { message: record['exception.message'] }
47
+ : {}),
48
+ });
49
+ return true;
50
+ }
51
+ /**
52
+ * span 기록과 구조화 로그 레코드 생성을 한 번에 수행한다.
53
+ *
54
+ * `meta.errorCode` 가 로그의 `error.type` 과 span 의 `error.type` 에 같은 값으로 들어가므로
55
+ * 알림 규칙과 대시보드에서 하나의 키로 묶인다. 활성 span 이 없어도 로그 레코드는 정상 반환한다.
56
+ *
57
+ * @param error catch 한 값
58
+ * @param meta 로그에 함께 남길 컨텍스트. `errorCode` 는 `error.type` 으로 매핑된다
59
+ * @param spanOptions span 기록 옵션 (`errorType` 은 `meta.errorCode` 에서 결정되므로 제외)
60
+ * @returns winston · Nest Logger 의 메타 인자로 그대로 넘길 수 있는 평면 객체
61
+ *
62
+ * @example
63
+ * logger.error('CHZZK 채널 조회 실패', captureError(error, { errorCode: 'CHZZK_CHANNEL_FETCH_FAILED', channelId }));
64
+ */
65
+ function captureError(error, meta = {}, spanOptions = {}) {
66
+ const record = (0, error_record_1.toErrorLogRecord)(error, meta);
67
+ recordErrorOnSpan(error, { ...spanOptions, errorType: record['error.type'] });
68
+ return record;
69
+ }
70
+ //# sourceMappingURL=error-telemetry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-telemetry.js","sourceRoot":"","sources":["../src/error-telemetry.ts"],"names":[],"mappings":";;AAoCA,8CA8BC;AAgBD,oCAQC;AA1FD;;;;;GAKG;AACH,4CAA6E;AAC7E,iDAAkF;AAmBlF;;;;;;;;;GASG;AACH,SAAgB,iBAAiB,CAC/B,KAAc,EACd,UAAqC,EAAE;IAEvC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,WAAK,CAAC,aAAa,EAAE,CAAC;IACnD,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,MAAM,GAAG,IAAA,+BAAgB,EAAC,KAAK,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;IACzE,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,IAAI,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;SAAM,CAAC;QACN,IAAI,CAAC,eAAe,CAAC;YACnB,IAAI,EAAE,MAAM,CAAC,gBAAgB,CAAC;YAC9B,OAAO,EAAE,MAAM,CAAC,mBAAmB,CAAC;YACpC,KAAK,EAAE,MAAM,CAAC,sBAAsB,CAAC;SACtC,CAAC,CAAC;IACL,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE,MAAM,CAAC,YAAY,CAAC,CAAC,CAAC;IACtD,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;QACvB,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACzC,CAAC;IACD,IAAI,CAAC,SAAS,CAAC;QACb,IAAI,EAAE,oBAAc,CAAC,KAAK;QAC1B,GAAG,CAAC,OAAO,CAAC,wBAAwB;YAClC,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,mBAAmB,CAAC,EAAE;YAC1C,CAAC,CAAC,EAAE,CAAC;KACR,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,SAAgB,YAAY,CAC1B,KAAc,EACd,OAAsB,EAAE,EACxB,cAA4D,EAAE;IAE9D,MAAM,MAAM,GAAG,IAAA,+BAAgB,EAAC,KAAK,EAAE,IAAI,CAAC,CAAC;IAC7C,iBAAiB,CAAC,KAAK,EAAE,EAAE,GAAG,WAAW,EAAE,SAAS,EAAE,MAAM,CAAC,YAAY,CAAC,EAAE,CAAC,CAAC;IAC9E,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * 활성 span 에 오류를 표준 방식으로 기록하는 헬퍼.\n *\n * `toErrorLogRecord` 가 만드는 로그 필드와 같은 규약(`exception.*`, `error.type`)을 span 에도 적용해\n * 로그와 트레이스에서 같은 키로 오류를 찾을 수 있게 한다.\n */\nimport { Attributes, Span, SpanStatusCode, trace } from '@opentelemetry/api';\nimport { IErrorLogMeta, IErrorLogRecord, toErrorLogRecord } from './error-record';\n\n/**\n * `recordErrorOnSpan` 옵션.\n *\n * @property errorType `error.type` 속성으로 기록할 저카디널리티 분류 코드. 없으면 Error 클래스명을 쓴다\n * @property attributes 함께 기록할 추가 span 속성\n * @property includeStatusDescription span **status description** 에 exception message 를 넣을지 여부 (기본 false).\n * 주의: 이 옵션과 무관하게 `span.recordException` 은 항상 message 와 stack 을 exception 이벤트로 기록한다.\n * 오류 메시지에 비밀값이 섞일 수 있다면 throw 하기 전에 메시지를 정제해야 한다\n * @property span 기록 대상 span. 생략하면 현재 활성 span 을 쓴다\n */\nexport interface IRecordErrorOnSpanOptions {\n errorType?: string;\n attributes?: Attributes;\n includeStatusDescription?: boolean;\n span?: Span;\n}\n\n/**\n * 오류를 지정 span 또는 활성 span 에 기록한다.\n *\n * 기록 내용: exception 이벤트(name · message · stack), `error.type` 속성, 추가 속성, ERROR 상태.\n * Error 가 아닌 값(문자열 · 객체 등)은 `toErrorLogRecord` 로 정규화한 뒤 기록한다.\n *\n * @param error catch 한 값. Error 인스턴스가 아니어도 된다\n * @param options 분류 코드 · 추가 속성 · 대상 span\n * @returns 기록할 span 이 있어 실제로 기록했으면 true, 활성 span 이 없으면 false\n */\nexport function recordErrorOnSpan(\n error: unknown,\n options: IRecordErrorOnSpanOptions = {},\n): boolean {\n const span = options.span ?? trace.getActiveSpan();\n if (!span) {\n return false;\n }\n\n const record = toErrorLogRecord(error, { errorCode: options.errorType });\n if (error instanceof Error) {\n span.recordException(error);\n } else {\n span.recordException({\n name: record['exception.type'],\n message: record['exception.message'],\n stack: record['exception.stacktrace'],\n });\n }\n span.setAttribute('error.type', record['error.type']);\n if (options.attributes) {\n span.setAttributes(options.attributes);\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n ...(options.includeStatusDescription\n ? { message: record['exception.message'] }\n : {}),\n });\n return true;\n}\n\n/**\n * span 기록과 구조화 로그 레코드 생성을 한 번에 수행한다.\n *\n * `meta.errorCode` 가 로그의 `error.type` 과 span 의 `error.type` 에 같은 값으로 들어가므로\n * 알림 규칙과 대시보드에서 하나의 키로 묶인다. 활성 span 이 없어도 로그 레코드는 정상 반환한다.\n *\n * @param error catch 한 값\n * @param meta 로그에 함께 남길 컨텍스트. `errorCode` 는 `error.type` 으로 매핑된다\n * @param spanOptions span 기록 옵션 (`errorType` 은 `meta.errorCode` 에서 결정되므로 제외)\n * @returns winston · Nest Logger 의 메타 인자로 그대로 넘길 수 있는 평면 객체\n *\n * @example\n * logger.error('CHZZK 채널 조회 실패', captureError(error, { errorCode: 'CHZZK_CHANNEL_FETCH_FAILED', channelId }));\n */\nexport function captureError(\n error: unknown,\n meta: IErrorLogMeta = {},\n spanOptions: Omit<IRecordErrorOnSpanOptions, 'errorType'> = {},\n): IErrorLogRecord {\n const record = toErrorLogRecord(error, meta);\n recordErrorOnSpan(error, { ...spanOptions, errorType: record['error.type'] });\n return record;\n}\n"]}