如何在Express中创建自定义记录器? [英] How to to create a custom logger in Express?

查看:76
本文介绍了如何在Express中创建自定义记录器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学校锻炼期间,我们的任务是在Express中制作自定义中间件:

During an exercise in school we have been tasked with making custom middleware in Express:

这可能很棘手.使其成为您的自定义日志记录中间件 还注销最终的响应状态代码.例如, 向/成功的GET请求,您应该看到:

This might be tricky. Make it so that your custom logging middleware also logs out the eventual response status code. For example, after a successful GET request to / you should see:

GET / 200

我尝试过:

app.use(function(req, res, next) {
  console.log(chalk.green(req.method, req.url, res.statusCode));
  next();
});

它似乎可以工作,但是随后我尝试使用不存在的uri时仍然注意到:

It appears to work but then I noticed upon trying a uri which doesn't exist I still get:

GET /foo 200

这是否意味着 请求 (即GET)正在运行,但是如果资源在那儿就没事了?

Does this mean the request i.e. GET, is working but has nothing to do if the resource is there?

在这种情况下,我还尝试如何执行错误处理:

Also how would I implement error handling, in this instance I tried:

app.use(function(err, req, res, next) {
  if (err) {
    console.log(err);
  } else {
    console.log(chalk.green(req.method, req.url, res.statusCode));
  }
  next();
});

但是那根本没有用! 预先感谢!

But that didn't work at all! Thanks in advance!

推荐答案

app.use(function(req, res, next) {
  if (res.headersSent) {
    console.log(chalk.green(req.method, req.url, res.statusCode));
  } else {
    res.on('finish', function() {
      console.log(chalk.green(req.method, req.url, res.statusCode));
    })
  }
  next();
});

这篇关于如何在Express中创建自定义记录器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆