How to create and save a log file in NodeJS for testing purpose?
The log file should contain the success/failure ratio of tests conducted.
I haven't tried anything yet as I am new to NodeJs.
-
success/failure ratio or success/failed messages ?rresol– rresol2016-11-30 04:25:55 +00:00Commented Nov 30, 2016 at 4:25
-
you can use loggers like winstonAJS– AJS2016-11-30 04:59:37 +00:00Commented Nov 30, 2016 at 4:59
-
Close duplicate of stackoverflow.com/questions/8393636/…KeshavDulal– KeshavDulal2016-12-01 09:16:32 +00:00Commented Dec 1, 2016 at 9:16
2 Answers
Firstly do you know about npm?
If No, then read/research about it.
Else, then good. Look out for npm-modules suitable for logging task.
I shall recommend you winston-logger.
Install winston in your project as:
npm install winston --save
Here's a configuration ready to use out-of-box that I use frequently in my projects as logger.js under utils.
/**
* Configurations of logger.
*/
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
const consoleConfig = [
new winston.transports.Console({
'colorize': true
})
];
const createLogger = new winston.Logger({
'transports': consoleConfig
});
const successLogger = createLogger;
successLogger.add(winstonRotator, {
'name': 'access-file',
'level': 'info',
'filename': './logs/access.log',
'json': false,
'datePattern': 'yyyy-MM-dd-',
'prepend': true
});
const errorLogger = createLogger;
errorLogger.add(winstonRotator, {
'name': 'error-file',
'level': 'error',
'filename': './logs/error.log',
'json': false,
'datePattern': 'yyyy-MM-dd-',
'prepend': true
});
module.exports = {
'successlog': successLogger,
'errorlog': errorLogger
};
And then simply import wherever required as this:
const errorLog = require('../util/logger').errorlog;
const successlog = require('../util/logger').successlog;
Then you can log the success as:
successlog.info(`Success Message and variables: ${variable}`);
and Errors as:
errorlog.error(`Error Message : ${error}`);
It also logs all the success-logs and error-logs in a file under logs directory date-wise as you can see here.

I have used "accesslog" instead of "successlog" as a keyword in my project.
And I didn't get what you meant about 'success/failure ratio'.
In order to get the ratio simply count the no. of times success and error logs are logged.
3 Comments
require and module.exports correctly to import and export although I haven't worked on .mjs or .cjs based approaches. Try out and let us know. Thanksrequire('mkdirp').sync('logs') // your log directory
var logger = require('log4js')
logger.configure({
"appenders": [{
"type": "console"
}, {
"type": "dateFile",
"category": "log",
"filename": "logs/exp",
"pattern": "yyMMdd.log",
"alwaysIncludePattern": true
}],
"replaceConsole": true
})
logger.info('success')
logger.error('fail')