How to use Azure application insight in Typescript

357 views Asked by At

How to use Azure application insight in Typescript .The already available solutions are for Angular which isn't working for me.

I tried the solution for angular , it didn't work. i used a 3rd party tool as well. it didn't work.

1

There are 1 answers

2
Pavan On

How to use Azure application insight in Typescript

I created a sample TypeScript application using the commands below.

npm init -y
npm install typescript --save-dev 
npx tsc --init

I have installed the required packages below:

npm install applicationinsights --save
npm install @types/applicationinsights --save-dev

Using the code below, configure Application Insights with the AppInsights instrumentation key.

Code:

import * as appInsights from 'applicationinsights';

appInsights.setup('b607ca1b-7bd2-4682-b93d-a2d911cf03e9').start();

function trackEvent() {
  const client = appInsights.defaultClient;
  const telemetry = { name: 'Custom Event', properties: { key: 'value' } };
  client.trackEvent(telemetry);
  client.flush();

  console.log('Telemetry data sent - Event:', telemetry);
}

function trackTrace() {
  const client = appInsights.defaultClient;
  const message = 'This is a sample trace message.';
  client.trackTrace({ message });
  client.flush(); 

  console.log('Telemetry data sent - Trace:', message);
}

function trackMetric() {
  const client = appInsights.defaultClient;
  const metricName = 'Custom Metric';
  const value = Math.floor(Math.random() * 100); 
  client.trackMetric({ name: metricName, value });
  client.flush(); 

  console.log('Telemetry data sent - Metric:', metricName, value);
}

trackEvent();
trackTrace();
trackMetric();

Use the following commands to run this TypeScript application.

npx tsc
node app.js

enter image description here

Using the information below, you can find the AppInsights Instrumentation key:

enter image description here

Using the above code, a custom event and trace message were successfully sent to Application Insights. See below:

enter image description here

enter image description here