57 lines
1.7 KiB
JavaScript
57 lines
1.7 KiB
JavaScript
class Logger {
|
|
constructor(logging = true, logLevel = 'debug', nameModule = 'N/A') {
|
|
this.logging = logging; // Boolean flag to enable/disable logging
|
|
this.logLevel = logLevel; // Default log level: 'debug', 'info', 'warn', 'error'
|
|
this.levels = ['debug', 'info', 'warn', 'error']; // Log levels in order of severity
|
|
this.nameModule = nameModule; // Name of the module that uses the logger
|
|
}
|
|
|
|
// Helper function to check if a log message should be displayed based on current log level
|
|
shouldLog(level) {
|
|
return this.levels.indexOf(level) >= this.levels.indexOf(this.logLevel);
|
|
}
|
|
|
|
// Log a debug message
|
|
debug(message) {
|
|
if (this.logging && this.shouldLog('debug')) {
|
|
console.debug(`[DEBUG] -> ${this.nameModule}: ${message}`);
|
|
}
|
|
}
|
|
|
|
// Log an info message
|
|
info(message) {
|
|
if (this.logging && this.shouldLog('info')) {
|
|
console.info(`[INFO] -> ${this.nameModule}: ${message}`);
|
|
}
|
|
}
|
|
|
|
// Log a warning message
|
|
warn(message) {
|
|
if (this.logging && this.shouldLog('warn')) {
|
|
console.warn(`[WARN] -> ${this.nameModule}: ${message}`);
|
|
}
|
|
}
|
|
|
|
// Log an error message
|
|
error(message) {
|
|
if (this.logging && this.shouldLog('error')) {
|
|
console.error(`[ERROR] -> ${this.nameModule}: ${message}`);
|
|
}
|
|
}
|
|
|
|
// Set the log level dynamically
|
|
setLogLevel(level) {
|
|
if (this.levels.includes(level)) {
|
|
this.logLevel = level;
|
|
} else {
|
|
console.error(`[ERROR ${nameModule}]: Invalid log level: ${level}`);
|
|
}
|
|
}
|
|
|
|
// Toggle the logging on or off
|
|
toggleLogging() {
|
|
this.logging = !this.logging;
|
|
}
|
|
}
|
|
|
|
module.exports = Logger; |