0

I am running a basic http server to serve static files in Node.js with express:

var setting = require('../setting')

var express = require('express'),
app = express(),
port = setting.http.port;

app.use(express.static(__dirname + '/' + setting.http.static_dir));
app.listen(port);

I know I can use something like forever to restart the server if it's dead for some reason. But, is there any way to log something when the server is crashed so that I can know the reason why it's crashed and when it's crashed?

Joe Huang
  • 6,296
  • 7
  • 48
  • 81
  • Do you have the console open or are you logging stdout and stderr? That's usually where you'd get your first clue. – jfriend00 Jan 16 '16 at 01:32

2 Answers2

1

With forever:

forever -o out.log -e err.log my-script.js

see this SO answer for more details.


If you want to only log Express server errors, you could use something like the error handler generated by the Express CLI tool:

server.on('error', onError);

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

where server is the instance created by running http.createServer(app).


If you want to log callback errors, you could have something like this:

brokenFunction(function(err) {
  if(err) return errorHandler(err);
  //...
});

function errorHandler(err) {
  //Do something with the error like printing to console or writing to file.
  console.log(err);
}

where brokenFunction is the function that returns an error to the callback and errorHandler is the function that performs any actions you want to occur on an error.

Community
  • 1
  • 1
WillS
  • 362
  • 1
  • 12
1

PM2 could be one useful tool. It allows you to keep applications alive forever, to reload them without downtime and to facilitate common system admin tasks. It is very useful for production environment.

If the Node app started in the console, the stack trace would be output in the console once it crashed. However, there was NO more information of variable or more details to help us to analysis why it crash. Now the --abort-on-uncaught-exception flag will be one good option to help us, we can start our app with

node --abort-on-uncaught-exception app.js

There will be core dump file once your app is crashed. Then to analysis the dump file with

lldb -c /cores/core.6781

More debug information could be found in this page.

zangw
  • 43,869
  • 19
  • 177
  • 214