Files
pos-system/microservices/packages/tracing/src/index.ts
Ho Ngoc Hai 76d75c753b Migrate
2026-05-23 18:37:02 +07:00

56 lines
2.1 KiB
TypeScript

import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
/**
* EN: Configuration interface for distributed tracing setup
* VI: Interface cấu hình cho việc thiết lập distributed tracing
*/
export interface TracingConfig {
/** EN: Name of the service for trace identification / VI: Tên service để xác định trace */
serviceName: string;
/** EN: OTLP collector endpoint URL (default: http://localhost:4318/v1/traces) / VI: URL endpoint OTLP collector (mặc định: http://localhost:4318/v1/traces) */
otlpEndpoint?: string;
/** EN: Enable/disable tracing (default: true) / VI: Bật/tắt tracing (mặc định: true) */
enabled?: boolean;
}
/**
* EN: Initialize OpenTelemetry distributed tracing with OTLP exporter
* VI: Khởi tạo OpenTelemetry distributed tracing với OTLP exporter
*
* @param config - Tracing configuration / Cấu hình tracing
* @returns NodeSDK instance or null if tracing is disabled / Instance NodeSDK hoặc null nếu tracing bị tắt
*/
export const initTracing = (config: TracingConfig): NodeSDK | null => {
// EN: Return null if tracing is explicitly disabled
// VI: Trả về null nếu tracing bị tắt rõ ràng
if (config.enabled === false) {
return null;
}
// EN: Create OTLP exporter with configured endpoint
// VI: Tạo OTLP exporter với endpoint được cấu hình
const traceExporter = new OTLPTraceExporter({
url: config.otlpEndpoint || 'http://localhost:4318/v1/traces',
});
// EN: Initialize OpenTelemetry NodeSDK with auto-instrumentations
// VI: Khởi tạo OpenTelemetry NodeSDK với auto-instrumentations
const sdk = new NodeSDK({
serviceName: config.serviceName,
traceExporter,
instrumentations: [getNodeAutoInstrumentations()],
});
// EN: Start the tracing SDK
// VI: Khởi động tracing SDK
sdk.start();
return sdk;
};
// EN: Default export for the initTracing function
// VI: Export default cho hàm initTracing
export default initTracing;