@node-dlc/logger
Version:
107 lines • 3.46 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Logger = void 0;
/* eslint-disable @typescript-eslint/no-explicit-any */
const util_1 = __importDefault(require("util"));
const log_level_1 = require("./log-level");
const util_2 = require("./util");
class Logger {
constructor(area = '', instance) {
this._root = this;
this.area = area;
this.instance = instance;
this._level = log_level_1.LogLevel.Info;
this._transports = [];
// create bound methods so consumer doesnt lose context
this.trace = this.trace.bind(this);
this.debug = this.debug.bind(this);
this.info = this.info.bind(this);
this.warn = this.warn.bind(this);
this.error = this.error.bind(this);
}
/**
* Configured log-level
*/
get level() {
return this._root._level;
}
set level(value) {
this._root._level = value;
}
/**
* Gets the available transports
*/
get transports() {
return this._root._transports;
}
/**
* Constructs a sub-logger under the current parent
* @param area optional area, if not provided it inherits from the parent
* @param instance optional instance, if not provied it inherits from the parent
*/
sub(area, instance) {
const logger = new Logger(area || this.area, instance || this.instance);
logger._root = this._root;
return logger;
}
/**
* Write a trace message
*/
trace(...args) {
this._log(log_level_1.LogLevel.Trace, this.area, this.instance, args);
}
/**
* Write a debug message
* @param args variadic arguments
*/
debug(...args) {
this._log(log_level_1.LogLevel.Debug, this.area, this.instance, args);
}
/**
* Write an info message
* @param args variadic arguments
*/
info(...args) {
this._log(log_level_1.LogLevel.Info, this.area, this.instance, args);
}
/**
* Write a warning message
* @param args variadic arguments
*/
warn(...args) {
this._log(log_level_1.LogLevel.Warn, this.area, this.instance, args);
}
/**
* Write an error message
* @param args variadic arguments
*/
error(...args) {
this._log(log_level_1.LogLevel.Error, this.area, this.instance, args);
}
/////////////////////////////
_log(level, area, instance, args) {
if (!(0, util_2.shouldLog)(this.level, level))
return;
const formattedMsg = this._format(level, area, instance, args);
this._write(formattedMsg);
}
_format(level, area, instance, args) {
const date = new Date().toISOString();
const formattedArea = area ? ' ' + area : '';
const instanceFmt = instance ? ' ' + instance : '';
// convert buffers to hex encodings
args = args.map((arg) => Buffer.isBuffer(arg) ? arg.toString('hex') : arg);
const msg = util_1.default.format(args[0], ...args.slice(1));
return `${date} [${level}]${formattedArea}${instanceFmt}: ${msg}`;
}
_write(msg) {
for (const transport of this._root.transports) {
transport.write(msg);
}
}
}
exports.Logger = Logger;
//# sourceMappingURL=logger.js.map