@hemantwasthere/monitoring-sdk
Version:
Centralized monitoring SDK for Node.js applications with Prometheus, Loki, and Grafana integration
89 lines (88 loc) • 3.33 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggingService = void 0;
const winston_1 = require("winston");
const winston_loki_1 = __importDefault(require("winston-loki"));
class LoggingService {
constructor(config) {
this.config = config;
this.initializeLogger();
}
static getInstance(config) {
if (!LoggingService.instance) {
if (!config) {
throw new Error("Need config for first setup");
}
LoggingService.instance = new LoggingService(config);
}
else if (config) {
// Update settings if they changed
const currentConfigStr = JSON.stringify(LoggingService.instance.config);
const newConfigStr = JSON.stringify(config);
if (currentConfigStr !== newConfigStr) {
LoggingService.instance.config = config;
LoggingService.instance.initializeLogger();
}
}
return LoggingService.instance;
}
initializeLogger() {
const loggerTransports = [
new winston_1.transports.Console({
format: winston_1.format.combine(winston_1.format.colorize(), winston_1.format.timestamp(), winston_1.format.simple()),
}),
];
// Add Loki transport if host is provided
if (this.config.lokiHost) {
loggerTransports.push(new winston_loki_1.default({
host: this.config.lokiHost,
labels: {
app: this.config.projectName,
service: this.config.serviceName,
technology: this.config.technology,
environment: this.config.environment || "development",
...this.config.customLabels,
},
json: true,
replaceTimestamp: true,
onConnectionError: (err) => console.error("Loki connection error:", err),
}));
}
this.logger = (0, winston_1.createLogger)({
level: "info",
format: winston_1.format.combine(winston_1.format.timestamp(), winston_1.format.errors({ stack: true }), winston_1.format.json(), winston_1.format.label({
label: `${this.config.projectName}:${this.config.serviceName}`,
})),
transports: loggerTransports,
});
}
debug(message, ...args) {
this.logger.debug(message, ...args);
}
info(message, ...args) {
this.logger.info(message, ...args);
}
warn(message, ...args) {
this.logger.warn(message, ...args);
}
error(message, ...args) {
this.logger.error(message, ...args);
}
log(level, message, ...args) {
this.logger.log(level, message, ...args);
}
getLogger() {
return this.logger;
}
static reset() {
if (LoggingService.instance && LoggingService.instance.logger) {
LoggingService.instance.logger.clear();
LoggingService.instance.logger.close();
}
LoggingService.instance = undefined;
}
}
exports.LoggingService = LoggingService;