Warm tip: This article is reproduced from stackoverflow.com, please click
apollo apollo-server graphql typescript

How do I write a Apollo Server plugin to log the request and its duration

发布于 2020-04-07 23:22:18

I am surprised I could not find a library or example to do the following:

I want a simple server log of each request to the server that will state what query or mutation was requested, and the elapsed time it took to complete the request

I know there is the plugin and extension frameworks. But I am not sure what the best practice is to keep state between the two callbacks: requestDidStart and willSendResponse

something that would spit out:

path="createAccountMutation" service=20ms

extra credit would be to show the size of the payload

path="createAccountMutation" service=20ms bytes=355

Would love to see the solution in typescript

Note: I found apollo-log -- but it does not do request duration

Thanks!

Questioner
Jonathan
Viewed
96
Daniel Rearden 2020-01-30 23:34

requestDidStart is called once per request and returns a map of request lifecycle hooks, so you can initialize any state persisted between the hooks there.

const LogPlugin = {
  requestDidStart(requestContext) {
    const start = Date.now()
    let op

    return {
      didResolveOperation (context) {
        op = context.operationName
      },
      willSendResponse (context) {
        const stop = Date.now()
        const elapsed = stop - start
        const size = JSON.stringify(context.response).length * 2
        console.log(
          `Operation ${op} completed in ${elapsed} ms and returned ${size} bytes`
        )
      }
    }
  },
}

Note that this will only work on a per-request basis. If you need something more granular, like tracking how long an individual field takes to resolve, you'd need to utilize a directive or middleware