log4js-logging-error-library
v1.4.5
Published
This README would normally document whatever steps are necessary to get your application up and running.
Downloads
26
Readme
Log4Js-logging-error-library
Log4Js-logging-error-library
is a Node.js logging package built on top of log4js
to provide custom log appenders for MongoDB and MySQL. This library enables advanced logging capabilities, including structured logging, context-aware log entries, and email notifications for critical errors.
Installation
To install the package, use npm:
npm install log4js-logging-error-library
Usage
1. Setup Logging
To set up logging in your application, use the setupLogging
function. It configures the logging with MongoDB, MySQL appenders, and email notifications based on the provided connection strings and email configuration. If you don't want to set up MongoDB, MySQL, or email notifications, you can pass null
for those configurations.
const { setupLogging } = require('log4js-logging-error-library');
// MongoDB and MySQL connection strings and email configuration
const mongoConnectionString = 'mongodb://localhost:27017/mydb';
const mysqlConnectionString = 'mysql://root:password@localhost:3306/mydb';
const emailConfig = {
host: 'smtp.example.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '[email protected]',
pass: 'your-email-password',
},
from: '[email protected]',
to: '[email protected]',
};
// Set up logging
setupLogging(app, mongoConnectionString, mysqlConnectionString, emailConfig);
// If you don't want to set up MongoDB, MySQL, or email notifications, pass null
setupLogging(app, null, mysqlConnectionString, null); // Only MySQL logging
setupLogging(app, mongoConnectionString, null, null); // Only MongoDB logging
setupLogging(app, null, null, emailConfig); // Only email notifications
2. Logging Methods
The logger
object provides methods to log messages at different levels and handle criticality:
const { logger } = require('log4js-logging-error-library');
logger.error(err, req,'A error message','high');
logger.warn('A warning message', warn, req, 'medium');
logger.debug('Debugging information', debug, req, 'low');
logger.info('Informational message',info, req);
logger.trace('Tracing information', tracing, req);
logger.fatal('Fatal error message', fatal, req);
3. Middleware Integration
Use the captureRequestDetails
middleware to capture request details and add them to the logging context:
const { captureRequestDetails } = require('log4js-logging-error-library');
router.get('/path-to-api', captureRequestDetails, Controller.function);
4. Fetch Logs
You can fetch logs from MongoDB or MySQL using the following methods:
const { getMongoLogs, getMySQLLogs } = require('log4js-logging-error-library');
async function fetchLogs() {
const mongoLogs = await getMongoLogs(mongoConnectionString);
const mysqlLogs = await getMySQLLogs(mysqlConnectionString);
console.log('MongoDB Logs:', mongoLogs);
console.log('MySQL Logs:', mysqlLogs);
}
Components
index.js
- Purpose: The main entry point of the package. It configures logging using
log4js
, sets up custom appenders, and provides utility functions for logging, fetching logs, and sending emails for critical errors. - Functions:
setupLogging(app, mongoConnectionString, mysqlConnectionString, emailConfig)
: Configureslog4js
with MongoDB, MySQL appenders, and email notifications.getMongoLogs(mongoConnectionString)
: Fetches logs from MongoDB.getMySQLLogs(mysqlConnectionString)
: Fetches logs from MySQL.logger
: Provides various logging methods (error
,warn
,debug
,info
,trace
,fatal
).
log4js.json
The log4js.json
file contains the configuration for log4js
appenders and categories.
Appenders
appFile
:- Type:
dateFile
- Purpose: Writes logs to a file, creating a new file each day.
- Options:
filename
: Path to the log file.pattern
: File naming pattern with date.layout
: Specifies the log format.compress
: Compress old log files.keepFileExt
: Keep file extension when compressing.daysToKeep
: Number of days to keep old logs.maxLogSize
: Maximum size of a log file before rotating.
- Type:
console
:- Type:
console
- Purpose: Logs messages to the console.
- Options:
layout
: Specifies the log format for console output.
- Type:
Categories
default
:- Append:
appFile
,console
- Level:
all
- Purpose: Default logging category that uses both file and console appenders, with logging level set to
all
.
- Append:
log4js-mongodb-appender.js
- Purpose: Custom appender for logging to MongoDB.
- Key Functions:
mongodbAppender(layout, config)
: Defines how log events are processed and saved to MongoDB.configure(config, layouts)
: Configures the MongoDB appender with the provided settings.
log4js-mysql-appender.js
- Purpose: Custom appender for logging to MySQL.
- Key Functions:
mysqlAppender(layout, config)
: Defines how log events are processed and saved to MySQL.configure(config, layouts)
: Configures the MySQL appender with the provided settings.
appErrorLog.model.js
- Purpose: Defines the Mongoose schema and model for MongoDB error logs.
- Schema Fields:
dateTime
: Date and time of the log entry.level
: Log level (e.g., error, warn).module
: Module where the log originated.methodName
: Method name where the log originated.callStack
: Stack trace of the log entry.message
: log message.- `functionName: Function Name.
- `fileLocation: Location of the function.
loggedInUserId
: ID of the logged-in user.apiEndPoint
: API endpoint associated with the log.parameterValues
: Parameters associated with the log.
captureRequestDetails.js
- Purpose: Middleware to capture request details and add them to the logging context.
- Details Captured:
apiEndPoint
: The endpoint being accessed.loggedInUserId
: ID of the logged-in user.parameterValues
: Parameters from the request.module
: Module being accessed.methodName
: HTTP method of the request.
Email Notifications
The package can send email notifications for critical errors. The email configuration should be passed to the setupLogging
function. If the criticality is set to high
, an email notification will be sent.
Example
In your app.js
, set up the email configuration along with MongoDB and MySQL configurations. Pass null
for configurations you don't want to set up:
const express = require('express');
const app = express();
const { setupLogging } = require('log4js-logging-error-library');
const mongoConnectionString = 'mongodb://localhost:27017/mydb';
const mysqlConnectionString = 'mysql://root:password@localhost:3306/mydb';
const emailConfig = {
host: 'smtp.example.com',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: '[email protected]',
pass: 'your-email-password',
},
from: '[email protected]',
to: '[email protected]',
};
// Full setup
setupLogging(app, mongoConnectionString, mysqlConnectionString, emailConfig);
// Only MySQL logging
setupLogging(app, null, mysqlConnectionString, null);
// Only MongoDB logging
setupLogging(app, mongoConnectionString, null, null);
// Only email notifications
setupLogging(app, null, null, emailConfig);
// Rest of your app setup...
By following these steps, you can set up and use Log4Js-logging-error-library
to log errors, warnings, and other messages to MongoDB, MySQL, and send email notifications for critical errors. If you do not need certain setups like MongoDB, MySQL, or email, you can simply pass null
for those configurations.