How to log the HTTP status code?

Hi there,

I have set up logging using the approach recommended here:
Metrics and logging - Apollo GraphQL Docs

I’m wondering if it is somehow possible to include the HTTP status code in my logs. I do not see it on requestContext.response in the willSendResponse event nor does it seem to be available in formatResponse.

Is this possible?

Thank you so much

Hi @anjali, welcome to the community.

You might be aware that GraphQL always returns a 200 OK response back for every request. Here are some GraphQL specific error codes though - Error handling - Apollo GraphQL Docs.

With that being said, there might be some 3rd party libraries that allow you to do what you want. But the responsibility to determine which HTTP status code to return will lie on you.

Thanks for your reply, @kartik_gujarati.

I do know that GraphQL returns 200 OK for requests even with errors, but our server is returning a 400 for a Forbidden Error as well as 500s for Internal Server Errors. I am hoping to capture these status codes in the logs, but it looks like these are added after the plugin hooks in the request lifecycle.

Hi @anjali! So close :slight_smile:

I think response.http.status will have what you’re looking for from inside the willSendResponse hook.

Hi @trevor.scheer ,

Thanks for your reply.

The only property that is available in side my requestContext.response.http inside the willSendResponse hook is headers.

I am not seeing status. Am I missing something?

Thanks so much,
Anjali

Hey @anjali, apologies - I read the typings wrong and it turns out that response.http.status is optional!

In the case that it’s still not set from within the willSendResponse hook, ApolloServer will default the code to 200. You’re also able to set it yourself if you find that useful.

Thanks! So we have some authorization logic that will throw a 400 Forbidden error. Also I know that if there’s something wrong with the Gateway, we receive a 500 error. I’m hoping to be able to capture these http status codes in our logs, given that it’s not always 200. It would be great to be able to quickly look at the logs and understand if the gateway is down, for example. Is this possible?

Another alternative is to do response code logging at the HTTP level, eg something like javascript - Get response status code in a middleware - Stack Overflow

When you say “we have some authorization logic…” is this is a RESTDataSource within your GraphQL Server, or is this authorization logic part of your GraphQL server from where you are doing the logging?

If the authorization is performed by a RESTDataSource, you can log right from the RESTDataSource. You should have access to the status code for that REST call. And if the authorization logic is part of your GraphQL server, you can log right after the authorization fails. In either case, you do not have to wait until the didEncounterErrors or the willSendResponse callback to trigger to perform logging.