json - winston 日志格式

标签 json node.js winston

我正在使用 Winston ^3.0.0-rc6,如下所示:

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

    }
};

const jsonFormatter = (logEntry) => {
    if (logEntry.type) {
        const base = {
            timestamp: new Date()
        };
        const json = Object.assign(base, logEntry);
        logEntry[MESSAGE] = JSON.stringify(json);
    } else {
        logEntry = "";
    }

    return logEntry;
}

const logger = winston.createLogger({
    format: winston.format(jsonFormatter)(),
    transports: [
        new winston.transports.File(options.file)
    ],
    exceptionHandlers: [
        new winston.transports.File(options.uncaughtExceptions)
    ]
});

我的日志输出:

{"timestamp":"2018-06-10T07:41:03.387Z","type":"Authentication","status":"failed","level":"error","message":"Incorrect password"}

但我希望它们像:

{
    "timestamp": "2018-06-10T07:41:03.387Z",
    "type": "Authentication",
    "status": "failed",
    "level": "error",
    "message": "Incorrect password"
}

我尝试使用 json: true 和 PrettyPrint 但它没有成功。

谁能帮忙

谢谢。

最佳答案

我在你的代码中注意到了这一点

logEntry[MESSAGE] = JSON.stringify(json);

您正在使用JSON.stringify()它需要另外两个可选参数

JSON.stringify(value[, replacer[, space]])

如果您将 space 设置为您想要的空格数量,您将获得您正在寻找的输出。因此将初始行更改为:

logEntry[MESSAGE] = JSON.stringify(json, null, 2);  // or 4 ;)

(replacer 参数为 null,因为我们不想更改默认行为。)

关于json - winston 日志格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50781602/

相关文章:

javascript - Crontab 阻止 Winston 写入我的日志文件

node.js - Node winston 不支持多文件传输?

java - Java中的JSON解析找不到项目

javascript - Mongoose :缓存虚拟

php - 如何从单独的脚本轮换 Winston 日志?

node.js - 使用 mocha/supertest 测试随机值

node.js - ES6 - 导入文件的重复声明

AngularJS 406 Not Acceptable http 发布请求

php - 在网站上显示 JSON 数据

javascript - 尝试访问 JSON 数组中的 key