expressgraphql-jsbunyan

Logging query string with express-bunyan-logger and graphql


I've made a short, self contained example of a problem I'm having with express-bunyan-logger.

I'm trying to add express-bunyan-logger as middleware, and utilize includesFn to log the query string and body as a custom fields.

const app = express();

const graphqlLogger = require('express-bunyan-logger')({
  name: 'graphql-logger',
  includesFn: (req, res) => {
    const includes = {};
    if (req.body) includes.req_body = JSON.stringify(req.body);
    if (req.query) includes.req_query = JSON.stringify(req.query);
    return includes;
  },
});

app.use(graphqlLogger);

Problem is, even for a URL of the form http://localhost:4000/graphql?query=query%20%7B%0A%20%20books%20%7B%0A%20%20%20%20title%0A%20%20%7D%0A%7D, the req_query and req_body fields are always empty. If I inspect the req object that's passed to includesFn in a debugger, it doesn't contain any values for req.query or req.params.

I'm sure I'm doing something wrong here; how do I get the includesFn to log the query string and body correctly?


Solution

  • So, turns out the includesFn is being called twice, once per each request.

    First, for the GET request, then you will get only the req.query object not empty.

    The second request is the POST request that is being with JSON data, so in order to to get the req.body defined and not empty, you have to do the following:

    1. run npm install body-parser.
    2. include the following in your app.js file:

      const bodyParser = require('body-parser');
      
      ...
      
      app.use(bodyParser.urlencoded({
        extended: true
      }));
      
      app.use(bodyParser.json());