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

别来无恙 提交于 2019-12-11 18:56:55

问题


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


回答1:


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!



来源:https://stackoverflow.com/questions/51547294/how-to-create-multiple-log-files-and-append-logs-in-that-file-using-winston-libr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!