user1hjgjhgjhggjhg
user1hjgjhgjhggjhg

Reputation: 1327

How to create multiple log files and append logs in that file using winston library

I am using Winston library in nodes for error logs. Now what I want is to create multiple logger files dynamically.

The code I am using is this

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(),
            )
        }),
    ]
});

I need something like if I pass a filename calling logger

logger.info(`Test info Log!`,'filename');

It should log file in this filename. if file doesn't exist it creates it and appends everything in that file

Upvotes: 0

Views: 1322

Answers (1)

Harshal Yeole
Harshal Yeole

Reputation: 4983

What you are trying to achieve here is creating the log files dynamically by specifying the filename.

Which is Not Possible as we have to declare the files and logger options while we instantiate the logger instance in the winston.js file.

Here:

module.exports = logger = winston.createLogger({}

And you cannot update it on the go!

Hope I have cleared your thoughts!

Upvotes: 1

Related Questions