【问题标题】:how to utilize process.stdout.write instead of console.log in winston?如何在 winston 中使用 process.stdout.write 而不是 console.log?
【发布时间】:2023-01-28 03:33:25
【问题描述】:

我正在使用 winston 库来记录 nodeJS 应用程序。

我很乐意使用 process.stdout.write 而不是 console.log。我注意到 AWS Lambda docker 图像中的输出格式问题只发生在 console.log 上。

是否存在可以使用 process.stdout.write 而不是 console.log 的 Winston 传输?

如果没有,是否有替代方案而不覆盖控制台传输?

这是我当前的代码示例:

const winston = require('winston');
const appRoot = require('app-root-path');

const options = {
    file: {
        level: 'info',
        filename: `${appRoot}/logs/app.log`,
        handleExceptions: true,
        json: true,
        maxsize: 5242880, // 5MB
        maxFiles: 5,
        colorize: false,
    },
    console: {
        level: 'debug',
        handleExceptions: true,
        json: false,
        colorize: true,
    },
};

const logger = new winston.Logger({
    transports: [
        new winston.transports.File(options.file),
        new winston.transports.Console(options.console),
    ],
    exitOnError: false,
});

logger.stream = {
    write: (message: string) => logger.info(message),
};

module.exports = logger;

【问题讨论】:

    标签: aws-lambda winston


    【解决方案1】:

    以下是您如何创建使用 process.stdout.write 的自定义传输的示例:

        const winston = require('winston');
    
    const customStdout = new winston.transports.Transport({
        log: (level, msg, meta, callback) => {
            process.stdout.write(`[${level}]: ${msg}
    `);
            callback(null, true);
        }
    });
    
    const logger = new winston.Logger({
        transports: [customStdout]
    });
    

    您可以在代码中使用此记录器对象而不是控制台传输。这将为您提供与 console.log 相同的行为,但它将使用 process.stdout.write 代替。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-09-29
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多