Search code examples
javascriptnode.jsazureazure-functionsazure-application-insights

Why my azure function is not logging errors in Application Insights?


My functions are working fine, but when I try to handle errors and log them using the "context.error", they are not being sent to Applications Insights, only the requests are being registered. Shouldn't the "context.error" log the error straight to App Insights? Am I missing something?

Here's my Error Handler function:

module.exports = function handleError(context, error) {
  context.error(error);

  let isInternalError = error.statusCode === 500 || error.code === 500 || typeof error.code !== "number";
  let status = isInternalError ? 500 : error.statusCode || error.code || 500;
  let errorMessage = error.message;
  let errorsList = [];
  
  if (error.name === "ValidationError") {
    isInternalError = false;
    status = 400;
    errorsList = Object.keys(error.errors).map(key => error.errors[key].message);
    errorMessage = "Validation Error";
  }

  return {
    status,
    jsonBody: {
      errorMessage: isInternalError ? 'Internal Server Error' : errorMessage,
      errorsList,
      errorStack: process.env.ENVIRONMENT !== "prod" ? error.stack : undefined
    }
  };
}

Thank you!


Solution

  • Shouldn't the "context.error" log the error straight to App Insights?

    You need to initialize telemetry client before calling context.error method. You can refer to this Ms Docs for info.

    In order to log the errors in Application Insights, I have added the following lines of code in your existing code.

    const  appInsights  =  require("applicationinsights");
    appInsights.setup(process.env.APPLICATIONINSIGHTS_CONNECTION_STRING).start();
    module.exports  =  function  handleError(context) {
    appInsights.defaultClient.trackException({ exception:  error });
    context.error(error);
    

    Output:

    enter image description here

    I can see the logs in application insights as well

    enter image description here