Add the following to the top of the index.ts to initialize the App Insights client as early as possible and to import the types needed for the plugin. Note in the configuration we've defined a custom property of "functionArea" to help organize our logs and make them easier to query.
azure-quickstart/data-access/graphql/index.ts
let appInsights = require("applicationinsights");
appInsights.setup().start();
appInsights.defaultClient.commonProperties = {
environment: process.env.WEBSITE_HOSTNAME,
functionArea: "graphql"
};
let appInsightsClient = appInsights.defaultClient;
import {
ApolloServerPlugin,
GraphQLRequestContext,
GraphQLRequestListener,
} from 'apollo-server-plugin-base';
Define the Apollo Plugin
This plugin logs some valuable information:
Metrics: apollo-query / apollo-error
Quickly see the volume of queries / errors in Azure Monitor
Exceptions:
Track down details of errors through Azure Log Analytics
azure-quickstart/data-access/graphql/index.ts
// referenced from https://jeffmagnusson.com/post/graphql-apollo-server-plugins-in-typescript
const appInsightsPlugin = <ApolloServerPlugin & GraphQLRequestListener>{
// Fires whenever a GraphQL request is received from a client.
requestDidStart(requestContext:GraphQLRequestContext): GraphQLRequestListener | void{
appInsightsClient.trackMetric({name: "apollo-query", value: 1});
return this;
},
// Fires for graph exceptions
didEncounterErrors: function(requestContext:GraphQLRequestContext) {
appInsightsClient.trackMetric({name: "apollo-error", value: 1});
appInsightsClient.trackException({exception: new Error("Apollo Error")});
appInsightsClient.trackException({exception: {category:"Apollo Error", details: requestContext.errors}});
}
}
Add the plugin to Apollo Server
azure-quickstart/data-access/graphql/index.ts
const server = new ApolloServer({
...
plugins: [
appInsightsPlugin
],
...
});