nodejs+express 实现访问日志和错误日志功能
发布于 11 年前 作者 kimady 25204 次浏览 最后一次编辑是 8 年前

打开app.js,加入以下代码:

var fs = require('fs');
var accessLogfile = fs.createWriteStream('access.log', {flags: 'a'});
var errorLogfile = fs.createWriteStream('error.log', {flags: 'a'});

然后在app.configure第一行加入:

app.use(express.logger({stream: accessLogfile}));

至于错误日志,需要单独实现错误响应,修改如下: 对于3.x版本的express:

app.configure('production', function() {
  app.use(function(err, req, res, next){
    var meta = '[' + new Date() + '] ' + req.url + '\n';
    errorLogfile.write(meta + err.stack + '\n');
    next();
  });
});

对于2.x版本的express:

app.configure('production', function() {
  app.error(function(err, req, res, next){
    var meta = '['+new Date()+']' + req.url + '\n';
    errLogfile.write(meta + err.stack + '\n');
    next();
  });
});
3 回复

我使用forever跑的express,可以指定access和error的log,真心不错。

在3.x中use,为什么能够捕获到error?不能理解~求解释

恩 对 支持用forever!

回到顶部