首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Winston日志格式

Winston日志格式
EN

Stack Overflow用户
提问于 2018-06-10 15:48:30
回答 2查看 13.9K关注 0票数 3

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

代码语言:javascript
复制
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)
    ]
});

我的日志输出:

代码语言:javascript
复制
{"timestamp":"2018-06-10T07:41:03.387Z","type":"Authentication","status":"failed","level":"error","message":"Incorrect password"}

但我希望他们是这样的:

代码语言:javascript
复制
{
    "timestamp": "2018-06-10T07:41:03.387Z",
    "type": "Authentication",
    "status": "failed",
    "level": "error",
    "message": "Incorrect password"
}

我试着尝试使用json : true和prettyPrint,但它没有起到作用。

有谁能帮忙吗?

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-07-08 19:31:51

我在你的代码中注意到

代码语言:javascript
复制
logEntry[MESSAGE] = JSON.stringify(json);

您使用的是JSON.stringify(),它接受另外两个可选参数

代码语言:javascript
复制
JSON.stringify(value[, replacer[, space]])

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

代码语言:javascript
复制
logEntry[MESSAGE] = JSON.stringify(json, null, 2);  // or 4 ;)

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

票数 2
EN

Stack Overflow用户

发布于 2018-06-10 16:36:58

这已被弃用:您可以检查链接here

我尝试过使用json: true和prettyPrint,但它没有起到作用。

像下面这样的简单代码可以为您工作:

代码语言:javascript
复制
const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    //
    // - Write to all logs with level `info` and below to `combined.log` 
    // - Write all logs error (and below) to `error.log`.
    //
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

如果这不起作用,请让我知道,这样我就可以即兴发挥。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50781602

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档