@rsdk/core 5.10.1-next.0 → 5.10.1

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 (34) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/config/parsers/index.d.ts +1 -0
  3. package/dist/config/parsers/index.js +1 -0
  4. package/dist/config/parsers/index.js.map +1 -1
  5. package/dist/config/parsers/string-record/exception.d.ts +4 -0
  6. package/dist/config/parsers/string-record/exception.js +14 -0
  7. package/dist/config/parsers/string-record/exception.js.map +1 -0
  8. package/dist/config/parsers/string-record/index.d.ts +2 -0
  9. package/dist/config/parsers/string-record/index.js +21 -0
  10. package/dist/config/parsers/string-record/index.js.map +1 -0
  11. package/dist/config/parsers/string-record/string-record.parser.d.ts +8 -0
  12. package/dist/config/parsers/string-record/string-record.parser.js +42 -0
  13. package/dist/config/parsers/string-record/string-record.parser.js.map +1 -0
  14. package/dist/logging/logger-initializing.module.d.ts +22 -1
  15. package/dist/logging/logger-initializing.module.js +103 -11
  16. package/dist/logging/logger-initializing.module.js.map +1 -1
  17. package/dist/logging/logging.config.d.ts +24 -1
  18. package/dist/logging/logging.config.js +132 -3
  19. package/dist/logging/logging.config.js.map +1 -1
  20. package/dist/logging/otel-time.transform.d.ts +9 -0
  21. package/dist/logging/otel-time.transform.js +35 -0
  22. package/dist/logging/otel-time.transform.js.map +1 -0
  23. package/package.json +7 -2
  24. package/src/config/parsers/index.ts +1 -0
  25. package/src/config/parsers/string-record/exception.ts +10 -0
  26. package/src/config/parsers/string-record/index.ts +2 -0
  27. package/src/config/parsers/string-record/string-record.parser.ts +55 -0
  28. package/src/config/parsers/string-record/string-record.spec.ts +33 -0
  29. package/src/logging/logger-factory.lifecycle.spec.ts +91 -0
  30. package/src/logging/logger-initializing.module.spec.ts +263 -0
  31. package/src/logging/logger-initializing.module.ts +128 -17
  32. package/src/logging/logging.config.ts +113 -3
  33. package/src/logging/otel-time.transform.spec.ts +59 -0
  34. package/src/logging/otel-time.transform.ts +40 -0
@@ -5,6 +5,7 @@ export * from './number';
5
5
  export * from './path';
6
6
  export * from './size';
7
7
  export * from './string';
8
+ export * from './string-record';
8
9
  export * from './timespan';
9
10
  export * from './url';
10
11
  export * from './array/';
@@ -0,0 +1,10 @@
1
+ import { BootstrapException } from '../../../exceptions';
2
+
3
+ export class InvalidStringRecord extends BootstrapException {
4
+ constructor(reason: string, value: unknown, cause?: unknown) {
5
+ super(`Invalid string record: ${reason}`, {
6
+ cause,
7
+ details: { value },
8
+ });
9
+ }
10
+ }
@@ -0,0 +1,2 @@
1
+ export * from './string-record.parser';
2
+ export { InvalidStringRecord } from './exception';
@@ -0,0 +1,55 @@
1
+ import type { PropertyParser } from '../../types';
2
+
3
+ import { InvalidStringRecord } from './exception';
4
+
5
+ /** Парсит JSON в плоский объект, проверяя, что все значения — строки. */
6
+ export class StringRecordParser
7
+ implements PropertyParser<Record<string, string>>
8
+ {
9
+ type(): string {
10
+ return 'json(Record<string, string>)';
11
+ }
12
+
13
+ description(): string {
14
+ return 'Parses a JSON object whose values are all strings';
15
+ }
16
+
17
+ parse(value: unknown): Record<string, string> {
18
+ const parsed = this.toJson(value);
19
+
20
+ if (
21
+ parsed === null ||
22
+ typeof parsed !== 'object' ||
23
+ Array.isArray(parsed)
24
+ ) {
25
+ throw new InvalidStringRecord('expected a JSON object', value);
26
+ }
27
+
28
+ const result: Record<string, string> = {};
29
+
30
+ for (const [key, item] of Object.entries(parsed)) {
31
+ if (typeof item !== 'string') {
32
+ throw new InvalidStringRecord(
33
+ `value of key <${key}> must be a string, got ${typeof item}`,
34
+ value,
35
+ );
36
+ }
37
+
38
+ result[key] = item;
39
+ }
40
+
41
+ return result;
42
+ }
43
+
44
+ private toJson(value: unknown): unknown {
45
+ if (typeof value !== 'string') {
46
+ return value;
47
+ }
48
+
49
+ try {
50
+ return JSON.parse(value);
51
+ } catch (error) {
52
+ throw new InvalidStringRecord('value is not valid JSON', value, error);
53
+ }
54
+ }
55
+ }
@@ -0,0 +1,33 @@
1
+ import { StringRecordParser } from './string-record.parser';
2
+
3
+ describe('StringRecordParser', () => {
4
+ const parser = new StringRecordParser();
5
+
6
+ it('parses a JSON object of string values', () => {
7
+ expect(parser.parse('{"a":"1","b":"two"}')).toEqual({ a: '1', b: 'two' });
8
+ });
9
+
10
+ it('parses an empty object', () => {
11
+ expect(parser.parse('{}')).toEqual({});
12
+ });
13
+
14
+ it('accepts an already-parsed object (e.g. default value)', () => {
15
+ expect(parser.parse({ a: 'b' })).toEqual({ a: 'b' });
16
+ });
17
+
18
+ it('rejects invalid JSON', () => {
19
+ expect(() => parser.parse('not json')).toThrow();
20
+ });
21
+
22
+ it('rejects non-object JSON (array, primitive, null)', () => {
23
+ expect(() => parser.parse('["a","b"]')).toThrow();
24
+ expect(() => parser.parse('"a string"')).toThrow();
25
+ expect(() => parser.parse('42')).toThrow();
26
+ expect(() => parser.parse('null')).toThrow();
27
+ });
28
+
29
+ it('rejects objects with non-string values', () => {
30
+ expect(() => parser.parse('{"a":1}')).toThrow();
31
+ expect(() => parser.parse('{"a":{"nested":"x"}}')).toThrow();
32
+ });
33
+ });
@@ -0,0 +1,91 @@
1
+ import { LoggerFactory, LogLevel, LogTimestampFormat } from '@rsdk/logging';
2
+ import type { TransportMultiOptions } from 'pino';
3
+ import pino from 'pino';
4
+
5
+ /**
6
+ * Регресс на баг, пойманный реальным запуском: applyInstrumentations пересоздавал
7
+ * только что созданный worker-транспорт и синхронно звал .end(), который у
8
+ * медленно закрывающихся транспортов (OTEL) висел 10с и ронял процесс. Теперь
9
+ * воркер переиспользуется, пока его конфиг не сменился.
10
+ */
11
+ interface FakeStream {
12
+ write: jest.Mock;
13
+ on: jest.Mock;
14
+ end: jest.Mock;
15
+ flush: jest.Mock;
16
+ flushSync: jest.Mock;
17
+ unref: jest.Mock;
18
+ writable: boolean;
19
+ }
20
+
21
+ function fakeStream(): FakeStream {
22
+ return {
23
+ write: jest.fn(),
24
+ on: jest.fn(),
25
+ end: jest.fn(),
26
+ flush: jest.fn((cb?: () => void) => cb?.()),
27
+ flushSync: jest.fn(),
28
+ unref: jest.fn(),
29
+ writable: true,
30
+ };
31
+ }
32
+
33
+ const base = {
34
+ level: LogLevel.info,
35
+ redact: [] as string[],
36
+ timestampFormat: LogTimestampFormat.isoTime,
37
+ };
38
+
39
+ function transport(dest: number): TransportMultiOptions {
40
+ return {
41
+ targets: [
42
+ { target: 'pino/file', options: { destination: dest }, level: 'info' },
43
+ ],
44
+ };
45
+ }
46
+
47
+ describe('LoggerFactory — жизненный цикл worker-транспорта', () => {
48
+ let transportSpy: jest.SpyInstance;
49
+
50
+ beforeEach(() => {
51
+ transportSpy = jest
52
+ .spyOn(pino, 'transport')
53
+ .mockImplementation(() => fakeStream() as any);
54
+ });
55
+
56
+ afterEach(() => {
57
+ jest.restoreAllMocks();
58
+ });
59
+
60
+ it('переиспользует воркер на applyInstrumentations (не пересоздаёт)', () => {
61
+ const t = transport(1);
62
+
63
+ LoggerFactory.reconfigure({ ...base, transport: t });
64
+ expect(transportSpy).toHaveBeenCalledTimes(1);
65
+
66
+ LoggerFactory.applyInstrumentations(() => {});
67
+ LoggerFactory.applyInstrumentations(() => {});
68
+
69
+ // воркер тот же — pino.transport больше не вызывался
70
+ expect(transportSpy).toHaveBeenCalledTimes(1);
71
+ });
72
+
73
+ it('пересоздаёт воркер при смене конфига транспорта', () => {
74
+ LoggerFactory.reconfigure({ ...base, transport: transport(1) });
75
+ LoggerFactory.reconfigure({ ...base, transport: transport(1) }); // новый объект
76
+
77
+ expect(transportSpy).toHaveBeenCalledTimes(2);
78
+ });
79
+
80
+ it('закрывает воркер при переключении на stream', () => {
81
+ LoggerFactory.reconfigure({ ...base, transport: transport(1) });
82
+ const created = transportSpy.mock.results[0].value;
83
+
84
+ LoggerFactory.reconfigure({
85
+ ...base,
86
+ stream: { write() {}, writable: true } as any,
87
+ });
88
+
89
+ expect(created.end).toHaveBeenCalled();
90
+ });
91
+ });
@@ -0,0 +1,263 @@
1
+ import { Timespan } from '@rsdk/common';
2
+ import { LoggerFactory, LogLevel, LogTimestampFormat } from '@rsdk/logging';
3
+ import type { TransportTargetOptions } from 'pino';
4
+ import pino from 'pino';
5
+
6
+ import { LoggerInitializingModule } from './logger-initializing.module';
7
+ import type { LoggingConfig } from './logging.config';
8
+ import { LogOtelProtocol } from './logging.config';
9
+
10
+ function makeConfig(overrides: Partial<LoggingConfig> = {}): LoggingConfig {
11
+ return {
12
+ level: LogLevel.info,
13
+ redact: [],
14
+ sync: false,
15
+ shutdownTimeout: new Timespan(1, 's'),
16
+ forceTransport: false,
17
+ httpEndpoint: undefined,
18
+ httpHeaders: {},
19
+ httpTimeout: new Timespan(2500, 'ms'),
20
+ httpBatchSize: 100,
21
+ httpBatchInterval: new Timespan(5, 's'),
22
+ httpMaxRetries: 2,
23
+ httpRetryDelay: new Timespan(1, 's'),
24
+ httpMaxBufferSize: 100000,
25
+ httpSilent: false,
26
+ otelEnabled: false,
27
+ otelEndpoint: undefined,
28
+ otelProtocol: undefined,
29
+ otelServiceName: undefined,
30
+ logTimestampFormat: LogTimestampFormat.isoTime,
31
+ onUpdate: jest.fn(),
32
+ ...overrides,
33
+ } as unknown as LoggingConfig;
34
+ }
35
+
36
+ type Delivery = Record<string, any>;
37
+
38
+ /** Конструирует модуль и возвращает то, что ушло в LoggerFactory.reconfigure. */
39
+ function capture(config: LoggingConfig): Delivery {
40
+ const spy = jest
41
+ .spyOn(LoggerFactory, 'reconfigure')
42
+ .mockImplementation(() => {});
43
+
44
+ // eslint-disable-next-line no-new
45
+ new LoggerInitializingModule(config);
46
+
47
+ return spy.mock.calls[0][0] as Delivery;
48
+ }
49
+
50
+ function targetOf(delivery: Delivery, name: string): Delivery | undefined {
51
+ return delivery.transport?.targets?.find((t: Delivery) => t.target === name);
52
+ }
53
+
54
+ /** OTEL-таргет — это pipeline [time-transform → pino-opentelemetry-transport]. */
55
+ function otelPipeline(delivery: Delivery): Delivery | undefined {
56
+ return delivery.transport?.targets?.find((t: Delivery) =>
57
+ t.pipeline?.some(
58
+ (s: Delivery) => s.target === 'pino-opentelemetry-transport',
59
+ ),
60
+ );
61
+ }
62
+
63
+ /** Стейдж OTEL-экспортёра внутри pipeline. */
64
+ function otelStage(delivery: Delivery): Delivery | undefined {
65
+ return otelPipeline(delivery)?.pipeline?.find(
66
+ (s: Delivery) => s.target === 'pino-opentelemetry-transport',
67
+ );
68
+ }
69
+
70
+ describe('LoggerInitializingModule — выбор доставки', () => {
71
+ beforeEach(() => {
72
+ (LoggerInitializingModule as any).logger = { info: jest.fn() };
73
+
74
+ // не создаём реальные SonicBoom — мокаем destination маркером с opts
75
+ jest
76
+ .spyOn(pino, 'destination')
77
+ .mockImplementation((opts: any) => ({ __stream: true, opts }) as any);
78
+ });
79
+
80
+ afterEach(() => {
81
+ jest.restoreAllMocks();
82
+ });
83
+
84
+ describe('stream-режим (только stdout)', () => {
85
+ it('без OTEL/HTTP/force → in-process stream, без transport', () => {
86
+ const d = capture(makeConfig());
87
+
88
+ expect(d.transport).toBeUndefined();
89
+ expect(d.stream).toBeDefined();
90
+ expect(d.stream.opts.dest).toBe(process.stdout.fd);
91
+ });
92
+
93
+ it('LOG_SYNC=false → async stream', () => {
94
+ const d = capture(makeConfig({ sync: false }));
95
+
96
+ expect(d.stream.opts.sync).toBe(false);
97
+ });
98
+
99
+ it('LOG_SYNC=true → sync stream', () => {
100
+ const d = capture(makeConfig({ sync: true }));
101
+
102
+ expect(d.stream.opts.sync).toBe(true);
103
+ });
104
+ });
105
+
106
+ describe('переход на worker-transport', () => {
107
+ it('forceTransport=true → transport c единственным stdout-таргетом', () => {
108
+ const d = capture(makeConfig({ forceTransport: true }));
109
+
110
+ expect(d.stream).toBeUndefined();
111
+ expect(d.transport.targets).toHaveLength(1);
112
+
113
+ const file = targetOf(d, 'pino/file');
114
+
115
+ expect(file?.options).toEqual({ destination: process.stdout.fd });
116
+ expect(file?.level).toBe(LogLevel.info);
117
+ });
118
+
119
+ it('otelEnabled=true → transport (stdout + otel-pipeline)', () => {
120
+ const d = capture(makeConfig({ otelEnabled: true }));
121
+
122
+ expect(d.stream).toBeUndefined();
123
+ expect(targetOf(d, 'pino/file')).toBeDefined();
124
+ expect(otelStage(d)).toBeDefined();
125
+ });
126
+
127
+ it('OTEL обёрнут в pipeline [time-transform → otel]', () => {
128
+ const d = capture(makeConfig({ otelEnabled: true }));
129
+ const pipeline = otelPipeline(d)!.pipeline as Delivery[];
130
+
131
+ expect(pipeline).toHaveLength(2);
132
+ expect(pipeline[0].target).toMatch(/otel-time\.transform\.js$/);
133
+ expect(pipeline[1].target).toBe('pino-opentelemetry-transport');
134
+ });
135
+
136
+ it('httpEndpoint задан → transport (stdout + http)', () => {
137
+ const d = capture(
138
+ makeConfig({ httpEndpoint: new URL('https://logs.example.com/in') }),
139
+ );
140
+
141
+ expect(d.stream).toBeUndefined();
142
+ expect(targetOf(d, 'pino-http-transport')).toBeDefined();
143
+ });
144
+
145
+ it('otel + http → три таргета', () => {
146
+ const d = capture(
147
+ makeConfig({
148
+ otelEnabled: true,
149
+ httpEndpoint: new URL('https://logs.example.com/in'),
150
+ }),
151
+ );
152
+
153
+ expect(d.transport.targets).toHaveLength(3);
154
+ expect(targetOf(d, 'pino/file')).toBeDefined();
155
+ expect(otelStage(d)).toBeDefined();
156
+ expect(targetOf(d, 'pino-http-transport')).toBeDefined();
157
+ });
158
+ });
159
+
160
+ describe('OTEL target', () => {
161
+ it('минимальный: без endpoint/protocol/serviceName', () => {
162
+ const d = capture(makeConfig({ otelEnabled: true }));
163
+ const opts = otelStage(d)!.options as any;
164
+
165
+ expect(opts.logRecordProcessorOptions.recordProcessorType).toBe('batch');
166
+ expect(opts.logRecordProcessorOptions.exporterOptions).toEqual({});
167
+ expect(opts.loggerName).toBeUndefined();
168
+ expect(opts.resourceAttributes).toBeUndefined();
169
+ });
170
+
171
+ it('полный: endpoint раскладывается по трём ключам, protocol и service.name выставлены', () => {
172
+ const d = capture(
173
+ makeConfig({
174
+ otelEnabled: true,
175
+ otelEndpoint: new URL('http://collector:4318'),
176
+ otelProtocol: LogOtelProtocol.grpc,
177
+ otelServiceName: 'my-svc',
178
+ }),
179
+ );
180
+ const opts = otelStage(d)!.options as any;
181
+ const exporter = opts.logRecordProcessorOptions.exporterOptions;
182
+ const url = 'http://collector:4318/';
183
+
184
+ expect(exporter.protocol).toBe('grpc');
185
+ expect(exporter.httpExporterOptions).toEqual({ url });
186
+ expect(exporter.protobufExporterOptions).toEqual({ url });
187
+ expect(exporter.grpcExporterOptions).toEqual({ url });
188
+ expect(opts.loggerName).toBe('my-svc');
189
+ expect(opts.resourceAttributes).toEqual({ 'service.name': 'my-svc' });
190
+ });
191
+
192
+ it('endpoint без явного protocol → protocol не задаётся (env-fallback)', () => {
193
+ const d = capture(
194
+ makeConfig({
195
+ otelEnabled: true,
196
+ otelEndpoint: new URL('http://collector:4318'),
197
+ }),
198
+ );
199
+ const exporter = (otelStage(d)!.options as any).logRecordProcessorOptions
200
+ .exporterOptions;
201
+
202
+ expect(exporter.protocol).toBeUndefined();
203
+ expect(exporter.protobufExporterOptions).toEqual({
204
+ url: 'http://collector:4318/',
205
+ });
206
+ });
207
+ });
208
+
209
+ describe('HTTP target', () => {
210
+ it('url/headers проброшены, длительности конвертированы в мс', () => {
211
+ const d = capture(
212
+ makeConfig({
213
+ httpEndpoint: new URL('https://logs.example.com/ingest'),
214
+ httpHeaders: { 'x-api-key': 'secret' },
215
+ httpTimeout: new Timespan(3, 's'),
216
+ httpBatchInterval: new Timespan(10, 's'),
217
+ httpRetryDelay: new Timespan(500, 'ms'),
218
+ httpBatchSize: 50,
219
+ httpMaxRetries: 5,
220
+ httpMaxBufferSize: 42,
221
+ httpSilent: true,
222
+ }),
223
+ );
224
+ const opts = targetOf(d, 'pino-http-transport')!.options as any;
225
+
226
+ expect(opts.url).toBe('https://logs.example.com/ingest');
227
+ expect(opts.headers).toEqual({ 'x-api-key': 'secret' });
228
+ expect(opts.timeout).toBe(3000);
229
+ expect(opts.batchInterval).toBe(10000);
230
+ expect(opts.retryDelay).toBe(500);
231
+ expect(opts.batchSize).toBe(50);
232
+ expect(opts.maxRetries).toBe(5);
233
+ expect(opts.maxBufferSize).toBe(42);
234
+ expect(opts.silent).toBe(true);
235
+ });
236
+ });
237
+
238
+ describe('level', () => {
239
+ it('каждый таргет наследует config.level', () => {
240
+ const d = capture(
241
+ makeConfig({
242
+ level: LogLevel.warn,
243
+ otelEnabled: true,
244
+ httpEndpoint: new URL('https://logs.example.com/in'),
245
+ }),
246
+ );
247
+
248
+ for (const target of d.transport.targets as TransportTargetOptions[]) {
249
+ expect(target.level).toBe(LogLevel.warn);
250
+ }
251
+ });
252
+ });
253
+
254
+ describe('timestampFormat', () => {
255
+ it('logTimestampFormat маппится в timestampFormat (LOG_TIMESTAMP_FORMAT)', () => {
256
+ const d = capture(
257
+ makeConfig({ logTimestampFormat: LogTimestampFormat.epochTime }),
258
+ );
259
+
260
+ expect(d.timestampFormat).toBe(LogTimestampFormat.epochTime);
261
+ });
262
+ });
263
+ });
@@ -1,15 +1,27 @@
1
+ import type { OnApplicationShutdown } from '@nestjs/common';
1
2
  import { Module } from '@nestjs/common';
3
+ import type { LoggerOptions } from '@rsdk/logging';
2
4
  import { LoggerFactory } from '@rsdk/logging';
3
- import type { TransportMultiOptions, TransportTargetOptions } from 'pino';
4
- import pino from 'pino';
5
+ import path from 'node:path';
6
+ import pino, {
7
+ type TransportMultiOptions,
8
+ type TransportPipelineOptions,
9
+ type TransportTargetOptions,
10
+ } from 'pino';
5
11
 
6
12
  import { LoggingConfig } from './logging.config';
7
13
 
14
+ /**
15
+ * Абсолютный путь к скомпилированному pipeline-трансформу (рядом в dist).
16
+ * Воркер pino грузит таргет по пути, поэтому ссылаемся на .js, а не на модуль.
17
+ */
18
+ const OTEL_TIME_TRANSFORM = path.join(__dirname, 'otel-time.transform.js');
19
+
8
20
  @Module({})
9
- export class LoggerInitializingModule {
21
+ export class LoggerInitializingModule implements OnApplicationShutdown {
10
22
  private static logger = LoggerFactory.create(LoggerInitializingModule);
11
23
 
12
- constructor(config: LoggingConfig) {
24
+ constructor(private readonly config: LoggingConfig) {
13
25
  const cfg = (): void => {
14
26
  LoggerInitializingModule.logger.info(
15
27
  `Setting log level: <${config.level}>`,
@@ -20,7 +32,8 @@ export class LoggerInitializingModule {
20
32
 
21
33
  LoggerFactory.reconfigure({
22
34
  ...config,
23
- stream: pino.transport(this.buildTransportOptions(config)),
35
+ timestampFormat: config.logTimestampFormat,
36
+ ...this.buildDelivery(config),
24
37
  });
25
38
  };
26
39
 
@@ -28,28 +41,126 @@ export class LoggerInitializingModule {
28
41
  cfg();
29
42
  }
30
43
 
44
+ async onApplicationShutdown(): Promise<void> {
45
+ await LoggerFactory.shutdown(this.config.shutdownTimeout.millis());
46
+ }
47
+
48
+ /**
49
+ * Worker-транспорт нужен только для сетевых приёмников (OTEL/HTTP) либо по
50
+ * явному запросу. Для логирования лишь в stdout остаёмся на in-process
51
+ * stream — без воркеров, как было до multitransport.
52
+ */
53
+ private buildDelivery(config: LoggingConfig): Partial<LoggerOptions> {
54
+ const needsTransport =
55
+ config.otelEnabled ||
56
+ Boolean(config.httpEndpoint) ||
57
+ config.forceTransport;
58
+
59
+ return needsTransport
60
+ ? { transport: this.buildTransportOptions(config) }
61
+ : {
62
+ stream: pino.destination({
63
+ dest: process.stdout.fd,
64
+ sync: config.sync,
65
+ }),
66
+ };
67
+ }
68
+
31
69
  private buildTransportOptions(config: LoggingConfig): TransportMultiOptions {
32
- const targets: TransportTargetOptions[] = [
70
+ const targets: (TransportTargetOptions | TransportPipelineOptions)[] = [
33
71
  {
34
72
  target: 'pino/file',
35
- options: { destination: process.stdout.fd },
73
+ options: {
74
+ destination: process.stdout.fd,
75
+ },
36
76
  level: config.level,
37
77
  },
38
78
  ];
39
79
 
80
+ // OTEL включается флагом (endpoint опционален — резолвится из стандартных
81
+ // OTEL_* env), а HTTP — наличием endpoint (у него стандартного discovery
82
+ // нет). Отсюда разные модели enable у двух сетевых транспортов.
40
83
  if (config.otelEnabled) {
41
- targets.push({
42
- target: 'pino-opentelemetry-transport',
43
-
44
- /**
45
- * NOTE: {} required to avoid runtime error "Cannot read property 'xxx' of undefined"
46
- * (unsafe destructuring in pino-opentelemetry-transport)
47
- */
48
- options: {},
49
- level: config.level,
50
- });
84
+ targets.push(this.buildOtelTarget(config));
85
+ }
86
+
87
+ if (config.httpEndpoint) {
88
+ targets.push(this.buildHttpTarget(config.httpEndpoint, config));
51
89
  }
52
90
 
53
91
  return { targets };
54
92
  }
93
+
94
+ /**
95
+ * OTEL-таргет оборачивается в pipeline `[time-transform → otel]`: трансформ
96
+ * приводит поле `time` к числовому epoch ms, которого требует OTLP (иначе при
97
+ * дефолтном isoTime записи молча отбрасываются), не затрагивая формат времени
98
+ * остальных таргетов.
99
+ *
100
+ * `otlp-logger` (через который работает pino-opentelemetry-transport) НЕ
101
+ * читает ключи `endpoint`/`serviceName`: endpoint задаётся через
102
+ * exporterOptions.url, а имя сервиса — через resourceAttributes/loggerName.
103
+ */
104
+ private buildOtelTarget(config: LoggingConfig): TransportPipelineOptions {
105
+ const exporterOptions: Record<string, unknown> = {};
106
+
107
+ // Без явного протокола otlp-logger резолвит его из стандартного
108
+ // OTEL_EXPORTER_OTLP_PROTOCOL env (default protobuf).
109
+ if (config.otelProtocol) {
110
+ exporterOptions.protocol = config.otelProtocol;
111
+ }
112
+
113
+ if (config.otelEndpoint) {
114
+ const exporterUrl = { url: config.otelEndpoint.href };
115
+
116
+ // url кладём под все три ключа: otlp-logger прочитает только
117
+ // соответствующий выбранному протоколу, остальные проигнорирует.
118
+ exporterOptions.httpExporterOptions = exporterUrl;
119
+ exporterOptions.protobufExporterOptions = exporterUrl;
120
+ exporterOptions.grpcExporterOptions = exporterUrl;
121
+ }
122
+
123
+ const options: Record<string, unknown> = {
124
+ logRecordProcessorOptions: {
125
+ recordProcessorType: 'batch',
126
+ exporterOptions,
127
+ },
128
+ };
129
+
130
+ if (config.otelServiceName) {
131
+ options.loggerName = config.otelServiceName;
132
+ options.resourceAttributes = {
133
+ 'service.name': config.otelServiceName,
134
+ };
135
+ }
136
+
137
+ return {
138
+ level: config.level,
139
+ pipeline: [
140
+ { target: OTEL_TIME_TRANSFORM },
141
+ { target: 'pino-opentelemetry-transport', options },
142
+ ],
143
+ };
144
+ }
145
+
146
+ private buildHttpTarget(
147
+ url: URL,
148
+ config: LoggingConfig,
149
+ ): TransportTargetOptions {
150
+ return {
151
+ target: 'pino-http-transport',
152
+ options: {
153
+ url: url.href,
154
+ headers: config.httpHeaders,
155
+ timeout: config.httpTimeout.millis(),
156
+ batchSize: config.httpBatchSize,
157
+ batchInterval: config.httpBatchInterval.millis(),
158
+ maxRetries: config.httpMaxRetries,
159
+ retryDelay: config.httpRetryDelay.millis(),
160
+ maxBufferSize: config.httpMaxBufferSize,
161
+ silent: config.httpSilent,
162
+ },
163
+ level: config.level,
164
+ };
165
+ }
55
166
  }