npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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): Configures log4js 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.
  • console:

    • Type: console
    • Purpose: Logs messages to the console.
    • Options:
      • layout: Specifies the log format for console output.

Categories

  • default:
    • Append: appFile, console
    • Level: all
    • Purpose: Default logging category that uses both file and console appenders, with logging level set to all.

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.