Enable logs for SmartActions with morgan

@Danny @Justin_Martin

Hello everyone :wave:

After playing with the Morgan logger, I have figure out something.

Please, be sure to initialise Morgan (eg call app.use(morgan(jsonFormat));) right after the line configuring the jwt middleware, and before the lines that initialise your forest routes.

In a generated project from the forest-cli, it should look like something like this:

...
app.use(jwt({
  secret: process.env.FOREST_AUTH_SECRET,
  credentialsRequired: false,
  algorithms: ['HS256'],
}));

<==Put the morgan configuration and middleware right here !==>

app.use('/forest', (request, response, next) => {
  if (PUBLIC_ROUTES.includes(request.url)) {
    return next();
  }
  return ensureAuthenticated(request, response, next);
});

requireAll({
  dirname: path.join(__dirname, 'routes'),
  recursive: true,
  resolve: (Module) => app.use('/forest', Module),
});

requireAll({
  dirname: path.join(__dirname, 'middlewares'),
  recursive: true,
  resolve: (Module) => Module(app),
});

...

Now, we ensure that Morgan logging system will be called before the route is even handled by any code.

Keep in mind that you absolutely need to initialise Morgan after the jwt library, otherwise you will not be able to retrieve any information from the user, as the jwt library is responsible for filling in the request.user attribute.

I hope this can help !

Steve.

5 Likes