Amy T McBride Amy T McBride - 1 year ago 68
Node.js Question

Cat shows there is nothing in log (express server)

I currently have the following code:

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(bodyParser.urlencoded({ extended: false }));
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;

// 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: {}

Which should write the contents of the logs to a file, so I can look through the IP address ranges and find out who accessed my website and from where. However, though the file is created, when I type
cat access.log
the contents is blank, though I've tested myself so I know people are accessing it. From what I can find on Google I'm supposed to do a something with a trusted proxy and req.ips. I found this bit of sample code:

app.set('trust proxy', function (ip) {
if (ip === '' || ip === '') return true; // trusted IPs
else return false;

Which looks pretty similar to what I'm after (I assume I change '' to my own server IP address...?) But what I'd really like to be able to do is make this output to the access.log file I've created.

Any ideas?


Answer Source

You have your logger() after your routes, so you won't see normal traffic, you will only log errors. If you want to see normal traffic, move this line:

app.use(logger('combined', {stream: accessLogStream}));

before this line:

app.use('/', routes);

If you want to also log requests to static assets in your public/ directory, then move it up further before this line:

app.use(express.static(path.join(__dirname, 'public')));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download