For enquiries call:

Phone

+1-469-442-0620

Easter Sale-mobile

HomeBlogWeb DevelopmentLogging in Node.js - Getting Started & Best Practices

Logging in Node.js - Getting Started & Best Practices

Published
05th Sep, 2023
Views
view count loader
Read it in
10 Mins
In this article
    Logging in Node.js - Getting Started & Best Practices

    Node.js is a JavaScript runtime environment that is built on the Chrome V8 JavaScript engine. For running any application in JavaScript node.js helps to execute your application. We also know that node JavaScript is an open-source server environment and it can be run on various platforms (Windows, Linux, Unix, Mac OS X, etc.). node.js generates the dynamic content, and also can do various operations to create, open, and write files on the server using the node.js file. 

    Logging is an important part of understanding the complete application life cycle of the node.js application. From start to debugging then adding new features, logs provide support by analyzing the data, and also we can resolve the bugs much more easily and also detecting the errors at a very early stage. node.js uses logs are warn, error, info, and debug. Logging means recording the information about the application during the runtime. 

    Before you begin working with NodeJS, you should have a thorough understanding of how to work and create logs in the node.js logger. In this node.js blog, we will look at some of the best practices for JS loggers as well as how to improve node.js performance. If you want to improve your skills and practice more in node. js. I recommend that you take this course Node.js course duration. 

    Getting Started with Node.js Logging 

    Node.js Logger is one of the most essential and important steps for a developer to work in a node.js logger.  Using the js log, developers get help with what it is that their code is actually doing, and can help developers save the time of debugging works. One of the biggest advantage of using a node.js log is that it helps you to understand the source code working. Today developers likes to use the runtime’s console methods such as console.log(), which helps to debug the error in the source code. In this way, it helps the developers to understand the application easily. 

    For Example, there is an issues in the server section of code, then log will point to the particular issues, and helps you to identify arise in  the problem. 

    There are several ways to log into node.js logger: 

    Console.log: The original logging method is console.log, which writes a function in the debugging console as a message. 

    console.log(level, message) 

    Debug Module: The benefit of debugging is that you get to use a lot of different packages. Furthermore, the best frameworks will show you how to attach a log to the middleware. Middleware is simply something that will be added to the request pipeline. There are various methods for configuring logging middleware. 

    • Application:  

    const app =express(); 
    const loggingMiddleware = require('my-logging-middleware'); 
    app.use(loggingMiddleware) 
    • Winston Package:  It includes storage options, different log levels and queries and a profiler. 

    const app =express(); 
    const winston = require('winston'); 
    const consoleTransport = new winston.transports.Console(); 
    const myWinstonOptions = { 
        transports: [consoleTransport] 
    } 
     
    const logger = new winston.createLogger(myWinstonOptions); 
    function logRequest(reqresnext){ 
        logger.info(req.url) 
        next() 
    } 
    app.use(logRequest); 
    function logError(errreqresnext) { 
        logger.error(err) 
        next() 
    } 
    app.use(logError); 

    When to Log?

    Deciding when to use node.js logging is very important. In node.js logs are done purposefully. There are a few categories of logging to be considered, and also it has its own purpose. 

    Here are common levels of logging in node.js 

    1. Error: important events that will cause the program execution to fail 
    2. Warncrucial events that should be noticed to prevent fails 
    3. Infoimportant events that detail a completed task 
    4. Debugmostly used by developers 

    These logging levels are present in Winston are those available in npm (node package manager). 

    Node.js console.log and console.error 

    console.log 

    Node.js provides a console module which has tons of very useful ways to interact with CLI. It is basically the same as the console object in the browser. It is the most basic and most used method in console.log(), which prints the string you pass to it to the console. 

    You can also pass the multiple variables to a console.log and also can use to clear the console using the console.clear(). 

    The method use to log in to console.log. It has variants like a console. error, console.info, and console. warn 

    console.error

    The console. error() from the console class of Node.js is used to display an error message on the console. It prints to stderr with a newline. 

    Syntax:  console.error([data][, …args]) 

    Parameter: This function can contain multiple arguments. The first argument is used for the primary message and other arguments are used for values. 

    Return Value: This function lets you return an error message. 

    Program: 

    // store number to variable 
    num = 20; 
    if (num < 100) { 
        console.log("Enter number greater than 100"); 
    } 
    else { 
        console.error("Correct choice"); 
    } 

    The Debug Module 

    Debug module has a great feature that allows you to enable or disable debug functions in a group. 

    debug('app:meta')('config loaded'); 
    debug('app:database')('querying db...'); 
    debug('app:database')('got results!', results); 

    Enable debug functions in Node.js by passing the process name i.e. the DEBUG environment variable.  

    DBEUG = 'app:database' node app.js; 

    If you want to master front-end and back-end in web technologies then check out this course master full stack developer. 

    Node.js Logging Packages with Winston  

    Winston is a very popular library for node.js logging. Winston is one of the most download logging and It's around more than 4,000,000 weekly. It executes your application activities and generates useful information in the log file or in the database. Later on, you can check the logs generated by your apps. Using Winston you can send and save your logs in different ways, such as through emails, and databases.  

    Winston is intended to be a straightforward and universal logging library that supports multiple transports. A transport is essentially a log storage device. Multiple transports (see: Transports ) can be configured at different levels on each Winston logger (see: Logging levels ). The goal of Winston is to decouple parts of the logging process in order to make it more flexible and extensible. 

    In this section, we will explain how to install, set up and use the logger in a node.js app. Before starting with this example, make ensure that you have installed the recent version of node.js. 

    Getting started with Winston  

    Winston is available in the npm package, you can install it through the command line terminal by using: npm install winston. After that, import it into your Node.js application 

    const winston = require(‘ winston’); 

    It provides by default logger. Using this logger you can called the Winston module. 

    const winston = require('winston'); 
    const logger = winston.createLogger({ 
        level: 'info', 
        format: winston.format.json(), 
        transports: [new winston.transports.Console()], 
    }); 
    console.log(logger); 

    The following parameters are accepted by loggers: 

    NameDefaultDescription
    Level‘info’Log only if info.level is less than or equal to
    levelsWinston.config.npm.levelsLevels representing log priorities
    formatWinston.format.jsonFormatting for info messages.
    exitOnErrorTrueIf false, handled exceptions will not cause process.exit
    silentFalseIf true, all logs are suppressed

    You can also start logging through the methods on the logger object: 

    logger.info('Information message'); 
    logger.error('Error message'); 
    logger.warn('Warning message'); 

    Log Levels in Winston 

    In Winston, logging levels follow the severity ordering specified by RFC5424: severity is assumed to be numerically ascending from most important to least important. 

    Each level is assigned an integer priority. The higher the priority, the more important the message, and the lower the corresponding integer priority. For example, as specified in RFC5424, syslog levels are prioritized from 0 to 7. (highest to lowest). 

    Similarly, logging levels in npm are numbered from 0 to 6 (highest to lowest): 

    { 
        error: 0, 
        warn: 1, 
        info: 2, 
        http: 3, 
        verbose: 4, 
        debug: 5, 
        silly: 6 
    } 

    Best Practices for Node.js Logging Library 

    1. Add Timestamp 

    JavaScript Date object is used to handle the date and time in the node.js app. It is available to use by default. The console.timeStamp() is an in-built API of the console module which does not display anything unless used in the inspector. 

    1. Syntax: console.timeStamp([label]) 
    2. Parameters: This function accepts a single parameter. 
    3. Return Value: It prints the timestamp at the call in the inspector. 

    Example: 

    const express = require('express'); 
    const pino = require('pino'); 
    const expressPino = require('express-pino-logger'); 
    const logger = pino({level: process.env.LOG_LEVEL || 'info'}); 
    cosnt expressLogger = expressPino({ logger }); 
    const PORT = process.env.PORT || 3000; 
    const app = express(); 
    app.use(expressLogger); 
    app.get('/', (reqres=> { 
        logger.debug('calling res.send'); 
        res.send('Hello World'); 
    }); 
    app.listen(PORT, () => { 
        logger.info('Server running on port %d', PORT); 
    }); 

    Output:

    2. Include Tags in Your Logs 

    while working with complex application that have many components, like tags in your logs, lets you to filter out messages you don’t want to focus. Tags provides you benefit for searching the log files manually with grep ( it is a command line tools for searching the text data sets). Tags are key-value pair string that are indexed and searchable. 

    3. Use Papertrail for Log Aggregation

    Papertrail help you to centralize your log in the cloud. You can easily use the Papertrail to configure centralized logging from Node.js apps. IT can handle log from the Node.js app using the text log file, or integrating with the logging library, such as Winston or bunyan. It also provides instant log visibility. 

    It can setup in less than a minute, and provides useful features such as fast search, flexible system groups, team-wide access and monitoring. Papertrail allows you to consolidate all your Logs with syslog, and other application and database logs. It gives you easy access to syslog, text logs - all in one location. 

    4. Use a Node.js Logging Library 

    There are 5 popular Node.js logging libraries available on NPM . All of them are downloaded by many users around the world. So they are more popular. Let’s get started !. 

    • Winston: - it is a logging library. It is designed to be simple and enables logging with support for multiple transports.  
    • Bunyan:- This is also another famous Node.js logging library. It is used defines the simple and fast JSON logging library for Node.js services. 

    It advocates that logs should be used in JSON format only. 

    • Pino:- It is a relatively Node.js logging library that marks itself “ very low overhead Nodejs Logger”. It’s attributes are asynchronous logging which leads to fast performance. 
    • Log Level:-  It can be used in both Node.js and browser. It is “minimal lightweight logging for JavaScript”. It also seems to be very easy and convenient to used. 
    • Npmlog:- It performs the logging for npm. It also supports the custom levels and the color output. 

    5. Use the Correct Log Levels 

    These are some of the most common log levels that are used. 

    1. FATAL: this logging at this level signifies the end of the program. 
    2. ERROR: it represents an error condition in the system that occurs to halt a certain operation, but not the overall the system.  
    3. WARN: it denotes runtime warnings that are undesirable or unusual, but not a errors. For example backup data source when the primary source is not available. 
    4. INFO: in this level info messages are purely informative.  
    5. DEBUG:  used to represent diagnostic information that may be needed for troubleshooting. 

    6. Use Structured Logging 

    While writing how to log your messages look, should be your first priority to make entries more easy to read for both the machines and humans. 

    It is also important to use a structured format that are easy to parse for machines. This will allows automating processing the logs(like alerting messages). Having human-readable log entries will impact more to developers. 

    7. Write Descriptive Messages 

    Log entries should describe more precisely regarding the events. Each message should be unique to the situation and should be clearly explain the event that are occurred at some point. Log entries should help to understand what happened, so it’s important to get this aspect of logging right! 

    8. Avoid Logging Sensitive Information

    It is critical not to include sensitive information in your logs. Bank account information, address, password, credit card, and debit card. Log messages are stored in plain text; this data will be exposed and fall into the hands of the wrong people. You should also ensure data should not exposed. 

    For example credit card details or debit card should only be seen by the billing parts of your system. Still this is not fully useful, but can use a blocklist to prevent specific fields for making it into the logs. 

    9. Automatically Log Uncaught Exceptions and Unhandled Promise Rejections 

    When you face uncaught exceptions or unhandled promise rejections, it is always good practice to crash the program. It is also very important to log the details of the uncaught exception or unhandled promise rejection before exiting. it helps you to handle both the situations. 

    Looking to master Python? Join our online course for python and unlock your coding potential. Affordable fees, expert guidance, and a unique learning experience await you. Don't miss out, enroll today!

    Conclusion 

    In this blog, we learned how to debug the application and what the best practices are for logging the node. Js. While working with JavaScript and logging your first line of code i.e. console.log is quick, but when it comes to production, there are a lot of things that you should keep in mind about logging. This blog gives you introduction about the logs, how to use, when to use and what should avoid while working with logs in node.js. It doesn’t contain everything you need to know. 

    So, if you want to learn more about logging in node.js using a practical example. Then go through this course knowledgeHut’s Node.js course duration. 

    Thanks for Reading! 

    Frequently Asked Questions (FAQs)

    1How do I access the console log in terminal?

    You can go to terminal window and Debug console. Or you can press F5 for Debugging or Ctrl-F5 for Run. 

    2Where are Nodejs logs?

    This is the default location of the logs in the directory i.e. directory named _logs inside the npm cache.  

    3Does console log slow down node?

    console.log is an asynchronous and non-blocking, so it will not slow down your application with too much except one tick for the function call. 

    4What is console log in JavaScript?

    The console.log() methods is just used to output a message to the web console and this feature is available in web workers. 

    Profile

    Prateek Singh

    Blog Author

    Prateek Singh is a highly-skilled at building front-end interfaces. He loves JavaScript ecosystem and have designed & developed multiple products in his career. He has worked in Fintech, E-Commerce, Healthcare & Semi-conductor industries. Prateek enjoys conversation on Programming, Sports, Art, and Space Science. He is fascinated about origin of the universe, the existential reality & the design around us. 

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon