Search code examples
typescriptgraphqlapolloapollo-server

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


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!


Solution

  • 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