JavaScript

How to Create API to View Logs in Node.js?

APIs” can be utilized to invoke web services, operating systems, etc. The logs are assistive to analyze the behavior of the multiple APIs. This logging is of great aid in monitoring and debugging the applications becoming complicated. Moreover, the log files help record the activities, limitations, and abnormalities that are faced in the application or a computer system.

Contents Overview

What is an API?

An “API” is an abbreviated form of “Application Programming Interface” that corresponds to a set of protocols and tools to build software applications. Also, API specifies the way for the software applications to enable communication with each other.

How to Create API to View Logs in Node.js?

An API can be created by installing the packages and the logs can be viewed via the following approaches:

  • Winston” Logging Framework.
  • log4js” Logging Framework.

Prerequisites For Creating API to View Logs

The following are the prerequisites that need to be considered before creating an API to view logs:

Step 1: Initialize the Project
First, initialize the project with default values via the “-y” flag using the below command:

npm init -y

Step 2: Install the Dependencies
Now, install the “express” and “winston” packages to create an API via the following cmdlet:

npm install express winston

Here, both packages are installed simultaneously.

Now, install the following package to make use of the “log4js” logging framework:

npm install log4js

Before proceeding to the examples, create a “template.js” file to contain the code for creating API and viewing logs.

What is the Winston Logging Framework?

Winston” is one of the best Node.js logging options, as it is flexible and open-source. It can be used to transmit and save logs in multiple ways such as files, databases, consoles, etc. Also, it has multiple log formats.

Log Levels in Winston

There are the following six log levels in Winston:

logger.error('error');
logger.warn('warn');
logger.info('info');
logger.verbose('verbose');
logger.debug('debug');
logger.silly('silly');

Approach 1: Create API to View/Display Logs in Node.js Utilizing the “Winston” Logging Framework

This example uses this package to create an API and specify a route to display the logs on the server as well as on the file:

const express = require('express');
const include = require('winston');
const app = express();
const logger = include.createLogger({
    level: 'info',
    format: include.format.json(),
    transports: [
        new include.transports.Console(),
        new include.transports.File({
            filename: 'sample.log'
  })
  ]
});
app.get('/logs', (req, res) => {
    logger.query({ order: 'desc', limit: 100 },
        (err, results) => {
            if (err) {
               res.status(500).send({
                error: 'Error fetching logs'
                });
            } else {
               res.send(results);
            }
 });
});
app.listen(3000, () => {
    logger.info('Server has started on port 3000');
});

In this block of code:

  • First, include the installed “express” and “winston” packages and create an express application.
  • In the next step, create a Winston logger instance using the “createLogger()” method.
  • This logger basically has two transport types i.e., logging to the console and logging to the file named “sample.log”.
  • Now, use Winston to log detailed information.
  • Also, specify the API endpoint and include a route i.e., “/logs” to view the logs and return them as a JSON response from the local server.
  • This API basically fetches the latest 100 logs(specified in limits) and retrieves them as a JSON response upon the “/logs” route being fetched.
  • Note: The logs are repeated upon the code compilation.
  • Moreover, the loggers can also be customized to log more detailed information or write logs to multiple files or databases.
  • If an error is faced, send an error response and if successful, send the log entries as a response.
  • Lastly, start the server and log the message when ready.

Bonus Tip: Specify the “localhost:” followed by the same route as specified in the code to streamline the viewing of logs on the local server.

Output
Execute the following command in the terminal to view the logs on both the local server and on the file:

node template.js

Output

Here, as seen, the logs are displayed on the local server by specifying the same route and the specified port.

“sample.log” File

Also, the logs are saved in the custom-made file in the workspace.

What is the “log4js” Logging Framework?

This particular framework is inspired by the Apache “log4j” library. This framework enables the developers to manage the outcomes, format log messages, categorize logs into different levels, etc.

Log Levels in “log4js”

There are the following six levels in “log4js”:

logger.trace('TRACE message.');
logger.debug('DEBUG message.');
logger.info('INFO message.');
logger.warn('WARN message.');
logger.error('ERROR message.');
logger.fatal('FATAL message.');

Approach 2: Create API to View/Display Logs in Node.js Using the “log4js” Logging Framework

This approach uses this particular logging framework to likewise write logs to a custom file and then create an endpoint for the API to display the logs, which reads logs from a file and retrieves them as a JSON response:

const express = require("express");
const app = express();
const include = require("log4js");
const include2 = require("fs");
include.configure({
   appenders: {
     file: {
       type: "file",
       filename: "logfile.log"
        }
    },
    categories: {
      default: {
        appenders:
           ["file"], level: "info"
        }
    },
});
const logger = include.getLogger();
app.get("/logs", (req, res) => {
    const logs = include2.readFileSync("logfile.log", "utf8");
    res.json({ logs: logs });
});
logger.info("Info message");
logger.warn("Warning message");
logger.error("Error message");
app.listen(3000, () => {
    console.log("Server has started on port 3000");
});

The code explanation is as follows:

  • First, import the required “express” and “log4js” packages, respectively.
  • After that, configure “log4js” to write logs to a file named “logfile.log”.
  • Now, apply the “getLogger()” method to create a logger and similarly, create a route i.e., “/logs” to view the logs on the local server as well.
  • Read the logs from the created file and return these logs as a JSON response.
  • Also, specify the logging statements to be logged on both platforms.
  • Finally, start the server on the target port to display the logs on the local server.

Output
Executing the following command creates a log file comprising the logs in the form of logging statements:

node template.js

Here, it is evident that the logs are displayed on the local server by specifying the correct route.

Note: These logs are displayed repeatedly as the code is compiled multiple times.

Logfile.log File
Below is the custom file in which the same logs are saved as well:

Conclusion

An API can be created by installing the “express” and “winston” packages and the logs can be viewed by creating a Winston logger instance and specifying an API route. This can be achieved via the “Winston” or the “log4js” logging frameworks. Both these approaches can be utilized to view the logs on the local server as well as write logs to a custom file.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.