Nodejs记录器中间件

时间:2017-09-14 13:02:32

标签: node.js express

我希望对一个快递中的每个请求都有请求和响应 基于日志文件的应用程序。我想只要求jsons和响应。您能否建议我使用中间件或其他最适合此目的的解决方案?

祝你好运

2 个答案:

答案 0 :(得分:2)

尝试Morgan并使用跳过非json请求的自定义过滤器。

app.use(
  morgan(
    ':method :url :status :res[content-length] - :response-time ms',
    { skip: skipNonJSON }
  )
)

skipNonJSON可以定义如下,

function skipNonJSON(request, respnose) {
  return !(/\.json$/.test(req.url))
}

如果json请求您指的是以.json结尾的网址。对于JSON付费请求,请查看标题

function skipNonJSON(request, respnose) {
  return req.headers["Content-Type"] !== "application/json";
}

答案 1 :(得分:2)

您可以使用高度可配置的winston记录器。

const winston = require('winston');
let logger = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({ filename: 'file.log' })
  ]
 });
logger.info('Your custom data to log');
相关问题