For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan
Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.
const appRoot = require('app-root-path');
const winston = require('winston');
// define the custom settings for each transport (file, console)
const options = {
file: {
level: 'info',
filename: `${appRoot}/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // 5MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
handleExceptions: true,
json: false,
colorize: true,
},
};
// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
],
exitOnError: false, // do not exit on handled exceptions
});
} else {
logger = winston.createLogger({
transports: [
new winston.transports.File(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
}
// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
write(message) {
logger.info(message);
},
};
module.exports = logger;
After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log
,
" to the respective app.log created by you.
After this go to your index.js and include the following code in it.
const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));
winston.info('You have successfully started working with winston and morgan');