Explore the Powerful Capabilities of ionicons-logger for Enhanced Application Logging

Introduction to ionicons-logger

The ionicons-logger library offers a comprehensive and efficient logging solution designed to enhance your application’s logging functionalities with ease. It boasts dozens of useful APIs to cater to every logging need.

API Explanations and Code Snippets

Basic Configuration

Initialize the logger with a basic configuration.

 const logger = require('ionicons-logger');
 logger.init({ level: 'info' });

Logging Messages

Log different levels of messages.

 logger.debug('This is a debug message');
 logger.info('This is an info message');
 logger.warn('This is a warning message');
 logger.error('This is an error message');

Custom Transports

Add and configure custom transports.

 const customTransport = new logger.Transport({
   type: 'file',
   filename: 'app.log'
 });
 
 logger.addTransport(customTransport);

Formatting Logs

Format log messages as per your requirements.

 logger.format = (level, message) => {
  return `[${new Date().toISOString()}] [${level}] ${message}`;
 };

Handling Exceptions

Setup exception handling to capture uncaught exceptions.

 process.on('uncaughtException', (err) => {
   logger.error('Uncaught Exception:', err);
 });

Log Rotation

Enable log rotation to manage log file sizes.

 customTransport.on('rotate', (oldFilename, newFilename) => {
   logger.info(`Log file rotated from ${oldFilename} to ${newFilename}`);
 });

Application Example

Here is an example application showcasing the various APIs of ionicons-logger.

 const express = require('express');
 const app = express();
 const logger = require('ionicons-logger');

 // Initialize logger
 logger.init({ level: 'info' });

 // Custom Transport
 const customTransport = new logger.Transport({
   type: 'file',
   filename: 'app.log'
 });
 logger.addTransport(customTransport);

 // Middleware for logging requests
 app.use((req, res, next) => {
   logger.info(`Received ${req.method} request for ${req.url}`);
   next();
 });

 app.get('/', (req, res) => {
   res.send('Hello World!');
   logger.info('Sent response: Hello World!');
 });

 // Error handling
 app.use((err, req, res, next) => {
   logger.error('Error encountered:', err);
   res.status(500).send('Internal Server Error');
 });

 // Start server
 app.listen(3000, () => {
   logger.info('Server is running on port 3000');
 });

Hash

Leave a Reply

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