als-logger Documentation
Overview
als-logger
is a comprehensive logging utility for Node.js applications. It is designed to simplify logging across different levels (log, error, info) and handle uncaught exceptions and unhandled promise rejections. This package integrates with als-store
for efficient log management and supports automatic log file rotation based on age.
Installation
Install als-logger
using npm:
npm install als-logger
Constructor and Parameters
The Logger
class constructor accepts an optional options
object:
const Logger = require('als-logger');
const logger = new Logger(options);
Options
-
dirPath
(string): The directory path for storing log files. Defaults to a 'logs' directory at the parent level of the module. During initialization, the specified directory is created if it does not exist. -
maxAge
(number): Maximum age in milliseconds for a log file before it is rotated. Defaults to 24 hours (1000*60*60*24
). This is enforced dynamically when callinglogs
andlist
functions. -
dev
(boolean): Development mode flag. If set totrue
, andlogObj
is not specified, the standardconsole
object is used for logging. Defaults tofalse
. -
logObj
(object): Custom logging object used in development mode. Must implementlog
,error
, andinfo
methods. Ifdev
isfalse
, this parameter is irrelevant.
Validation
- The
options
object is validated to ensure correct types and values. - Throws errors for invalid parameter types or values.
exceptions()
The exceptions
method is designed to enhance the robustness of your application by handling two critical types of events: uncaught exceptions and unhandled promise rejections.
Functionality
When exceptions
is called, it sets up listeners for the following global process events:
-
uncaughtException
: This event is emitted when an exception bubbles all the way back to the event loop without being caught by any try/catch blocks. If not handled, these exceptions can cause the Node.js process to terminate. -
unhandledRejection
: This event is emitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop. Unhandled rejections can lead to unexpected behaviors and crashes.
Upon capturing either of these events, exceptions
uses the logger.error
method to log the details of the error. This ensures that all uncaught exceptions and unhandled rejections are not only caught but also recorded, providing valuable insights during debugging and post-mortem analysis.
Usage
To utilize this feature, simply call the exceptions
method after creating an instance of the logger:
const Logger = require('als-logger');
const logger = new Logger({/* options */});
logger.exceptions();
// Rest of your application code
Example
Here's how exceptions
can be implemented:
logger.exceptions();
// Simulating an uncaught exception
setTimeout(() => {
throw new Error('Simulated uncaught exception');
}, 1000);
// Simulating an unhandled rejection
new Promise((resolve, reject) => {
reject(new Error('Simulated unhandled rejection'));
});
In both cases, the logger captures the errors and logs them using logger.error
, ensuring that these critical issues are recorded for review and action.
Log Methods
There ara 3 log methods: log
,error
,info
. All those methods, use save
method for save report.
All log methods are asynchronous and return a Promise. They do not throw errors, but return them.
You don't have to await if it's not nessesary.
Example:
await logger.log('This is a standard log message');
await logger.error('This is an error message');
await logger.info('This is an info message');
await logger.save(['This is a standard log message'],'log')
await logger.save(['This is an error message'],'error');
await logger.save(['This is an info message'],'info');
list() and logs()
methods
list
method retrieves a list of log metadata.
const logMetadata = await logger.list();
Example for output:
[
{ date: 1702981524289, n: 0, type: 'log' },
{ date: 1702981524299, n: 0, type: 'error' },
{ date: 1702981524306, n: 0, type: 'info' }
]
logs
method retrieves the content of all log files.
const logContents = await logger.logs();
Example for output:
[
{ message: [ 'test' ], date: 1702981561578, n: 0, type: 'log' },
{ message: [ 'test' ], date: 1702981561588, n: 0, type: 'error' },
{ message: [ 'test' ], date: 1702981561594, n: 0, type: 'info' }
]
Example Usage
const Logger = require('als-logger');
const logger = new Logger({
dirPath: '/path/to/logs',
maxAge: 1000 * 60 * 60 * 24, // 24 hours
dev: false
});
logger.log('Application started');
logger.error(new Error('Unexpected error occurred'));
logger.info('Server listening on port 3000');
als-logger
is an ideal solution for applications requiring robust and manageable logging functionality, with the added benefit of automatic log rotation and exceptional condition handling.