This logger module provides a flexible and configurable logging mechanism for Node.js applications. It supports different log levels, custom log domains, and allows customization of the log output and format. It uses chalk
for colored console output and ensures that only one instance of the logger is created (singleton pattern).
import Logger, { LogLevel } from "./logger";
To get the singleton instance of the logger, use:
const logger = Logger.getInstance();
You can set options like log level, log domains, custom output function, and custom format function when getting the instance:
const logger = Logger.getInstance({
logLevel: LogLevel.DEBUG,
logDomains: ["APP", "DB"],
customOutput: (logMessage) => {
// Custom output logic
console.log(logMessage);
},
customFormat: (level, domain, message) => {
// Custom format logic
return {
level,
domain,
message,
timestamp: new Date().toISOString(),
};
},
});
The logger supports different log levels:
INFO
WARN
ERROR
DEBUG
You can log messages using the corresponding methods:
logger.info("APP", "This is an info message");
logger.warn("APP", "This is a warning message");
logger.error("APP", "This is an error message");
logger.debug("APP", "This is a debug message");
import Logger, { LogLevel } from "./logger";
const logger = Logger.getInstance({
logLevel: LogLevel.DEBUG,
logDomains: ["APP", "DB"],
});
logger.info("APP", "Application has started");
logger.warn("DB", "Database connection is slow");
logger.error("APP", "Unhandled exception occurred");
logger.debug("DB", "Query executed: SELECT * FROM users");
- Specifies the minimum level of messages to log.
- Type:
LogLevel
- Default:
LogLevel.INFO
- Specifies the domains to log messages for.
- Type:
string[]
- Default:
[]
(log all domains)
- Custom function for handling the log output.
- Type:
(logMessage: LogMessage, ...additionalArgs: any[]) => void
- Custom function for formatting log messages.
- Type:
(level: LogLevel, domain: LogDomain, message: string, ...additionalArgs: any[]) => LogMessage
export enum LogLevel {
NONE = "none",
INFO = "info",
WARN = "warn",
ERROR = "error",
DEBUG = "debug",
}
Returns the singleton instance of the logger, optionally configuring it with the provided options.
Resets the logger instance. Useful for testing purposes.
Logs a message with the specified level and domain.
Logs an info message.
Logs a warning message.
Logs an error message.
Logs a debug message.
The logger module includes tests to ensure its functionality. The tests cover creating singleton instances, respecting log levels and domains, and using custom output and format functions.