我们如何记录每个http请求和响应并将其快速保存到数据库中

时间:2019-06-27 06:25:27

标签: express logging httprequest response winston

我正在尝试将所有传入的请求及其响应保存到数据库中。

我正在尝试使用express-winston npm软件包来实现此目的,并且它正在控制台中记录响应正文和请求。但我想将其保存在数据库中。我该怎么办??

var winston = require("winston");
var expressWinston = require("express-winston");

expressWinston.requestWhitelist.push("body");
// expressWinston.responseWhitelist.push("body");
app.use(
  expressWinston.logger({
    transports: [
      new winston.transports.Console({
        json: true,
        colorize: true
      })
    ]
  })
);
expressWinston.responseWhitelist.push("body");

我正在控制台中获取此日志。

  

{“ level”:“ info”,“ message”:“ HTTP GET / ideas / category / hello”,“ meta”:{“ res”:{“ statusCode”:200,“ body”:{“ hiiii “:” djdjjdjdjdd“}},” req“:{” url“:” / ideas / category / hello“,” headers“:{” host“:” localhost:5000“,” connection“:” keep-alive“ ,“ upgrade-insecure-requests”:“ 1”,“ user-agent”:“ Mozilla / 5.0(X11; Linux x86_64)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 75.0.3770.100 Safari / 537.36”,“接受“:” text / html,application / xhtml + xml,application / xml; q = 0.9,image / webp,image / apng, / ; q = 0.8,application / signed-exchange; v = b3“,” accept-encoding“:” gzip,deflate,br“,” accept-language“:” en-GB,en; q = 0.9,en-US; q = 0.8,hi; q = 0.7“,” cookie”:“ connect.sid = s%3A90PCwDOrv0v9yeSYZq-4I4Quac​​tbcduq.8EpLenv6t1lCPqLcV5R1o1%2FF15p9kEBqrZ82FBHiYJA“},”方法“:” GET“,” httpVersion“:” 1.1“,”正则表达式“查询”:{}},“ responseTime”:2}}

1 个答案:

答案 0 :(得分:0)

进行一些研究后,我得到了答案。我们可以使用winston-sql-transport npm软件包来实现这一目标。请参见下面的代码:

const { Logger } = require('winston');
const { SQLTransport } = require('./../lib/winston-sql-transport');

const logger = new Logger({
  transports: [
    new SQLTransport({
      tableName: 'winston_logs',
    })]
});

module.exports = logger;