Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 524
Nikos Avatar asked Sep 05 '25 03:09

Nikos


1 Answers

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
      }
    }
}
like image 135
Harry Adel Avatar answered Sep 07 '25 23:09

Harry Adel