radius-read
Version:
Realtime Dashboard
322 lines • 11 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LoggerService = void 0;
const tslib_1 = require("tslib");
const winston_1 = tslib_1.__importStar(require("winston"));
const winston_daily_rotate_file_1 = tslib_1.__importDefault(require("winston-daily-rotate-file"));
const path = tslib_1.__importStar(require("path"));
const moment_1 = tslib_1.__importDefault(require("moment"));
const logger_enum_1 = require("./../enums/logger.enum");
const logger_model_1 = require("./../models/logger.model");
const { combine, splat, timestamp, printf } = winston_1.format;
/**
* LoggerService provides methods for logging messages with different severity levels.
*/
class LoggerService {
/**
* Creates an instance of LoggerService.
*/
constructor() {
/**
* Project root directory path
* @date Jun 26, 2025 10:55:41 AM
* @author Biswaranjan Nayak
*
* @private
* @type {string}
*/
this.PROJECT_ROOT = path.join(__dirname, '..');
/**
* Variable to check if custom format is enabled
* @date Jun 26, 2025 10:56:32 AM
* @author Biswaranjan Nayak
*
* @private
* @type {boolean}
*/
this.iscustomFormatEnabled = true;
/**
* Custom format for log messages with timestamp, level, and message.
* @date Jun 26, 2025 10:59:25 AM
* @author Biswaranjan Nayak
*
* @private
* @type {*}
*/
this.customFormat = printf((_a) => {
var { level, message, timestamp } = _a, metadata = tslib_1.__rest(_a, ["level", "message", "timestamp"]);
let msg = `[${(0, moment_1.default)(timestamp).format('MMM DD, YYYY, hh:mm:ss A')}] [${level.toUpperCase()}] ${message}`;
if (metadata && Object.keys(metadata).length > 0) {
msg += JSON.stringify(metadata);
}
return msg;
});
/**
* No custom format for log messages, just prints the message to console.
* @date Jun 26, 2025 10:59:37 AM
* @author Biswaranjan Nayak
*
* @private
* @type {*}
*/
this.nocustomFormat = printf((_a) => {
var { level, message, timestamp } = _a, metadata = tslib_1.__rest(_a, ["level", "message", "timestamp"]);
let msg = `${message}`;
// if(metadata) {
// msg += JSON.stringify(metadata)
// }
console.log(message);
return msg;
});
}
/**
* Initializes the logger with the given log appender and custom format option.
* @param logAppender
* @param customFormat
* @returns
*/
init(logAppender, customFormat = true) {
if (!logAppender)
return false;
var config = new logger_model_1.LogConfig();
config.customFormat = customFormat;
config.type = logger_enum_1.LogType.Multi;
config.options = new logger_model_1.LogOptions();
config.options.console = new logger_model_1.ConsoleLogOptions();
config.options.file = new logger_model_1.FileLogOptions();
config.options.file.filename = logAppender.rollingFileAppender.filename;
config.options.file.maxfiles = logAppender.rollingFileAppender.backups;
config.options.file.maxsize = logAppender.rollingFileAppender.maxLogSize;
return this.configure(config);
}
/**
* Configures the logger based on the provided configuration.
* @param config
* @returns
*/
configure(config) {
this.iscustomFormatEnabled = config.customFormat;
var flag = false;
if (config.type === logger_enum_1.LogType.Multi) {
if (config.options.console && config.options.file) {
this.configureMultiLogger(config.options.console, config.options.file, config.customFormat);
flag = true;
}
}
else if (config.type === logger_enum_1.LogType.Console) {
if (config.options.console) {
this.configureConsoleLogger(config.options.console, config.customFormat);
flag = true;
}
}
else if (config.type === logger_enum_1.LogType.File) {
if (config.options.file) {
this.configureFileLogger(config.options.file, config.customFormat);
flag = true;
}
}
else {
if (config.options.console) {
this.configureConsoleLogger(config.options.console, config.customFormat);
flag = true;
}
}
if (flag === true) {
this.LOGGER.stream = {
write: function (message) {
this.LOGGER.info(message);
}
};
}
return flag;
}
;
/**
* Configures the console logger with the provided options and custom format.
* @param logOptions
* @param customFormat
*/
configureConsoleLogger(logOptions, customFormat = true) {
var logConfig = {
transports: [
new (winston_1.default.transports.Console)(logOptions)
],
exitOnError: false,
};
if (customFormat) {
logConfig.format = combine(splat(), timestamp(), this.customFormat);
}
else {
logConfig.format = combine(this.nocustomFormat);
}
this.LOGGER = winston_1.default.createLogger(logConfig);
}
;
/**
* Configures the file logger with the provided options and custom format.
* @param logOptions
* @param customFormat
*/
configureFileLogger(logOptions, customFormat = true) {
var logConfig = {
transports: [
new (winston_1.default.transports.File)(logOptions)
],
exitOnError: false,
};
if (customFormat) {
logConfig.format = combine(splat(), timestamp(), this.customFormat);
}
else {
logConfig.format = combine(this.nocustomFormat);
}
this.LOGGER = winston_1.default.createLogger(logConfig);
}
;
/**
* Configures the multi logger with console and file options, and custom format.
* @param consoleLogOptions
* @param fileLogOptions
* @param customFormat
*/
configureMultiLogger(consoleLogOptions, fileLogOptions, customFormat = true) {
var logConfig = {
transports: [
new (winston_1.default.transports.Console)(consoleLogOptions),
// new (winston.transports.File)(fileLogOptions),
new winston_daily_rotate_file_1.default({
filename: fileLogOptions.filename,
zippedArchive: true,
maxSize: fileLogOptions.maxsize,
maxFiles: fileLogOptions.maxfiles,
level: fileLogOptions.level,
datePattern: 'DD-MM-YYYY',
eol: '\n\n'
// dirname: this.LOG_DIR,
// createSymlink: true,
// symlinkName: path.basename(fileLogOptions.filename),
})
],
exitOnError: false,
};
if (customFormat) {
logConfig.format = combine(splat(), timestamp(), this.customFormat);
}
else {
logConfig.format = combine(this.nocustomFormat);
}
this.LOGGER = winston_1.default.createLogger(logConfig);
}
;
/**
* Debug log method to log debug messages.
* @param args
*/
debug(...args) {
this.LOGGER.debug(this.joinArray(this.formatLogArguments(args)));
}
;
/**
* Log method to log messages at the default level.
* @param args
*/
log(...args) {
this.LOGGER.debug(this.joinArray(this.formatLogArguments(args)));
}
;
/**
* Info log method to log informational messages.
* @param args
*/
info(...args) {
this.LOGGER.info(this.joinArray(this.formatLogArguments(args)));
}
;
/**
* Warn log method to log warning messages.
* @param args
*/
warn(...args) {
this.LOGGER.warn(this.joinArray(this.formatLogArguments(args)));
}
;
/**
* Error log method to log error messages.
* @param args
*/
error(...args) {
this.LOGGER.error(this.joinArray(this.formatLogArguments(args)));
}
;
/**
* Fatal log method to log fatal error messages.
* @param args
* @returns
*/
formatLogArguments(args) {
args = Array.prototype.slice.call(args);
var stackInfo = this.getStackInfo(1);
if (stackInfo) {
// get file path relative to project root
var calleeStr = `[${stackInfo.relativePath}] [${stackInfo.line}]`;
if (typeof args[0] === 'string') {
if (this.iscustomFormatEnabled)
args[0] = calleeStr + ' - ' + args[0];
}
else {
args.unshift(calleeStr);
}
}
return args;
}
;
/**
* Joins an array of arguments into a formatted string.
* @param args
* @returns
*/
joinArray(args) {
if (!Array.isArray(args) || args.length === 0)
return "";
return args.map((item, index) => {
if (index === 0)
return item;
if (index === args.length - 1)
return `\n${item}`;
return `[${item}]`;
}).join(' ');
}
/**
* Gets stack information for the specified stack index.
* @param stackindex
* @returns
*/
getStackInfo(stackindex) {
// get call stack, and analyze it
// get all file, method, and line numbers
var _a;
var _err = new Error();
var stacklist = (_a = (_err).stack) === null || _a === void 0 ? void 0 : _a.split('\n').slice(3);
// stack trace format:
// http://code.google.com/p/v8/wiki/javascriptstacktraceapi
// do not remove the regex expresses to outside of this method (due to a bug in node.js)
var stackreg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi;
var stackreg2 = /at\s+()(.*):(\d*):(\d*)/gi;
var s = stacklist[stackindex] || stacklist[0];
var sp = stackreg.exec(s) || stackreg2.exec(s);
if (sp && sp.length === 5) {
return {
method: sp[1],
relativePath: path.relative(this.PROJECT_ROOT, sp[2]),
line: sp[3],
pos: sp[4],
file: path.basename(sp[2]),
stack: stacklist.join('\n')
};
}
return undefined;
}
;
}
exports.LoggerService = LoggerService;
//# sourceMappingURL=logger.service.js.map