winston记录到单独的文件

时间:2018-05-07 08:17:48

标签: node.js winston

我是node.js的新手,并且有这样的winson配置

const winston = require('winston');

const transports = [];

if (process.env.NODE_ENV !== 'development') {
  transports.push(new (winston.transports.DailyRotateFile)({
    filename: path.resolve(__dirname, '../logs/%DATE%/source1.log'),
    level: 'info',
    datePattern: 'YYYY-MM-DD',
  }));
   transports.push(new (winston.transports.DailyRotateFile)({
    filename: path.resolve(__dirname, '../logs/%DATE%/source2.log'),
    level: 'info',
    datePattern: 'YYYY-MM-DD',
  }));
}

let logger = winston.createLogger({
    level: 'info',
    format: winston.format.json(),
    transports,
    exitOnError: true,
});

logger.log({
    date: (new Date()).toString(),
    level,
    message,
    source,
});

我需要记录依赖于源的单独文件(文件中的所有source1日志../logs/%DATE%/source1.log'和source2相同)

怎么办呢?

1 个答案:

答案 0 :(得分:1)

通过GoogleTraduction FR-> ZH

你好!

如果您希望将日志分成几个单独的文件,我可以为您提供以下解决方案。
注意:此解决方案基于日志级别。

温斯顿:3.0.0
Nodejs:9.3.0

./ logger / index.js

const winston = require('winston');

module.exports = (dirname) => {
    const loggers = {
        info: null,
        warn: null,
        query: null,
        errDat: null,
        errFun: null,
        errInt: null,
    };

    for (let level of Object.keys(loggers)) {
        loggers[level] = winston.createLogger({
            levels: { [level]: 0 },
            format: winston.format.combine(
                winston.format.timestamp(),
                winston.format.printf(info =>
                    `${info.timestamp}\t[${info.level}]\t${info.message}`
                ),
            ),
            transports: [
                new winston.transports.Console({
                    level
                }),
                new winston.transports.File({
                    dirname,
                    filename: `${level}.log`,
                    level,
                    format: winston.format.json(),
                }),
            ]
        })[level];
    }

    return loggers;
};

其他文件

const path = require('path');
const { info, query, errInt, errDat, errFun } = require('./logger')(
    path.join(__dirname, 'logs')
);

info(`Test`);
query(`Test`);
errDat(`Test`);
errInt(`Test`);
errFun(`Test`);