我目前有以下代码:
var express = require('express');
var path = require('path');
var fs = require('fs');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// Create write stream and append to file
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// additional logging
app.use(logger('combined', {stream: accessLogStream}));
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
哪个应该将日志的内容写入文件,这样我就可以查看 IP 地址范围并找出谁访问了我的网站以及从何处访问。但是,虽然创建了文件,但当我键入内容时cat access.log
,内容是空白的,尽管我已经测试过自己,所以我知道人们正在访问它。从我在谷歌上可以找到的内容来看,我应该使用受信任的代理和 req.ips 做一些事情。我找到了这段示例代码:
app.set('trust proxy', function (ip) {
if (ip === '127.0.0.1' || ip === '123.123.123.123') return true; // trusted IPs
else return false;
});
这看起来与我所追求的非常相似(我假设我将 '123.123.123.123' 更改为我自己的服务器 IP 地址......?)但我真正想做的是让这个输出访问我创建的 .log 文件。
有任何想法吗?
ATPB