CNode

nodejs+express 实现访问日志和错误日志功能

Kkimady发布于13 年前最后回复13 年前3 回复26647 浏览0 收藏

打开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)

F
fcicada#1·13 年前

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

K
kulelikule#2·13 年前

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

C
chemdemo#3·13 年前

恩 对 支持用forever!

参与回复
登录后即可参与回复。登录