4

I managed to setup logging graphQL errors with:

app.use('/graphql', graphqlHTTP(request => {
  return {
    schema,
    rootValue: {
      request
    },
    formatError: error => {
      const params = {
        message  : error.message,
        locations: error.locations,
        stack    : error.stack
      };
      winston.error(`message: "${error.message}", QUERY: "${request.body.query}"`);
      // Optional ${request.body.operationName} ${request.body.variables}
      return (params);
    }
  }
}));

How can I set up a general function that can access the request and response, even when there is no error?

Edit: I've managed to log all requests by:

function loggingMiddleware(req, res, next) {
  if (req.url.startsWith('/graphql')) {
    winston.debug('REQUEST: ', req.body);
  }
  next();
}
app.use(loggingMiddleware);

before I call app.use('/graphql'), but still don't know how to run a "post graphql handling" handler to log the response as well.

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
eran
  • 14,496
  • 34
  • 98
  • 144
  • Thanks for posting about how you managed to logging. I find `req.body` to be undefined with the current version of `express-graphql` though (0.9.0). – Dan Dascalescu Apr 14 '20 at 08:03

3 Answers3

4

You can proxy the req.send() function in express.

app.use(function (req, res, next) {
    let originalSend = res.send;
    res.send = function (data) {
        console.log(data);
        originalSend.apply(res, Array.from(arguments));
    }
    next();
})

This is just to show you how you can achieve something like this.

I see you use winston, so I'd suggest you to use express-winston.

Also, check this out.

Community
  • 1
  • 1
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
1

I'm using this package to achieve what you want: https://github.com/withspectrum/graphql-log

Also I use debug and I added a date as prefix of my logs, here is a example code:

if (process.env.NODE_ENV === 'development') {
    const createGraphQLLogger = require('graphql-log');
    const debug = require('debug')('server:resolvers');
    debug.enabled = true;
    const logExecutions = createGraphQLLogger({
        prefix: new Date(),
        logger: debug
    })
    logExecutions(resolvers);
}
1

It's very simple. express-graphql provides an extensions mechanism, which supplies you with the result directly as one of the parameters.

app.use('/graphql', graphQLHTTP(request => {
  return {
    schema: ...,
    extensions({
      result,
    }) {
      console.log(result.data);
    },
  };
}));
Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404