4

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

Nikos
  • 696
  • 2
  • 9
  • 23

1 Answers1

2

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
      }
    }
}
Harry Adel
  • 1,238
  • 11
  • 16