Skip to content
Related Articles

Related Articles

Improve Article
Logging in Node.js
  • Last Updated : 01 Apr, 2021

Node.js is a JavaScript runtime that’s built on Chrome’s V8 JavaScript engine and its run-time environment includes everything which we’d like to execute a program written in JavaScript. Logging is an essential part of understanding the complete application life cycle of the Node.js program. From starting to debugging and adding new features, logs provide support by analyzing the data, and we can resolve bugs much easier and quicker by detecting errors as soon as they occur. There are common levels of logging in Node.js: error, warn, info, debug. Logging involves recording information about the application’s runtime behavior in a more persistent manner.

There are following ways to log in Node.js:

console.log: The original method of logging is console.log which is a function that writes a message to log on the debugging console, but you have little control over it where things log from outside the code.

Syntax:

console.log(level, message)

Debug module: The advantage of using debug is that a lot of packages use it. You can turn it on to urge additional information on what’s happening in web middleware like Express and Koa when your back-end gets an internet request. The good frameworks will offer you how to attach logging middleware, but you would possibly not get all the small print sent there too.



Middleware Middleware is simply something you’ll put into the request pipeline. Ways to setup logging middleware:

  • Application:

    Javascript




    const app = express()
    const loggingMiddleware = require('my-logging-middleware')
    app.use(loggingMiddleware)
  • Router:

    Javascript




    const router = express.Router()
    const routeLoggingMiddleware = require('my-route-logging-middleware')
    router.use(routeLoggingMiddleware)

Winston Package: Winston includes storage options,different log levels & queries and a profiler. 

Javascript




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(req, res, next) {
    logger.info(req.url)
    next()
}
app.use(logRequest)
  
function logError(err, req, res, next) {
    logger.error(err)
    next()
}
app.use(logError)



My Personal Notes arrow_drop_up
Recommended Articles
Page :