对nodejs的日志请求表达

时间:2017-08-11 01:05:52

标签: node.js express logging

我想记录所有这样的请求:

CREATE TABLE IF NOT EXISTS `klusek73_umowy`.`Ceny` ( `idCeny` INT UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT, `Umowy_idUmowy` INT UNSIGNED ZEROFILL NOT NULL, `Cena1` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena2` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena3` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena4` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena5` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena6` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena7` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena8` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena9` DECIMAL(7,2) UNSIGNED NOT NULL, `Cena10` DECIMAL(7,2) UNSIGNED NOT NULL, PRIMARY KEY (`idCeny`, `Umowy_idUmowy`), UNIQUE INDEX `idCeny_UNIQUE` (`idCeny` ASC), INDEX `fk_Ceny_Umowy1_idx` (`Umowy_idUmowy` ASC), UNIQUE INDEX `Umowy_idUmowy_UNIQUE` (`Umowy_idUmowy` ASC), CONSTRAINT `fk_Ceny_Umowy1` FOREIGN KEY (`Umowy_idUmowy`) REFERENCES `klusek73_umowy`.`Umowy` (`idUmowy`) ON DELETE NO ACTION ON UPDATE NO ACTION) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;

然而,在express中,在处理请求之前调用中间件,因此我无法获得真正的响应代码。我总是得到200.实现这个目标的正确方法是什么?

3 个答案:

答案 0 :(得分:2)

您可以使用morgan记录您的请求:

const morgan = require("morgan");
app.use(morgan('dev'));

有关更多文档,请访问morgan。哟也许有兴趣 on-finished包在请求完成时执行任意代码。

答案 1 :(得分:1)

您在这里:

app.use((req, res, next)=> {
  console.log('I run on every request!');
  next();
})

答案 2 :(得分:0)

让您的中间件位于您的路线下方并在您的路线中在回调中添加第三个参数,如下所示:

app.get( "/", function( req, res, next ) {
  res.send(something);
  next();
});

app.use(function(req, res, next) {
  console.log('after request is done');
});