als-logger
is a flexible and powerful logging utility for Node.js applications. It supports customizable log formats, file management, error handling, and much more.
-
Customizable Logging Levels: Easily log different message types like
log
,warn
, anderror
. - File Management: Automatically rotates log files and removes old entries based on age.
- Error Handling: Captures uncaught exceptions and unhandled promise rejections.
- Retry Mechanism: Retries log writes with configurable attempts and wait times.
Install the package via npm:
npm install als-logger
Create an instance of the Logger
and start logging messages.
const Logger = require('als-logger');
const logger = new Logger('/path/to/logs', { maxdays: 5, dev: true });
// Log messages of various types
logger.log('This is a log message.');
logger.warn('This is a warning.');
logger.error('This is an error.');
Enable automatic logging of uncaught exceptions and unhandled promise rejections by setting the exceptions
option to true
.
const logger = new Logger('/path/to/logs', { exceptions: true });
Use the logs
method to retrieve and sort log entries.
// Retrieve the last 10 logs in ascending order
const { reports, errors } = await logger.logs(10, true);
console.log(reports);
if (errors.length > 0) console.error(errors);
-
dirPath
(string): Path to the directory where log files will be stored. Defaults to__dirname
. -
maxdays
(number): The maximum number of days to retain logs. Older logs will be automatically removed. Defaults to0
(no removal). -
attempts
(number): Number of attempts for retrying a failed log write. Defaults to3
. -
waitTime
(number): Time in milliseconds between retry attempts. Defaults to1000
. -
timeout
(number): Maximum time in milliseconds for writing a log entry. Defaults to5000
. -
exceptions
(boolean): Whether to capture and log uncaught exceptions and unhandled promise rejections. Defaults tofalse
. -
dev
(boolean): Iftrue
, outputs log messages to the console. Defaults tofalse
. -
loggerError
(function): A custom error handler function for logging errors.