Comprehensive Guide to log4js-logger for Efficient Logging in Node.js Applications

Introduction to log4js-logger

log4js-logger is a powerful and highly versatile logging library for Node.js applications, inspired by the log4j framework for Java. It allows developers to create configurable logging with different appenders, levels, and categories.

Getting Started

To get started with log4js-logger, you need to install it using npm:

npm install log4js

Basic Configuration

You can configure log4js with a simple JSON or JavaScript object. Here is a basic configuration example:


const log4js = require('log4js');

log4js.configure({
  appenders: {
    out: { type: 'stdout' },
    app: { type: 'file', filename: 'application.log' }
  },
  categories: {
    default: { appenders: ['out', 'app'], level: 'debug' }
  }
});

const logger = log4js.getLogger();
logger.debug("Some debug messages");

Custom Levels

Apart from the standard log levels, you can also define custom levels:


log4js.addLevel('custom', { value: 15000, colour: 'yellow' });

const customLogger = log4js.getLogger('customLogger');
customLogger.level = 'custom';
customLogger.custom("This is a custom log message");

Using Different Appenders

log4js-logger supports various appenders such as file, dateFile, console, etc. Here are some examples:

File Appender


log4js.configure({
  appenders: {
    file: { type: 'file', filename: 'app.log' }
  },
  categories: {
    default: { appenders: ['file'], level: 'info' }
  }
});
const fileLogger = log4js.getLogger('fileLogger');
fileLogger.info("This is an info message in a file");

Date File Appender


log4js.configure({
  appenders: {
    dateFile: { type: 'dateFile', filename: 'app-date.log', pattern: '.yyyy-MM-dd' }
  },
  categories: {
    default: { appenders: ['dateFile'], level: 'warn' }
  }
});
const dateFileLogger = log4js.getLogger('dateFileLogger');
dateFileLogger.warn("This is a warning message in a date-based file");

SMTP Appender


log4js.configure({
  appenders: {
    email: { 
      type: 'smtp', 
      recipients: 'admin@example.com', 
      sender: 'no-reply@example.com', 
      subject: 'Error Log Alert',
      smtp: {
        host: 'smtp.example.com',
        port: 587,
        auth: {
          user: 'user',
          pass: 'password'
        }
      }
    }
  },
  categories: {
    default: { appenders: ['email'], level: 'error' }
  }
});
const emailLogger = log4js.getLogger('emailLogger');
emailLogger.error("This is an error message sent via email");

Real-world Application Example

Let’s create a simple Express application that utilizes log4js-logger to log different levels of messages to both console and a file:


const express = require('express');
const log4js = require('log4js');

log4js.configure({
  appenders: {
    console: { type: 'console' },
    file: { type: 'file', filename: 'app.log' }
  },
  categories: {
    default: { appenders: ['console', 'file'], level: 'debug' }
  }
});

const app = express();
const logger = log4js.getLogger();

app.use((req, res, next) => {
  logger.info(`${req.method} ${req.url}`);
  next();
});

app.get('/', (req, res) => {
  logger.debug('Root path accessed');
  res.send('Hello, world!');
});

app.listen(3000, () => {
  logger.info('Server started on port 3000');
});

Conclusion

In conclusion, log4js-logger is a robust logging library for Node.js that offers an extensive range of configuration options and appenders to suit any logging requirement. By mastering this tool, developers can significantly improve the maintainability and debuggability of their applications.

Happy Logging!

Hash: c2c3365077646412a9ee92bd74daa5602c4ed8da007dd0fcd9a0ce8cf82eaac5

Leave a Reply

Your email address will not be published. Required fields are marked *