I am using Strapi (which is built on top of Koa) for my CMS. I have added a middleware which is triggered on every request to the server. This middleware initializes appInsights.
I am able to get trace logs from the code below, but for the life of me I do not get any request results. I've used the key for the same AppInsights resource on the Nuxt SPA which gets its data from this Strapi backend, and for this, I can see all the requests made. So the resource should be set up right.
This is the code for the middleware. All the trace messages and console logs are registering as expected.
const appInsights = require('applicationinsights');
module.exports = () => {
let isInit = false;
return {
initialize: function(cb) {
strapi.app.use(async (ctx, next) => {
if (!isInit) {
appInsights.setup().start();
appInsights.defaultClient.trackTrace({
message: 'STRAPI: trace on init'
});
console.log('app insights setup');
isInit = true;
}
await next();
appInsights.defaultClient.trackNodeHttpRequest({
request: ctx.request,
response: ctx.response
});
appInsights.defaultClient.trackTrace({
message: 'STRAPI: trace on all http calls'
});
console.log('track node http request');
});
cb();
}
};
};
You have to put your
appInsights.setup().start();
appInsights.defaultClient.trackTrace({
message: 'STRAPI: trace on init'
});
console.log('app insights setup');
outside your strapi.app.use
module.exports = () => {
return {
initialize: function(cb) {
appInsights.setup().start();
appInsights.defaultClient.trackTrace({
message: 'STRAPI: trace on init'
});
console.log('app insights setup');
strapi.app.use(async (ctx, next) => {
await next();
appInsights.defaultClient.trackNodeHttpRequest({
request: ctx.request,
response: ctx.response
});
appInsights.defaultClient.trackTrace({
message: 'STRAPI: trace on all http calls'
});
console.log('track node http request');
});
cb();
}
};
};
With this way your start
will be called one time when the server start.