Nikos
Nikos

Reputation: 724

Loopback strong-error-handler and log errors to file

I cannot understand how can I configure Loopback to store strong-error-handler output to a file with a proper logging strategy.

Upvotes: 4

Views: 644

Answers (1)

Harry Adel
Harry Adel

Reputation: 1436

There're two parts to be handled here. First, we need to grab the errors. This can be done easily, passing a layer/middleware intercepting the error as described here by the official documentation

Second, we've to pass those errors to our logging file. Handsome folks have already done it here, too. Some are recommending Winston while others are doing it by their hands, as for educational purposes, let's use the native way.

error-logger.js

'use strict';

const fs = require('fs');
const util = require('util');
const logFile = fs.createWriteStream(__dirname + '/debug.log', {flags: 'w'});
const logStdout = process.stdout;

module.exports = function(options) {
  return function logError(err, req, res, next) {
    console.log('unhandled error', err);
    logFile.write(util.format(err) + '\n');
    logStdout.write(util.format(err) + '\n');
    next(err);
  };
};

Don't forget about middleware.

server/middleware.json

{
  // ...
  "final:after": {
    "./middleware/error-logger": {},
    "strong-error-handler": {
      "params": {
        "log": false
      }
    }
}

Upvotes: 2

Related Questions