Whenever there were any server alerts in my team at Adobe, the first thing that we used to do was to look at the logs. And in most cases, we would track down the issue within minutes. Logs can be valuable in security, debugging, and analytics.

When debugging, your first friend is the console. The most simple type of logging you could do is using console.log and console.error methods.

console.log("hello Codesolution")

This would output Hello World in the terminal window.

But this is not enough in production because

  1. Console logs are synchronous(unless you use pipe)
  2. The console is completely manual, so you have to format, manage and debug on your own.

Given this, I decided to go ahead with Bunyan because ultimately we want to use the logs primarily for analytics (and I liked their JSON format). Once I installed Bunyan I found a package, express-bunyan-logger, that was doing exactly what we were looking for.

npm install express-bunyan-logger express

I introduced the following code in express.js before the controller code

app.use(require('express-bunyan-logger')({name: 'nodeBunyan',
  streams: [{
    type: 'rotating-file',
    level: 'info',                  // loging level
    path: '/var/log/nodeBunyan.log', //filepath create log file
    period: '1d',   // daily rotation
    count: 3,        // keep 3 back copies
  }]
}));
 
create an app.js and below code: 
const express = require('express')
const app = express()
const path = require('path')

app.use(require('express-bunyan-logger')({name: 'ShotPitch',
  streams: [{
    type: 'rotating-file',
    level: 'info',                  // loging level
    path:  path.join(__dirname, 'nodebunyan.log'),  //filepath create log file
    period: '1d',   // daily rotation
    count: 3,        // keep 3 back copies
  }]
}));

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.listen(9000)
Thank you :)

 

  1.  
About the author
Sudarshan Vishwakarma

sudarshan.vis101@gmail.com

Discussion
  • 0 comments

Add comment To Login
Add comment