Why log and log rotate?
Log is a file that records either events that occur in an application or messages between different users of a communication.Benefits
- For better debugging and find the problems.
- For better application management.
- For security reason to tracking an application behaviors.
How we can achieve these above points in Nodesjs
Step 1- Require a npm modules - winston and winston-daily-rotate-file
-
npm i winsto
-
npm i winston-daily-rotate-file
logger.js :
var winston = require('winston');
require('winston-daily-rotate-file');
var transport = new winston.transports.DailyRotateFile({
filename: './log', // Log file name and location
datePattern: 'yyyy-MM-ddTHH.', // Log rotate duration is hourly basis
prepend: true,
level: process.env.ENV == 'development' ? 'info' : 'debug' //As per requirement - local server or production
});
var logger = new (winston.Logger)({
transports: [
transport
]
});
module.exports = logger; //Export it as module
Step 3- We have created a module called logger. Now we need to include it on our app.js or server.js (Enter point of Node server where we include all other dependency)
i.e - app.js (I have created a app.js file as entry file in node run environment)
global.logger = require('logger'); //Include a Export Module
i.e 2017-01-27T11.log
2017-01-27T12.log
global.logger = require('logger'); //Include a Export Module
logger.info('Hello World!'); // set logger for information - same as console.log() function
logger.debug('Hello World!'); // set logger for debug purpose - log and debug as per your requirement
Step 4- Run your application - node app.js
It creates file on hourly basis. In our case it created file 2017-01-27T11.log file in parallel of app.js file.
content of 2017-01-27T11.log file is :
{"level":"info","message":"Hello World!","timestamp":"2017-01-27T11:43:22.529Z"}
{"level":"debug","message":"Hello World!","timestamp":"2017-01-27T11:43:22.570Z"}
- It will create new log file as hourly basis.i.e 2017-01-27T11.log
2017-01-27T12.log
You can drop comment for any questions or feedback.Will get back to you soon.