简体   繁体   English

在 Node.js 中使用 Winston 和 Winston-Daily-Rotate-File 输出 JSON Object 内的日志

[英]Outputting Logs inside JSON Object with Winston and Winston-Daily-Rotate-File in Node.js

I have the same problem and want the same result as in here: Outputting Logs inside JSON Object with Winston in Node.js我有同样的问题,并希望得到与此处相同的结果: Outputing Logs inside JSON Object with Winston in Node.js

But I use winston-daily-rotate-file and therefore the given answer/ solution does not work in my case.但是我使用winston-daily-rotate-file,因此给定的答案/解决方案在我的情况下不起作用。

My logger looks like this:我的记录器看起来像这样:

const path = require('path');
const { createLogger, format, transports, addColors, config } = require('winston');
const winstonDailyRotateFile = require('winston-daily-rotate-file');
const { combine, timestamp, json, colorize, label, printf, errors } = format;

const CustomTransport = require('./customtransport')

const customLevels = {
    levels: {
      error: 0,
      warn: 1,
      fileProcessed: 2,
      info: 3,
      debug: 4,
      silly: 5,
    },
    colors: {
        error: 'bold red',
        warn: 'bold yellow',
        fileProcessed: 'bold blue',
        info: 'bold cyan',
        debug: 'bold gray',
        silly: 'bold magenta'
    }
  };

addColors(customLevels.colors);

const consoleFormat = printf(({ level, message, label, stack }) => {
    const log = `${level}: [${label}] ${message}`;
    const errLog = `${log}\n${stack}`;

    return stack ? errLog : log;
});

module.exports = (module) => {
    const logger = createLogger({
        levels: customLevels.levels,
        transports: [
            new CustomTransport({

            }),
            new winstonDailyRotateFile({
                format: combine(
                    errors({stack: true}),
                    timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
                    label({ label: path.basename(module.filename) }),
                    json(),
                ),
                dirname: './logs',
                filename: 'sppa-%DATE%.log',
                datePattern: 'YYYY-MM-DD',
                zippedArchive: true,
                maxSize: '20m',
                maxFiles: '14d'
            })
        ]
    });

    // If we're not in production then log to the `console` 
    if (process.env.NODE_ENV !== 'production') {
        logger.add(new transports.Console({
            levels: customLevels.levels,
            level: 'silly',
            format: combine(
                colorize(),
                errors({stack: true}),
                label({ label: path.basename(module.filename) }),
                consoleFormat
            ),
        }));
    }

    return logger;
}

Any help would be greatey appreciated!任何帮助将不胜感激!

I used a workaround with regex now where I replaced newlines with a comma and added [ ] around the file.我现在使用正则表达式的解决方法,用逗号替换换行符并在文件周围添加 [ ]。 It looks like this:它看起来像这样:

app.get("/log", (req, res) => {
    fs.readFile('C:\\Path\\To\\nodeAPI\\logs\\test.log', function (err, data) {
        if (err) {
            console.log(err);
        }
        let content = data.toString('utf8').replace(/\r?\n|\r/g, ',');
        content = "[" + content + "]";
        res.send(content);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM