使用Morgan和Winston记录HTTP请求

时间:2019-12-06 17:46:55

标签: javascript node.js logging winston morgan

我正尝试使用morgan和Winston的流仅记录一些传入HTTP请求的信息:

// winston.js
const options = {
    console: {
        format: winston.format.json()
        level: 'debug',
        handleExceptions: true
    }
}

// instantiate a new Winston Logger with the settings defined above
const logger = new winston.createLogger({
    transports: [
        new winston.transports.Console(options.console)
    ],
    exitOnError: true
})

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
    write: function(message, encoding) {
        logger.info(message)
    }
}
// app.js
app.use(morgan('{"remote_addr": ":remote-addr", "method": ":method"}', { stream: logger.stream }));

但是winston似乎转义了JSON字符串,因此输出看起来像:

  

{“ message”:“ {\” remote_addr \“:\” :: 1 \“,\” method \“:\” GET \“} \ n”,“ level”:“ info”}

想要的输出:

  

{“ remote_addr”:“ :: 1”,“方法”:“ GET”,“级别”:“信息”}

如果不可能,至少:

  

{“ message”:“ {” remote_addr“:” :: 1“,” method“:” GET“}”,“ level”:“ info”}

我正在使用Winston 3.2和Morgan 1.9。

灵感来自this link

的最后一部分

0 个答案:

没有答案