@rsdk/core 5.12.0-next.9 → 5.13.0-next.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/CHANGELOG.md +4 -0
- package/dist/config/parsers/index.d.ts +1 -0
- package/dist/config/parsers/index.js +1 -0
- package/dist/config/parsers/index.js.map +1 -1
- package/dist/config/parsers/string-record/exception.d.ts +4 -0
- package/dist/config/parsers/string-record/exception.js +14 -0
- package/dist/config/parsers/string-record/exception.js.map +1 -0
- package/dist/config/parsers/string-record/index.d.ts +2 -0
- package/dist/config/parsers/string-record/index.js +21 -0
- package/dist/config/parsers/string-record/index.js.map +1 -0
- package/dist/config/parsers/string-record/string-record.parser.d.ts +8 -0
- package/dist/config/parsers/string-record/string-record.parser.js +42 -0
- package/dist/config/parsers/string-record/string-record.parser.js.map +1 -0
- package/dist/logging/logger-initializing.module.d.ts +17 -1
- package/dist/logging/logger-initializing.module.js +90 -11
- package/dist/logging/logger-initializing.module.js.map +1 -1
- package/dist/logging/logging.config.d.ts +22 -0
- package/dist/logging/logging.config.js +124 -3
- package/dist/logging/logging.config.js.map +1 -1
- package/package.json +6 -2
- package/src/config/parsers/index.ts +1 -0
- package/src/config/parsers/string-record/exception.ts +10 -0
- package/src/config/parsers/string-record/index.ts +2 -0
- package/src/config/parsers/string-record/string-record.parser.ts +55 -0
- package/src/config/parsers/string-record/string-record.spec.ts +33 -0
- package/src/logging/logger-factory.lifecycle.spec.ts +91 -0
- package/src/logging/logger-initializing.module.spec.ts +245 -0
- package/src/logging/logger-initializing.module.ts +112 -16
- package/src/logging/logging.config.ts +106 -2
|
@@ -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,245 @@
|
|
|
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(
|
|
51
|
+
delivery: Delivery,
|
|
52
|
+
name: string,
|
|
53
|
+
): TransportTargetOptions | undefined {
|
|
54
|
+
return delivery.transport?.targets?.find(
|
|
55
|
+
(t: TransportTargetOptions) => t.target === name,
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
describe('LoggerInitializingModule — выбор доставки', () => {
|
|
60
|
+
beforeEach(() => {
|
|
61
|
+
(LoggerInitializingModule as any).logger = { info: jest.fn() };
|
|
62
|
+
|
|
63
|
+
// не создаём реальные SonicBoom — мокаем destination маркером с opts
|
|
64
|
+
jest
|
|
65
|
+
.spyOn(pino, 'destination')
|
|
66
|
+
.mockImplementation((opts: any) => ({ __stream: true, opts }) as any);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
afterEach(() => {
|
|
70
|
+
jest.restoreAllMocks();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
describe('stream-режим (только stdout)', () => {
|
|
74
|
+
it('без OTEL/HTTP/force → in-process stream, без transport', () => {
|
|
75
|
+
const d = capture(makeConfig());
|
|
76
|
+
|
|
77
|
+
expect(d.transport).toBeUndefined();
|
|
78
|
+
expect(d.stream).toBeDefined();
|
|
79
|
+
expect(d.stream.opts.dest).toBe(process.stdout.fd);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('LOG_SYNC=false → async stream', () => {
|
|
83
|
+
const d = capture(makeConfig({ sync: false }));
|
|
84
|
+
|
|
85
|
+
expect(d.stream.opts.sync).toBe(false);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('LOG_SYNC=true → sync stream', () => {
|
|
89
|
+
const d = capture(makeConfig({ sync: true }));
|
|
90
|
+
|
|
91
|
+
expect(d.stream.opts.sync).toBe(true);
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
describe('переход на worker-transport', () => {
|
|
96
|
+
it('forceTransport=true → transport c единственным stdout-таргетом', () => {
|
|
97
|
+
const d = capture(makeConfig({ forceTransport: true }));
|
|
98
|
+
|
|
99
|
+
expect(d.stream).toBeUndefined();
|
|
100
|
+
expect(d.transport.targets).toHaveLength(1);
|
|
101
|
+
|
|
102
|
+
const file = targetOf(d, 'pino/file');
|
|
103
|
+
|
|
104
|
+
expect(file?.options).toEqual({ destination: process.stdout.fd });
|
|
105
|
+
expect(file?.level).toBe(LogLevel.info);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it('otelEnabled=true → transport (stdout + otel)', () => {
|
|
109
|
+
const d = capture(makeConfig({ otelEnabled: true }));
|
|
110
|
+
|
|
111
|
+
expect(d.stream).toBeUndefined();
|
|
112
|
+
expect(targetOf(d, 'pino/file')).toBeDefined();
|
|
113
|
+
expect(targetOf(d, 'pino-opentelemetry-transport')).toBeDefined();
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('httpEndpoint задан → transport (stdout + http)', () => {
|
|
117
|
+
const d = capture(
|
|
118
|
+
makeConfig({ httpEndpoint: new URL('https://logs.example.com/in') }),
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
expect(d.stream).toBeUndefined();
|
|
122
|
+
expect(targetOf(d, 'pino-http-transport')).toBeDefined();
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it('otel + http → три таргета', () => {
|
|
126
|
+
const d = capture(
|
|
127
|
+
makeConfig({
|
|
128
|
+
otelEnabled: true,
|
|
129
|
+
httpEndpoint: new URL('https://logs.example.com/in'),
|
|
130
|
+
}),
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
expect(d.transport.targets).toHaveLength(3);
|
|
134
|
+
expect(targetOf(d, 'pino/file')).toBeDefined();
|
|
135
|
+
expect(targetOf(d, 'pino-opentelemetry-transport')).toBeDefined();
|
|
136
|
+
expect(targetOf(d, 'pino-http-transport')).toBeDefined();
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
describe('OTEL target', () => {
|
|
141
|
+
it('минимальный: без endpoint/protocol/serviceName', () => {
|
|
142
|
+
const d = capture(makeConfig({ otelEnabled: true }));
|
|
143
|
+
const otel = targetOf(d, 'pino-opentelemetry-transport')!;
|
|
144
|
+
const opts = otel.options as any;
|
|
145
|
+
|
|
146
|
+
expect(opts.logRecordProcessorOptions.recordProcessorType).toBe('batch');
|
|
147
|
+
expect(opts.logRecordProcessorOptions.exporterOptions).toEqual({});
|
|
148
|
+
expect(opts.loggerName).toBeUndefined();
|
|
149
|
+
expect(opts.resourceAttributes).toBeUndefined();
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it('полный: endpoint раскладывается по трём ключам, protocol и service.name выставлены', () => {
|
|
153
|
+
const d = capture(
|
|
154
|
+
makeConfig({
|
|
155
|
+
otelEnabled: true,
|
|
156
|
+
otelEndpoint: new URL('http://collector:4318'),
|
|
157
|
+
otelProtocol: LogOtelProtocol.grpc,
|
|
158
|
+
otelServiceName: 'my-svc',
|
|
159
|
+
}),
|
|
160
|
+
);
|
|
161
|
+
const opts = targetOf(d, 'pino-opentelemetry-transport')!.options as any;
|
|
162
|
+
const exporter = opts.logRecordProcessorOptions.exporterOptions;
|
|
163
|
+
const url = 'http://collector:4318/';
|
|
164
|
+
|
|
165
|
+
expect(exporter.protocol).toBe('grpc');
|
|
166
|
+
expect(exporter.httpExporterOptions).toEqual({ url });
|
|
167
|
+
expect(exporter.protobufExporterOptions).toEqual({ url });
|
|
168
|
+
expect(exporter.grpcExporterOptions).toEqual({ url });
|
|
169
|
+
expect(opts.loggerName).toBe('my-svc');
|
|
170
|
+
expect(opts.resourceAttributes).toEqual({ 'service.name': 'my-svc' });
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
it('endpoint без явного protocol → protocol не задаётся (env-fallback)', () => {
|
|
174
|
+
const d = capture(
|
|
175
|
+
makeConfig({
|
|
176
|
+
otelEnabled: true,
|
|
177
|
+
otelEndpoint: new URL('http://collector:4318'),
|
|
178
|
+
}),
|
|
179
|
+
);
|
|
180
|
+
const exporter = (
|
|
181
|
+
targetOf(d, 'pino-opentelemetry-transport')!.options as any
|
|
182
|
+
).logRecordProcessorOptions.exporterOptions;
|
|
183
|
+
|
|
184
|
+
expect(exporter.protocol).toBeUndefined();
|
|
185
|
+
expect(exporter.protobufExporterOptions).toEqual({
|
|
186
|
+
url: 'http://collector:4318/',
|
|
187
|
+
});
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
describe('HTTP target', () => {
|
|
192
|
+
it('url/headers проброшены, длительности конвертированы в мс', () => {
|
|
193
|
+
const d = capture(
|
|
194
|
+
makeConfig({
|
|
195
|
+
httpEndpoint: new URL('https://logs.example.com/ingest'),
|
|
196
|
+
httpHeaders: { 'x-api-key': 'secret' },
|
|
197
|
+
httpTimeout: new Timespan(3, 's'),
|
|
198
|
+
httpBatchInterval: new Timespan(10, 's'),
|
|
199
|
+
httpRetryDelay: new Timespan(500, 'ms'),
|
|
200
|
+
httpBatchSize: 50,
|
|
201
|
+
httpMaxRetries: 5,
|
|
202
|
+
httpMaxBufferSize: 42,
|
|
203
|
+
httpSilent: true,
|
|
204
|
+
}),
|
|
205
|
+
);
|
|
206
|
+
const opts = targetOf(d, 'pino-http-transport')!.options as any;
|
|
207
|
+
|
|
208
|
+
expect(opts.url).toBe('https://logs.example.com/ingest');
|
|
209
|
+
expect(opts.headers).toEqual({ 'x-api-key': 'secret' });
|
|
210
|
+
expect(opts.timeout).toBe(3000);
|
|
211
|
+
expect(opts.batchInterval).toBe(10000);
|
|
212
|
+
expect(opts.retryDelay).toBe(500);
|
|
213
|
+
expect(opts.batchSize).toBe(50);
|
|
214
|
+
expect(opts.maxRetries).toBe(5);
|
|
215
|
+
expect(opts.maxBufferSize).toBe(42);
|
|
216
|
+
expect(opts.silent).toBe(true);
|
|
217
|
+
});
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
describe('level', () => {
|
|
221
|
+
it('каждый таргет наследует config.level', () => {
|
|
222
|
+
const d = capture(
|
|
223
|
+
makeConfig({
|
|
224
|
+
level: LogLevel.warn,
|
|
225
|
+
otelEnabled: true,
|
|
226
|
+
httpEndpoint: new URL('https://logs.example.com/in'),
|
|
227
|
+
}),
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
for (const target of d.transport.targets as TransportTargetOptions[]) {
|
|
231
|
+
expect(target.level).toBe(LogLevel.warn);
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
describe('timestampFormat', () => {
|
|
237
|
+
it('logTimestampFormat маппится в timestampFormat (LOG_TIMESTAMP_FORMAT)', () => {
|
|
238
|
+
const d = capture(
|
|
239
|
+
makeConfig({ logTimestampFormat: LogTimestampFormat.epochTime }),
|
|
240
|
+
);
|
|
241
|
+
|
|
242
|
+
expect(d.timestampFormat).toBe(LogTimestampFormat.epochTime);
|
|
243
|
+
});
|
|
244
|
+
});
|
|
245
|
+
});
|
|
@@ -1,15 +1,19 @@
|
|
|
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
|
|
4
|
-
|
|
5
|
+
import pino, {
|
|
6
|
+
type TransportMultiOptions,
|
|
7
|
+
type TransportTargetOptions,
|
|
8
|
+
} from 'pino';
|
|
5
9
|
|
|
6
10
|
import { LoggingConfig } from './logging.config';
|
|
7
11
|
|
|
8
12
|
@Module({})
|
|
9
|
-
export class LoggerInitializingModule {
|
|
13
|
+
export class LoggerInitializingModule implements OnApplicationShutdown {
|
|
10
14
|
private static logger = LoggerFactory.create(LoggerInitializingModule);
|
|
11
15
|
|
|
12
|
-
constructor(config: LoggingConfig) {
|
|
16
|
+
constructor(private readonly config: LoggingConfig) {
|
|
13
17
|
const cfg = (): void => {
|
|
14
18
|
LoggerInitializingModule.logger.info(
|
|
15
19
|
`Setting log level: <${config.level}>`,
|
|
@@ -20,7 +24,8 @@ export class LoggerInitializingModule {
|
|
|
20
24
|
|
|
21
25
|
LoggerFactory.reconfigure({
|
|
22
26
|
...config,
|
|
23
|
-
|
|
27
|
+
timestampFormat: config.logTimestampFormat,
|
|
28
|
+
...this.buildDelivery(config),
|
|
24
29
|
});
|
|
25
30
|
};
|
|
26
31
|
|
|
@@ -28,28 +33,119 @@ export class LoggerInitializingModule {
|
|
|
28
33
|
cfg();
|
|
29
34
|
}
|
|
30
35
|
|
|
36
|
+
async onApplicationShutdown(): Promise<void> {
|
|
37
|
+
await LoggerFactory.shutdown(this.config.shutdownTimeout.millis());
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Worker-транспорт нужен только для сетевых приёмников (OTEL/HTTP) либо по
|
|
42
|
+
* явному запросу. Для логирования лишь в stdout остаёмся на in-process
|
|
43
|
+
* stream — без воркеров, как было до multitransport.
|
|
44
|
+
*/
|
|
45
|
+
private buildDelivery(config: LoggingConfig): Partial<LoggerOptions> {
|
|
46
|
+
const needsTransport =
|
|
47
|
+
config.otelEnabled ||
|
|
48
|
+
Boolean(config.httpEndpoint) ||
|
|
49
|
+
config.forceTransport;
|
|
50
|
+
|
|
51
|
+
return needsTransport
|
|
52
|
+
? { transport: this.buildTransportOptions(config) }
|
|
53
|
+
: {
|
|
54
|
+
stream: pino.destination({
|
|
55
|
+
dest: process.stdout.fd,
|
|
56
|
+
sync: config.sync,
|
|
57
|
+
}),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
31
61
|
private buildTransportOptions(config: LoggingConfig): TransportMultiOptions {
|
|
32
62
|
const targets: TransportTargetOptions[] = [
|
|
33
63
|
{
|
|
34
64
|
target: 'pino/file',
|
|
35
|
-
options: {
|
|
65
|
+
options: {
|
|
66
|
+
destination: process.stdout.fd,
|
|
67
|
+
},
|
|
36
68
|
level: config.level,
|
|
37
69
|
},
|
|
38
70
|
];
|
|
39
71
|
|
|
72
|
+
// OTEL включается флагом (endpoint опционален — резолвится из стандартных
|
|
73
|
+
// OTEL_* env), а HTTP — наличием endpoint (у него стандартного discovery
|
|
74
|
+
// нет). Отсюда разные модели enable у двух сетевых транспортов.
|
|
40
75
|
if (config.otelEnabled) {
|
|
41
|
-
targets.push(
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
* (unsafe destructuring in pino-opentelemetry-transport)
|
|
47
|
-
*/
|
|
48
|
-
options: {},
|
|
49
|
-
level: config.level,
|
|
50
|
-
});
|
|
76
|
+
targets.push(this.buildOtelTarget(config));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (config.httpEndpoint) {
|
|
80
|
+
targets.push(this.buildHttpTarget(config.httpEndpoint, config));
|
|
51
81
|
}
|
|
52
82
|
|
|
53
83
|
return { targets };
|
|
54
84
|
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* `otlp-logger` (через который работает pino-opentelemetry-transport) НЕ
|
|
88
|
+
* читает ключи `endpoint`/`serviceName`: endpoint задаётся через
|
|
89
|
+
* exporterOptions.url, а имя сервиса — через resourceAttributes/loggerName.
|
|
90
|
+
*/
|
|
91
|
+
private buildOtelTarget(config: LoggingConfig): TransportTargetOptions {
|
|
92
|
+
const exporterOptions: Record<string, unknown> = {};
|
|
93
|
+
|
|
94
|
+
// Без явного протокола otlp-logger резолвит его из стандартного
|
|
95
|
+
// OTEL_EXPORTER_OTLP_PROTOCOL env (default protobuf).
|
|
96
|
+
if (config.otelProtocol) {
|
|
97
|
+
exporterOptions.protocol = config.otelProtocol;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (config.otelEndpoint) {
|
|
101
|
+
const exporterUrl = { url: config.otelEndpoint.href };
|
|
102
|
+
|
|
103
|
+
// url кладём под все три ключа: otlp-logger прочитает только
|
|
104
|
+
// соответствующий выбранному протоколу, остальные проигнорирует.
|
|
105
|
+
exporterOptions.httpExporterOptions = exporterUrl;
|
|
106
|
+
exporterOptions.protobufExporterOptions = exporterUrl;
|
|
107
|
+
exporterOptions.grpcExporterOptions = exporterUrl;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const options: Record<string, unknown> = {
|
|
111
|
+
logRecordProcessorOptions: {
|
|
112
|
+
recordProcessorType: 'batch',
|
|
113
|
+
exporterOptions,
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
if (config.otelServiceName) {
|
|
118
|
+
options.loggerName = config.otelServiceName;
|
|
119
|
+
options.resourceAttributes = {
|
|
120
|
+
'service.name': config.otelServiceName,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
target: 'pino-opentelemetry-transport',
|
|
126
|
+
options,
|
|
127
|
+
level: config.level,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
private buildHttpTarget(
|
|
132
|
+
url: URL,
|
|
133
|
+
config: LoggingConfig,
|
|
134
|
+
): TransportTargetOptions {
|
|
135
|
+
return {
|
|
136
|
+
target: 'pino-http-transport',
|
|
137
|
+
options: {
|
|
138
|
+
url: url.href,
|
|
139
|
+
headers: config.httpHeaders,
|
|
140
|
+
timeout: config.httpTimeout.millis(),
|
|
141
|
+
batchSize: config.httpBatchSize,
|
|
142
|
+
batchInterval: config.httpBatchInterval.millis(),
|
|
143
|
+
maxRetries: config.httpMaxRetries,
|
|
144
|
+
retryDelay: config.httpRetryDelay.millis(),
|
|
145
|
+
maxBufferSize: config.httpMaxBufferSize,
|
|
146
|
+
silent: config.httpSilent,
|
|
147
|
+
},
|
|
148
|
+
level: config.level,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
55
151
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Timespan } from '@rsdk/common';
|
|
1
2
|
import { DEFAULT_LEVEL, LogLevel, LogTimestampFormat } from '@rsdk/logging';
|
|
2
3
|
|
|
3
4
|
import {
|
|
@@ -6,11 +7,23 @@ import {
|
|
|
6
7
|
Config,
|
|
7
8
|
ConfigSection,
|
|
8
9
|
EnumParser,
|
|
10
|
+
IntParser,
|
|
9
11
|
Property,
|
|
10
12
|
StringParser,
|
|
13
|
+
StringRecordParser,
|
|
14
|
+
TimespanParser,
|
|
15
|
+
UrlParser,
|
|
11
16
|
} from '../config';
|
|
12
17
|
import { ConfigTag } from '../config/config.const';
|
|
13
18
|
|
|
19
|
+
export enum LogOtelProtocol {
|
|
20
|
+
httpProtobuf = 'http/protobuf',
|
|
21
|
+
http = 'http',
|
|
22
|
+
httpJson = 'http/json',
|
|
23
|
+
grpc = 'grpc',
|
|
24
|
+
console = 'console',
|
|
25
|
+
}
|
|
26
|
+
|
|
14
27
|
@ConfigSection({
|
|
15
28
|
tags: [ConfigTag.infrastructure, ConfigTag.logging],
|
|
16
29
|
})
|
|
@@ -32,16 +45,107 @@ export class LoggingConfig extends Config {
|
|
|
32
45
|
@Property('LOG_SYNC', new BoolParser(), {
|
|
33
46
|
defaultValue: false,
|
|
34
47
|
description:
|
|
35
|
-
'Synchronous
|
|
48
|
+
'Synchronous stdout writes. Applies only to in-process stream mode; worker transports (OTEL/HTTP/forced) are always async. https://github.com/pinojs/pino/blob/master/docs/asynchronous.md',
|
|
36
49
|
})
|
|
37
50
|
readonly sync!: boolean;
|
|
38
51
|
|
|
52
|
+
@Property('LOG_SHUTDOWN_TIMEOUT', new TimespanParser(), {
|
|
53
|
+
defaultValue: new Timespan(1, 's'),
|
|
54
|
+
description:
|
|
55
|
+
'Max time to flush buffered worker-transport logs on application shutdown. Raise it when using OTEL: its worker may take longer to flush the last batch',
|
|
56
|
+
})
|
|
57
|
+
readonly shutdownTimeout!: Timespan;
|
|
58
|
+
|
|
59
|
+
@Property('LOG_FORCE_TRANSPORT', new BoolParser(), {
|
|
60
|
+
defaultValue: false,
|
|
61
|
+
description:
|
|
62
|
+
'Use worker-based transport even when only stdout is configured (no OTEL/HTTP). Otherwise stdout-only logging stays in-process',
|
|
63
|
+
})
|
|
64
|
+
readonly forceTransport!: boolean;
|
|
65
|
+
|
|
66
|
+
@Property('LOG_HTTP_ENDPOINT', new UrlParser('http:', 'https:'), {
|
|
67
|
+
defaultValue: undefined,
|
|
68
|
+
description:
|
|
69
|
+
'URL endpoint for the HTTP logs transport. Transport is enabled when set',
|
|
70
|
+
})
|
|
71
|
+
readonly httpEndpoint?: URL;
|
|
72
|
+
|
|
73
|
+
@Property('LOG_HTTP_HEADERS', new StringRecordParser(), {
|
|
74
|
+
defaultValue: {},
|
|
75
|
+
description: 'JSON object of HTTP headers sent by the HTTP logs transport',
|
|
76
|
+
})
|
|
77
|
+
readonly httpHeaders!: Record<string, string>;
|
|
78
|
+
|
|
79
|
+
@Property('LOG_HTTP_TIMEOUT', new TimespanParser(), {
|
|
80
|
+
defaultValue: new Timespan(2500, 'ms'),
|
|
81
|
+
description: 'Request timeout for the HTTP logs transport',
|
|
82
|
+
})
|
|
83
|
+
readonly httpTimeout!: Timespan;
|
|
84
|
+
|
|
85
|
+
@Property('LOG_HTTP_BATCH_SIZE', new IntParser(), {
|
|
86
|
+
defaultValue: 100,
|
|
87
|
+
description: 'Number of logs flushed per batch by the HTTP logs transport',
|
|
88
|
+
})
|
|
89
|
+
readonly httpBatchSize!: number;
|
|
90
|
+
|
|
91
|
+
@Property('LOG_HTTP_BATCH_INTERVAL', new TimespanParser(), {
|
|
92
|
+
defaultValue: new Timespan(5, 's'),
|
|
93
|
+
description:
|
|
94
|
+
'Max interval between batch flushes of the HTTP logs transport',
|
|
95
|
+
})
|
|
96
|
+
readonly httpBatchInterval!: Timespan;
|
|
97
|
+
|
|
98
|
+
@Property('LOG_HTTP_MAX_RETRIES', new IntParser(), {
|
|
99
|
+
defaultValue: 2,
|
|
100
|
+
description: 'Max retry attempts for a failed HTTP logs batch',
|
|
101
|
+
})
|
|
102
|
+
readonly httpMaxRetries!: number;
|
|
103
|
+
|
|
104
|
+
@Property('LOG_HTTP_RETRY_DELAY', new TimespanParser(), {
|
|
105
|
+
defaultValue: new Timespan(1, 's'),
|
|
106
|
+
description: 'Base delay between HTTP logs retry attempts',
|
|
107
|
+
})
|
|
108
|
+
readonly httpRetryDelay!: Timespan;
|
|
109
|
+
|
|
110
|
+
@Property('LOG_HTTP_MAX_BUFFER_SIZE', new IntParser(), {
|
|
111
|
+
defaultValue: 100000,
|
|
112
|
+
description:
|
|
113
|
+
'Max number of buffered logs before dropping (HTTP logs transport)',
|
|
114
|
+
})
|
|
115
|
+
readonly httpMaxBufferSize!: number;
|
|
116
|
+
|
|
117
|
+
@Property('LOG_HTTP_SILENT', new BoolParser(), {
|
|
118
|
+
defaultValue: false,
|
|
119
|
+
description: 'Suppress internal warnings/errors of the HTTP logs transport',
|
|
120
|
+
})
|
|
121
|
+
readonly httpSilent!: boolean;
|
|
122
|
+
|
|
39
123
|
@Property('LOG_OTEL_ENABLED', new BoolParser(), {
|
|
40
124
|
defaultValue: false,
|
|
41
|
-
description: 'Enable OpenTelemetry exporter',
|
|
125
|
+
description: 'Enable OpenTelemetry logs exporter',
|
|
42
126
|
})
|
|
43
127
|
readonly otelEnabled!: boolean;
|
|
44
128
|
|
|
129
|
+
@Property('LOG_OTEL_ENDPOINT', new UrlParser('http:', 'https:'), {
|
|
130
|
+
defaultValue: undefined,
|
|
131
|
+
description: 'OTLP endpoint URL for the OpenTelemetry logs exporter',
|
|
132
|
+
})
|
|
133
|
+
readonly otelEndpoint?: URL;
|
|
134
|
+
|
|
135
|
+
@Property('LOG_OTEL_PROTOCOL', new EnumParser(LogOtelProtocol), {
|
|
136
|
+
defaultValue: undefined,
|
|
137
|
+
description:
|
|
138
|
+
'OTLP exporter protocol for the OpenTelemetry logs. When unset, resolved from standard OTEL_EXPORTER_OTLP_PROTOCOL env (defaults to http/protobuf)',
|
|
139
|
+
})
|
|
140
|
+
readonly otelProtocol?: LogOtelProtocol;
|
|
141
|
+
|
|
142
|
+
@Property('LOG_OTEL_SERVICE_NAME', new StringParser(), {
|
|
143
|
+
defaultValue: undefined,
|
|
144
|
+
description:
|
|
145
|
+
'service.name resource attribute for the OpenTelemetry logs. When unset, resolved from standard OTEL env',
|
|
146
|
+
})
|
|
147
|
+
readonly otelServiceName?: string;
|
|
148
|
+
|
|
45
149
|
@Property('LOG_TIMESTAMP_FORMAT', new EnumParser(LogTimestampFormat), {
|
|
46
150
|
defaultValue: LogTimestampFormat.isoTime,
|
|
47
151
|
description: 'Log timestamp format',
|