How can I log any errors from ExpressJS apps into a file?
I know I can log a Slim framework easily with 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 the error to console for development:
Model.findOne(options, function(err, doc) {
var output = {};
if (err) {
console.log("Error retrieving doc: " + err);
}
But in my production server, I do need a helpful log file when the app goes wrong.
Any ideas?
In Express's app.js
, it has this:
// 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 the production's one on? Is it the same as monolog that I need?
The built-in console module in Node. js lets you write log messages to standard output (stdout) and standard error (stderr)using the log and error functions, respectively. This module is most definitely the simplest method for getting started, since it doesn't require importing or configuring any third-party packages.
The simplest way of handling errors in Express applications is by putting the error handling logic in the individual route handler functions. We can either check for specific error conditions or use a try-catch block for intercepting the error condition before invoking the logic for handling the error.
Catching Errors Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example: app.get('/', (req, res) => { throw new Error('BROKEN') // Express will catch this on its own. })
winston is a popular library for logging.
You can transport all logs to one file or keep different files for error, debug and info logs.
Example:
var winston = require('winston');
var logger = new winston.Logger({
level: 'error',
transports: [
new (winston.transports.File)({ filename: 'error.log' })
]
});
In the code:
logger.log('error', 'test error message %s', 'my string');
You can also use winston daily rotate file with winston to rotate your log files based on size or date.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With