I am working in node js and using Winston library for logging. The following code does not create a log file.
var winston = require('winston');
var logger = winston.createLogger({
transports: [
new winston.transports.File({
level: 'info',
filename: './logs/all-logs.log',
handleExceptions: true,
json: true,
maxsize: 5242880, //5MB
maxFiles: 5,
colorize: false
}),
new winston.transports.Console({
level: 'debug',
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false
});
module.exports = logger;
module.exports.stream = {
write: function(message, encoding){
logger.info(message);
}
};
logger.info("hello world");
It logs to the terminal fine:
{"message":"hello world","level":"info"}
Directory Structure is like this
-test.js
-winston.js
-log
Here's you should use Winston:
Below code creates log files in /log/
directory.
First, install the winston-daily-rotate-file, fs, and winston using:
npm i winston-daily-rotate-file fs winston
Create a file with name winston.js
const fs = require("fs");
const winston = require("winston");
const logDir = "log";
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const tsFormat = () => (new Date()).toLocaleTimeString();
module.exports = logger = winston.createLogger({
transports: [
new (winston.transports.Console)({
format: winston.format.combine(
winston.format.colorize(),
winston.format.timestamp(),
winston.format.align(),
winston.format.simple(),
),
level: 'info'
}),
new (require("winston-daily-rotate-file"))({
filename: `${logDir}/-results.log`,
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json(),
)
}),
new winston.transports.File({
filename: 'log/error.log',
level: 'error',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.simple(),
)
}),
]
});
Now all you have to do is, import the logger and use it. Below is the example.
Now in the same directory, create a new file test.js and add following code:
const logger = require("./winston.js");
logger.info(`Test info Log!`);
logger.error(`Test error Log!`);
Now run test.js using
node test.js
Hope this is what you are looking for.