NodeJS ExpressJS - How to log errors for a production server?

How can I log any errors from ExpressJS applications to a file?

I know that I can easily log in to Slim Framework using monolog :

$app->get('/tickets', function (Request $request, Response $response) {
    $this->logger->addInfo("Something interesting happened");

    $mapper = new Simon\TicketMapper($this->db);
    $tickets = $mapper->getTickets();

    $response->getBody()->write(var_export($tickets, true));
    return $response;
});

In Express, I usually log an error on the development console :

Model.findOne(options, function(err, doc) {

    var output = {};
    if (err) {
        console.log("Error retrieving doc: " + err);
    }

But on my production server, I need a useful log file when the application does not work correctly.

Any ideas?

In Express, app.jsthis has:

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

But how do I turn on production? Is it just like a monologue, what do I need?

+6
source share
3 answers

winston - .

, .

:

  var winston = require('winston');

  var logger = new winston.Logger({
    level: 'error',
    transports: [
      new (winston.transports.File)({ filename: 'error.log' })
    ]
  });

:

logger.log('error', 'test error message %s', 'my string');

winston daily rotate file winston .

+7

, morgan, node, , pm2, pm2 . pm2 , , , , console.log , pm2 . pm2 .

+2

, PM2 - , , PM2 .

0

Source: https://habr.com/ru/post/1673342/


All Articles