@rsdk/core 5.12.0 → 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.
Files changed (28) hide show
  1. package/dist/config/parsers/index.d.ts +1 -0
  2. package/dist/config/parsers/index.js +1 -0
  3. package/dist/config/parsers/index.js.map +1 -1
  4. package/dist/config/parsers/string-record/exception.d.ts +4 -0
  5. package/dist/config/parsers/string-record/exception.js +14 -0
  6. package/dist/config/parsers/string-record/exception.js.map +1 -0
  7. package/dist/config/parsers/string-record/index.d.ts +2 -0
  8. package/dist/config/parsers/string-record/index.js +21 -0
  9. package/dist/config/parsers/string-record/index.js.map +1 -0
  10. package/dist/config/parsers/string-record/string-record.parser.d.ts +8 -0
  11. package/dist/config/parsers/string-record/string-record.parser.js +42 -0
  12. package/dist/config/parsers/string-record/string-record.parser.js.map +1 -0
  13. package/dist/logging/logger-initializing.module.d.ts +17 -1
  14. package/dist/logging/logger-initializing.module.js +90 -11
  15. package/dist/logging/logger-initializing.module.js.map +1 -1
  16. package/dist/logging/logging.config.d.ts +22 -0
  17. package/dist/logging/logging.config.js +124 -3
  18. package/dist/logging/logging.config.js.map +1 -1
  19. package/package.json +6 -2
  20. package/src/config/parsers/index.ts +1 -0
  21. package/src/config/parsers/string-record/exception.ts +10 -0
  22. package/src/config/parsers/string-record/index.ts +2 -0
  23. package/src/config/parsers/string-record/string-record.parser.ts +55 -0
  24. package/src/config/parsers/string-record/string-record.spec.ts +33 -0
  25. package/src/logging/logger-factory.lifecycle.spec.ts +91 -0
  26. package/src/logging/logger-initializing.module.spec.ts +245 -0
  27. package/src/logging/logger-initializing.module.ts +112 -16
  28. package/src/logging/logging.config.ts +106 -2
@@ -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/';
@@ -21,6 +21,7 @@ __exportStar(require("./number"), exports);
21
21
  __exportStar(require("./path"), exports);
22
22
  __exportStar(require("./size"), exports);
23
23
  __exportStar(require("./string"), exports);
24
+ __exportStar(require("./string-record"), exports);
24
25
  __exportStar(require("./timespan"), exports);
25
26
  __exportStar(require("./url"), exports);
26
27
  __exportStar(require("./array/"), exports);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/config/parsers/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,yCAAuB;AACvB,wCAAsB;AACtB,2CAAyB;AACzB,yCAAuB;AACvB,yCAAuB;AACvB,2CAAyB;AACzB,6CAA2B;AAC3B,wCAAsB;AACtB,2CAAyB;AACzB,0CAAwB"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/config/parsers/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,4CAA0B;AAC1B,yCAAuB;AACvB,wCAAsB;AACtB,2CAAyB;AACzB,yCAAuB;AACvB,yCAAuB;AACvB,2CAAyB;AACzB,kDAAgC;AAChC,6CAA2B;AAC3B,wCAAsB;AACtB,2CAAyB;AACzB,0CAAwB"}
@@ -0,0 +1,4 @@
1
+ import { BootstrapException } from '../../../exceptions';
2
+ export declare class InvalidStringRecord extends BootstrapException {
3
+ constructor(reason: string, value: unknown, cause?: unknown);
4
+ }
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InvalidStringRecord = void 0;
4
+ const exceptions_1 = require("../../../exceptions");
5
+ class InvalidStringRecord extends exceptions_1.BootstrapException {
6
+ constructor(reason, value, cause) {
7
+ super(`Invalid string record: ${reason}`, {
8
+ cause,
9
+ details: { value },
10
+ });
11
+ }
12
+ }
13
+ exports.InvalidStringRecord = InvalidStringRecord;
14
+ //# sourceMappingURL=exception.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"exception.js","sourceRoot":"","sources":["../../../../src/config/parsers/string-record/exception.ts"],"names":[],"mappings":";;;AAAA,oDAAyD;AAEzD,MAAa,mBAAoB,SAAQ,+BAAkB;IACzD,YAAY,MAAc,EAAE,KAAc,EAAE,KAAe;QACzD,KAAK,CAAC,0BAA0B,MAAM,EAAE,EAAE;YACxC,KAAK;YACL,OAAO,EAAE,EAAE,KAAK,EAAE;SACnB,CAAC,CAAC;IACL,CAAC;CACF;AAPD,kDAOC"}
@@ -0,0 +1,2 @@
1
+ export * from './string-record.parser';
2
+ export { InvalidStringRecord } from './exception';
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.InvalidStringRecord = void 0;
18
+ __exportStar(require("./string-record.parser"), exports);
19
+ var exception_1 = require("./exception");
20
+ Object.defineProperty(exports, "InvalidStringRecord", { enumerable: true, get: function () { return exception_1.InvalidStringRecord; } });
21
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/config/parsers/string-record/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,yDAAuC;AACvC,yCAAkD;AAAzC,gHAAA,mBAAmB,OAAA"}
@@ -0,0 +1,8 @@
1
+ import type { PropertyParser } from '../../types';
2
+ /** Парсит JSON в плоский объект, проверяя, что все значения — строки. */
3
+ export declare class StringRecordParser implements PropertyParser<Record<string, string>> {
4
+ type(): string;
5
+ description(): string;
6
+ parse(value: unknown): Record<string, string>;
7
+ private toJson;
8
+ }
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.StringRecordParser = void 0;
4
+ const exception_1 = require("./exception");
5
+ /** Парсит JSON в плоский объект, проверяя, что все значения — строки. */
6
+ class StringRecordParser {
7
+ type() {
8
+ return 'json(Record<string, string>)';
9
+ }
10
+ description() {
11
+ return 'Parses a JSON object whose values are all strings';
12
+ }
13
+ parse(value) {
14
+ const parsed = this.toJson(value);
15
+ if (parsed === null ||
16
+ typeof parsed !== 'object' ||
17
+ Array.isArray(parsed)) {
18
+ throw new exception_1.InvalidStringRecord('expected a JSON object', value);
19
+ }
20
+ const result = {};
21
+ for (const [key, item] of Object.entries(parsed)) {
22
+ if (typeof item !== 'string') {
23
+ throw new exception_1.InvalidStringRecord(`value of key <${key}> must be a string, got ${typeof item}`, value);
24
+ }
25
+ result[key] = item;
26
+ }
27
+ return result;
28
+ }
29
+ toJson(value) {
30
+ if (typeof value !== 'string') {
31
+ return value;
32
+ }
33
+ try {
34
+ return JSON.parse(value);
35
+ }
36
+ catch (error) {
37
+ throw new exception_1.InvalidStringRecord('value is not valid JSON', value, error);
38
+ }
39
+ }
40
+ }
41
+ exports.StringRecordParser = StringRecordParser;
42
+ //# sourceMappingURL=string-record.parser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"string-record.parser.js","sourceRoot":"","sources":["../../../../src/config/parsers/string-record/string-record.parser.ts"],"names":[],"mappings":";;;AAEA,2CAAkD;AAElD,yEAAyE;AACzE,MAAa,kBAAkB;IAG7B,IAAI;QACF,OAAO,8BAA8B,CAAC;IACxC,CAAC;IAED,WAAW;QACT,OAAO,mDAAmD,CAAC;IAC7D,CAAC;IAED,KAAK,CAAC,KAAc;QAClB,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAElC,IACE,MAAM,KAAK,IAAI;YACf,OAAO,MAAM,KAAK,QAAQ;YAC1B,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EACrB,CAAC;YACD,MAAM,IAAI,+BAAmB,CAAC,wBAAwB,EAAE,KAAK,CAAC,CAAC;QACjE,CAAC;QAED,MAAM,MAAM,GAA2B,EAAE,CAAC;QAE1C,KAAK,MAAM,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;YACjD,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC7B,MAAM,IAAI,+BAAmB,CAC3B,iBAAiB,GAAG,2BAA2B,OAAO,IAAI,EAAE,EAC5D,KAAK,CACN,CAAC;YACJ,CAAC;YAED,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;QACrB,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAEO,MAAM,CAAC,KAAc;QAC3B,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;YAC9B,OAAO,KAAK,CAAC;QACf,CAAC;QAED,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QAC3B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,IAAI,+BAAmB,CAAC,yBAAyB,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;QACzE,CAAC;IACH,CAAC;CACF;AAjDD,gDAiDC"}
@@ -1,6 +1,22 @@
1
+ import type { OnApplicationShutdown } from '@nestjs/common';
1
2
  import { LoggingConfig } from './logging.config';
2
- export declare class LoggerInitializingModule {
3
+ export declare class LoggerInitializingModule implements OnApplicationShutdown {
4
+ private readonly config;
3
5
  private static logger;
4
6
  constructor(config: LoggingConfig);
7
+ onApplicationShutdown(): Promise<void>;
8
+ /**
9
+ * Worker-транспорт нужен только для сетевых приёмников (OTEL/HTTP) либо по
10
+ * явному запросу. Для логирования лишь в stdout остаёмся на in-process
11
+ * stream — без воркеров, как было до multitransport.
12
+ */
13
+ private buildDelivery;
5
14
  private buildTransportOptions;
15
+ /**
16
+ * `otlp-logger` (через который работает pino-opentelemetry-transport) НЕ
17
+ * читает ключи `endpoint`/`serviceName`: endpoint задаётся через
18
+ * exporterOptions.url, а имя сервиса — через resourceAttributes/loggerName.
19
+ */
20
+ private buildOtelTarget;
21
+ private buildHttpTarget;
6
22
  }
@@ -20,41 +20,120 @@ const pino_1 = __importDefault(require("pino"));
20
20
  const logging_config_1 = require("./logging.config");
21
21
  let LoggerInitializingModule = class LoggerInitializingModule {
22
22
  static { LoggerInitializingModule_1 = this; }
23
+ config;
23
24
  static logger = logging_1.LoggerFactory.create(LoggerInitializingModule_1);
24
25
  constructor(config) {
26
+ this.config = config;
25
27
  const cfg = () => {
26
28
  LoggerInitializingModule_1.logger.info(`Setting log level: <${config.level}>`, {
27
29
  logLevel: config.level,
28
30
  });
29
31
  logging_1.LoggerFactory.reconfigure({
30
32
  ...config,
31
- stream: pino_1.default.transport(this.buildTransportOptions(config)),
33
+ timestampFormat: config.logTimestampFormat,
34
+ ...this.buildDelivery(config),
32
35
  });
33
36
  };
34
37
  config.onUpdate(cfg);
35
38
  cfg();
36
39
  }
40
+ async onApplicationShutdown() {
41
+ await logging_1.LoggerFactory.shutdown(this.config.shutdownTimeout.millis());
42
+ }
43
+ /**
44
+ * Worker-транспорт нужен только для сетевых приёмников (OTEL/HTTP) либо по
45
+ * явному запросу. Для логирования лишь в stdout остаёмся на in-process
46
+ * stream — без воркеров, как было до multitransport.
47
+ */
48
+ buildDelivery(config) {
49
+ const needsTransport = config.otelEnabled ||
50
+ Boolean(config.httpEndpoint) ||
51
+ config.forceTransport;
52
+ return needsTransport
53
+ ? { transport: this.buildTransportOptions(config) }
54
+ : {
55
+ stream: pino_1.default.destination({
56
+ dest: process.stdout.fd,
57
+ sync: config.sync,
58
+ }),
59
+ };
60
+ }
37
61
  buildTransportOptions(config) {
38
62
  const targets = [
39
63
  {
40
64
  target: 'pino/file',
41
- options: { destination: process.stdout.fd },
65
+ options: {
66
+ destination: process.stdout.fd,
67
+ },
42
68
  level: config.level,
43
69
  },
44
70
  ];
71
+ // OTEL включается флагом (endpoint опционален — резолвится из стандартных
72
+ // OTEL_* env), а HTTP — наличием endpoint (у него стандартного discovery
73
+ // нет). Отсюда разные модели enable у двух сетевых транспортов.
45
74
  if (config.otelEnabled) {
46
- targets.push({
47
- target: 'pino-opentelemetry-transport',
48
- /**
49
- * NOTE: {} required to avoid runtime error "Cannot read property 'xxx' of undefined"
50
- * (unsafe destructuring in pino-opentelemetry-transport)
51
- */
52
- options: {},
53
- level: config.level,
54
- });
75
+ targets.push(this.buildOtelTarget(config));
76
+ }
77
+ if (config.httpEndpoint) {
78
+ targets.push(this.buildHttpTarget(config.httpEndpoint, config));
55
79
  }
56
80
  return { targets };
57
81
  }
82
+ /**
83
+ * `otlp-logger` (через который работает pino-opentelemetry-transport) НЕ
84
+ * читает ключи `endpoint`/`serviceName`: endpoint задаётся через
85
+ * exporterOptions.url, а имя сервиса — через resourceAttributes/loggerName.
86
+ */
87
+ buildOtelTarget(config) {
88
+ const exporterOptions = {};
89
+ // Без явного протокола otlp-logger резолвит его из стандартного
90
+ // OTEL_EXPORTER_OTLP_PROTOCOL env (default protobuf).
91
+ if (config.otelProtocol) {
92
+ exporterOptions.protocol = config.otelProtocol;
93
+ }
94
+ if (config.otelEndpoint) {
95
+ const exporterUrl = { url: config.otelEndpoint.href };
96
+ // url кладём под все три ключа: otlp-logger прочитает только
97
+ // соответствующий выбранному протоколу, остальные проигнорирует.
98
+ exporterOptions.httpExporterOptions = exporterUrl;
99
+ exporterOptions.protobufExporterOptions = exporterUrl;
100
+ exporterOptions.grpcExporterOptions = exporterUrl;
101
+ }
102
+ const options = {
103
+ logRecordProcessorOptions: {
104
+ recordProcessorType: 'batch',
105
+ exporterOptions,
106
+ },
107
+ };
108
+ if (config.otelServiceName) {
109
+ options.loggerName = config.otelServiceName;
110
+ options.resourceAttributes = {
111
+ 'service.name': config.otelServiceName,
112
+ };
113
+ }
114
+ return {
115
+ target: 'pino-opentelemetry-transport',
116
+ options,
117
+ level: config.level,
118
+ };
119
+ }
120
+ buildHttpTarget(url, config) {
121
+ return {
122
+ target: 'pino-http-transport',
123
+ options: {
124
+ url: url.href,
125
+ headers: config.httpHeaders,
126
+ timeout: config.httpTimeout.millis(),
127
+ batchSize: config.httpBatchSize,
128
+ batchInterval: config.httpBatchInterval.millis(),
129
+ maxRetries: config.httpMaxRetries,
130
+ retryDelay: config.httpRetryDelay.millis(),
131
+ maxBufferSize: config.httpMaxBufferSize,
132
+ silent: config.httpSilent,
133
+ },
134
+ level: config.level,
135
+ };
136
+ }
58
137
  };
59
138
  exports.LoggerInitializingModule = LoggerInitializingModule;
60
139
  exports.LoggerInitializingModule = LoggerInitializingModule = LoggerInitializingModule_1 = __decorate([
@@ -1 +1 @@
1
- {"version":3,"file":"logger-initializing.module.js","sourceRoot":"","sources":["../../src/logging/logger-initializing.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,2CAAwC;AACxC,2CAA8C;AAE9C,gDAAwB;AAExB,qDAAiD;AAG1C,IAAM,wBAAwB,GAA9B,MAAM,wBAAwB;;IAC3B,MAAM,CAAC,MAAM,GAAG,uBAAa,CAAC,MAAM,CAAC,0BAAwB,CAAC,CAAC;IAEvE,YAAY,MAAqB;QAC/B,MAAM,GAAG,GAAG,GAAS,EAAE;YACrB,0BAAwB,CAAC,MAAM,CAAC,IAAI,CAClC,uBAAuB,MAAM,CAAC,KAAK,GAAG,EACtC;gBACE,QAAQ,EAAE,MAAM,CAAC,KAAK;aACvB,CACF,CAAC;YAEF,uBAAa,CAAC,WAAW,CAAC;gBACxB,GAAG,MAAM;gBACT,MAAM,EAAE,cAAI,CAAC,SAAS,CAAC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;aAC3D,CAAC,CAAC;QACL,CAAC,CAAC;QAEF,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;QACrB,GAAG,EAAE,CAAC;IACR,CAAC;IAEO,qBAAqB,CAAC,MAAqB;QACjD,MAAM,OAAO,GAA6B;YACxC;gBACE,MAAM,EAAE,WAAW;gBACnB,OAAO,EAAE,EAAE,WAAW,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,EAAE;gBAC3C,KAAK,EAAE,MAAM,CAAC,KAAK;aACpB;SACF,CAAC;QAEF,IAAI,MAAM,CAAC,WAAW,EAAE,CAAC;YACvB,OAAO,CAAC,IAAI,CAAC;gBACX,MAAM,EAAE,8BAA8B;gBAEtC;;;mBAGG;gBACH,OAAO,EAAE,EAAE;gBACX,KAAK,EAAE,MAAM,CAAC,KAAK;aACpB,CAAC,CAAC;QACL,CAAC;QAED,OAAO,EAAE,OAAO,EAAE,CAAC;IACrB,CAAC;;AA7CU,4DAAwB;mCAAxB,wBAAwB;IADpC,IAAA,eAAM,EAAC,EAAE,CAAC;qCAIW,8BAAa;GAHtB,wBAAwB,CA8CpC"}
1
+ {"version":3,"file":"logger-initializing.module.js","sourceRoot":"","sources":["../../src/logging/logger-initializing.module.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AACA,2CAAwC;AAExC,2CAA8C;AAC9C,gDAGc;AAEd,qDAAiD;AAG1C,IAAM,wBAAwB,GAA9B,MAAM,wBAAwB;;IAGN;IAFrB,MAAM,CAAC,MAAM,GAAG,uBAAa,CAAC,MAAM,CAAC,0BAAwB,CAAC,CAAC;IAEvE,YAA6B,MAAqB;QAArB,WAAM,GAAN,MAAM,CAAe;QAChD,MAAM,GAAG,GAAG,GAAS,EAAE;YACrB,0BAAwB,CAAC,MAAM,CAAC,IAAI,CAClC,uBAAuB,MAAM,CAAC,KAAK,GAAG,EACtC;gBACE,QAAQ,EAAE,MAAM,CAAC,KAAK;aACvB,CACF,CAAC;YAEF,uBAAa,CAAC,WAAW,CAAC;gBACxB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AC,WAAW;gBAC3B,OAAO,EAAE,MAAM,CAAC,WAAW,CAAC,MAAM,EAAE;gBACpC,SAAS,EAAE,MAAM,CAAC,aAAa;gBAC/B,aAAa,EAAE,MAAM,CAAC,iBAAiB,CAAC,MAAM,EAAE;gBAChD,UAAU,EAAE,MAAM,CAAC,cAAc;gBACjC,UAAU,EAAE,MAAM,CAAC,cAAc,CAAC,MAAM,EAAE;gBAC1C,aAAa,EAAE,MAAM,CAAC,iBAAiB;gBACvC,MAAM,EAAE,MAAM,CAAC,UAAU;aAC1B;YACD,KAAK,EAAE,MAAM,CAAC,KAAK;SACpB,CAAC;IACJ,CAAC;;AAzIU,4DAAwB;mCAAxB,wBAAwB;IADpC,IAAA,eAAM,EAAC,EAAE,CAAC;qCAI4B,8BAAa;GAHvC,wBAAwB,CA0IpC"}
@@ -1,9 +1,31 @@
1
+ import { Timespan } from '@rsdk/common';
1
2
  import { LogLevel, LogTimestampFormat } from '@rsdk/logging';
2
3
  import { Config } from '../config';
4
+ export declare enum LogOtelProtocol {
5
+ httpProtobuf = "http/protobuf",
6
+ http = "http",
7
+ httpJson = "http/json",
8
+ grpc = "grpc",
9
+ console = "console"
10
+ }
3
11
  export declare class LoggingConfig extends Config {
4
12
  readonly level: LogLevel;
5
13
  readonly redact: string[];
6
14
  readonly sync: boolean;
15
+ readonly shutdownTimeout: Timespan;
16
+ readonly forceTransport: boolean;
17
+ readonly httpEndpoint?: URL;
18
+ readonly httpHeaders: Record<string, string>;
19
+ readonly httpTimeout: Timespan;
20
+ readonly httpBatchSize: number;
21
+ readonly httpBatchInterval: Timespan;
22
+ readonly httpMaxRetries: number;
23
+ readonly httpRetryDelay: Timespan;
24
+ readonly httpMaxBufferSize: number;
25
+ readonly httpSilent: boolean;
7
26
  readonly otelEnabled: boolean;
27
+ readonly otelEndpoint?: URL;
28
+ readonly otelProtocol?: LogOtelProtocol;
29
+ readonly otelServiceName?: string;
8
30
  readonly logTimestampFormat: LogTimestampFormat;
9
31
  }
@@ -9,15 +9,38 @@ var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.LoggingConfig = void 0;
12
+ exports.LoggingConfig = exports.LogOtelProtocol = void 0;
13
+ const common_1 = require("@rsdk/common");
13
14
  const logging_1 = require("@rsdk/logging");
14
15
  const config_1 = require("../config");
15
16
  const config_const_1 = require("../config/config.const");
17
+ var LogOtelProtocol;
18
+ (function (LogOtelProtocol) {
19
+ LogOtelProtocol["httpProtobuf"] = "http/protobuf";
20
+ LogOtelProtocol["http"] = "http";
21
+ LogOtelProtocol["httpJson"] = "http/json";
22
+ LogOtelProtocol["grpc"] = "grpc";
23
+ LogOtelProtocol["console"] = "console";
24
+ })(LogOtelProtocol || (exports.LogOtelProtocol = LogOtelProtocol = {}));
16
25
  let LoggingConfig = class LoggingConfig extends config_1.Config {
17
26
  level;
18
27
  redact;
19
28
  sync;
29
+ shutdownTimeout;
30
+ forceTransport;
31
+ httpEndpoint;
32
+ httpHeaders;
33
+ httpTimeout;
34
+ httpBatchSize;
35
+ httpBatchInterval;
36
+ httpMaxRetries;
37
+ httpRetryDelay;
38
+ httpMaxBufferSize;
39
+ httpSilent;
20
40
  otelEnabled;
41
+ otelEndpoint;
42
+ otelProtocol;
43
+ otelServiceName;
21
44
  logTimestampFormat;
22
45
  };
23
46
  exports.LoggingConfig = LoggingConfig;
@@ -39,17 +62,115 @@ __decorate([
39
62
  __decorate([
40
63
  (0, config_1.Property)('LOG_SYNC', new config_1.BoolParser(), {
41
64
  defaultValue: false,
42
- description: 'Synchronous logs: https://github.com/pinojs/pino/blob/master/docs/asynchronous.md#asynchronous-logging',
65
+ description: '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',
43
66
  }),
44
67
  __metadata("design:type", Boolean)
45
68
  ], LoggingConfig.prototype, "sync", void 0);
69
+ __decorate([
70
+ (0, config_1.Property)('LOG_SHUTDOWN_TIMEOUT', new config_1.TimespanParser(), {
71
+ defaultValue: new common_1.Timespan(1, 's'),
72
+ description: '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',
73
+ }),
74
+ __metadata("design:type", common_1.Timespan)
75
+ ], LoggingConfig.prototype, "shutdownTimeout", void 0);
76
+ __decorate([
77
+ (0, config_1.Property)('LOG_FORCE_TRANSPORT', new config_1.BoolParser(), {
78
+ defaultValue: false,
79
+ description: 'Use worker-based transport even when only stdout is configured (no OTEL/HTTP). Otherwise stdout-only logging stays in-process',
80
+ }),
81
+ __metadata("design:type", Boolean)
82
+ ], LoggingConfig.prototype, "forceTransport", void 0);
83
+ __decorate([
84
+ (0, config_1.Property)('LOG_HTTP_ENDPOINT', new config_1.UrlParser('http:', 'https:'), {
85
+ defaultValue: undefined,
86
+ description: 'URL endpoint for the HTTP logs transport. Transport is enabled when set',
87
+ }),
88
+ __metadata("design:type", URL)
89
+ ], LoggingConfig.prototype, "httpEndpoint", void 0);
90
+ __decorate([
91
+ (0, config_1.Property)('LOG_HTTP_HEADERS', new config_1.StringRecordParser(), {
92
+ defaultValue: {},
93
+ description: 'JSON object of HTTP headers sent by the HTTP logs transport',
94
+ }),
95
+ __metadata("design:type", Object)
96
+ ], LoggingConfig.prototype, "httpHeaders", void 0);
97
+ __decorate([
98
+ (0, config_1.Property)('LOG_HTTP_TIMEOUT', new config_1.TimespanParser(), {
99
+ defaultValue: new common_1.Timespan(2500, 'ms'),
100
+ description: 'Request timeout for the HTTP logs transport',
101
+ }),
102
+ __metadata("design:type", common_1.Timespan)
103
+ ], LoggingConfig.prototype, "httpTimeout", void 0);
104
+ __decorate([
105
+ (0, config_1.Property)('LOG_HTTP_BATCH_SIZE', new config_1.IntParser(), {
106
+ defaultValue: 100,
107
+ description: 'Number of logs flushed per batch by the HTTP logs transport',
108
+ }),
109
+ __metadata("design:type", Number)
110
+ ], LoggingConfig.prototype, "httpBatchSize", void 0);
111
+ __decorate([
112
+ (0, config_1.Property)('LOG_HTTP_BATCH_INTERVAL', new config_1.TimespanParser(), {
113
+ defaultValue: new common_1.Timespan(5, 's'),
114
+ description: 'Max interval between batch flushes of the HTTP logs transport',
115
+ }),
116
+ __metadata("design:type", common_1.Timespan)
117
+ ], LoggingConfig.prototype, "httpBatchInterval", void 0);
118
+ __decorate([
119
+ (0, config_1.Property)('LOG_HTTP_MAX_RETRIES', new config_1.IntParser(), {
120
+ defaultValue: 2,
121
+ description: 'Max retry attempts for a failed HTTP logs batch',
122
+ }),
123
+ __metadata("design:type", Number)
124
+ ], LoggingConfig.prototype, "httpMaxRetries", void 0);
125
+ __decorate([
126
+ (0, config_1.Property)('LOG_HTTP_RETRY_DELAY', new config_1.TimespanParser(), {
127
+ defaultValue: new common_1.Timespan(1, 's'),
128
+ description: 'Base delay between HTTP logs retry attempts',
129
+ }),
130
+ __metadata("design:type", common_1.Timespan)
131
+ ], LoggingConfig.prototype, "httpRetryDelay", void 0);
132
+ __decorate([
133
+ (0, config_1.Property)('LOG_HTTP_MAX_BUFFER_SIZE', new config_1.IntParser(), {
134
+ defaultValue: 100000,
135
+ description: 'Max number of buffered logs before dropping (HTTP logs transport)',
136
+ }),
137
+ __metadata("design:type", Number)
138
+ ], LoggingConfig.prototype, "httpMaxBufferSize", void 0);
139
+ __decorate([
140
+ (0, config_1.Property)('LOG_HTTP_SILENT', new config_1.BoolParser(), {
141
+ defaultValue: false,
142
+ description: 'Suppress internal warnings/errors of the HTTP logs transport',
143
+ }),
144
+ __metadata("design:type", Boolean)
145
+ ], LoggingConfig.prototype, "httpSilent", void 0);
46
146
  __decorate([
47
147
  (0, config_1.Property)('LOG_OTEL_ENABLED', new config_1.BoolParser(), {
48
148
  defaultValue: false,
49
- description: 'Enable OpenTelemetry exporter',
149
+ description: 'Enable OpenTelemetry logs exporter',
50
150
  }),
51
151
  __metadata("design:type", Boolean)
52
152
  ], LoggingConfig.prototype, "otelEnabled", void 0);
153
+ __decorate([
154
+ (0, config_1.Property)('LOG_OTEL_ENDPOINT', new config_1.UrlParser('http:', 'https:'), {
155
+ defaultValue: undefined,
156
+ description: 'OTLP endpoint URL for the OpenTelemetry logs exporter',
157
+ }),
158
+ __metadata("design:type", URL)
159
+ ], LoggingConfig.prototype, "otelEndpoint", void 0);
160
+ __decorate([
161
+ (0, config_1.Property)('LOG_OTEL_PROTOCOL', new config_1.EnumParser(LogOtelProtocol), {
162
+ defaultValue: undefined,
163
+ description: 'OTLP exporter protocol for the OpenTelemetry logs. When unset, resolved from standard OTEL_EXPORTER_OTLP_PROTOCOL env (defaults to http/protobuf)',
164
+ }),
165
+ __metadata("design:type", String)
166
+ ], LoggingConfig.prototype, "otelProtocol", void 0);
167
+ __decorate([
168
+ (0, config_1.Property)('LOG_OTEL_SERVICE_NAME', new config_1.StringParser(), {
169
+ defaultValue: undefined,
170
+ description: 'service.name resource attribute for the OpenTelemetry logs. When unset, resolved from standard OTEL env',
171
+ }),
172
+ __metadata("design:type", String)
173
+ ], LoggingConfig.prototype, "otelServiceName", void 0);
53
174
  __decorate([
54
175
  (0, config_1.Property)('LOG_TIMESTAMP_FORMAT', new config_1.EnumParser(logging_1.LogTimestampFormat), {
55
176
  defaultValue: logging_1.LogTimestampFormat.isoTime,
@@ -1 +1 @@
1
- {"version":3,"file":"logging.config.js","sourceRoot":"","sources":["../../src/logging/logging.config.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAA4E;AAE5E,sCAQmB;AACnB,yDAAmD;AAK5C,IAAM,aAAa,GAAnB,MAAM,aAAc,SAAQ,eAAM;IAM9B,KAAK,CAAY;IAOjB,MAAM,CAAY;IAOlB,IAAI,CAAW;IAMf,WAAW,CAAW;IAMtB,kBAAkB,CAAsB;CAClD,CAAA;AAjCY,sCAAa;AAMf;IALR,IAAA,iBAAQ,EAAC,WAAW,EAAE,IAAI,mBAAU,CAAC,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zB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsdk/core",
3
- "version": "5.12.0",
3
+ "version": "5.13.0-next.0",
4
4
  "description": "Nestjs based microservice chassis",
5
5
  "license": "Apache License 2.0",
6
6
  "publishConfig": {
@@ -34,6 +34,7 @@
34
34
  "@rsdk/logging": "*",
35
35
  "@rsdk/metadata": "*",
36
36
  "@rsdk/nest-tools": "*",
37
+ "pino-http-transport": "^1.0.0",
37
38
  "pino-opentelemetry-transport": "^1.0.1",
38
39
  "reflect-metadata": "^0.1.12 || ^0.2.0",
39
40
  "rxjs": "^7.1.0"
@@ -45,9 +46,12 @@
45
46
  "@opentelemetry/exporter-logs-otlp-http": {
46
47
  "optional": true
47
48
  },
49
+ "pino-http-transport": {
50
+ "optional": true
51
+ },
48
52
  "pino-opentelemetry-transport": {
49
53
  "optional": true
50
54
  }
51
55
  },
52
- "gitHead": "e37dbd5dfabbc6150e3d22d545b03ee5e41bf6a4"
56
+ "gitHead": "6efbb4a745c7e9cf44c5c71b6365ffb290820894"
53
57
  }
@@ -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,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 type { TransportMultiOptions, TransportTargetOptions } from 'pino';
4
- import pino from 'pino';
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
- stream: pino.transport(this.buildTransportOptions(config)),
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: { destination: process.stdout.fd },
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
- 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
- });
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 logs: https://github.com/pinojs/pino/blob/master/docs/asynchronous.md#asynchronous-logging',
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',