How to Integrate Flutter App with Azure Application Insights

Abraham Aditya
Bina Nusantara IT Division
7 min readJun 29, 2023

At present, there are many applications that are integrated with various tools, one of which is analytics tools. Analytics tools help us collect, organize, and analyze data efficiently, allowing us to make smarter strategic decisions that align with our desired business goals.

One of the commonly used analytics tools in existing applications today is Azure Application Insights. Azure Application Insights is a service provided by Microsoft Azure for monitoring and analyzing the performance of applications and web services. It is a specialized analytics tool designed to assist developers and operational teams in understanding and improving the quality and performance of the applications they build.

In this opportunity, I would like to share the steps to integrate a Flutter app with Azure Application Insights.

Step 1: Installing Library

Please note that in the provided Azure documentation, it states that Flutter is not natively supported, and therefore, we cannot integrate it automatically or manually as per the Azure documentation instructions.

Then, the solution is to use the public library created by Kent Boogaart, available on pub.dev, which is the official package repository for Dart and Flutter apps.

To install it, you can run this command:

  • Run this command in your terminal.
$ flutter pub add azure_application_insights
  • Automatically, the system will add a line like this to the pubspec.yaml file.
dependencies:
azure_application_insights: ^3.1.0
  • Import it into your Dart file’s code.
import 'package:azure_application_insights/azure_application_insights.dart';

Step 2: Code Declaration

  • First things first, assign the Instrumentation Key available in your Azure Application Insights to a specific variable.
import 'package:http/http.dart';
import 'package:azure_application_insights/azure_application_insights.dart';

const instrumentationKey = String.fromEnvironment("PUT INSTRUMENTATION_KEY HERE");

The Instrumentation Key can be found in the Azure Portal under Azure Services > Application Insights > [Your Application Insights Name].

Figure 1. Overview Menu on Azure Application Insights
  • After that, we can proceed with the initial setup by creating the getProcessor() function as a required function to execute the subsequent functions that we will install.
import 'package:http/http.dart';
import 'package:azure_application_insights/azure_application_insights.dart';

const instrumentationKey = String.fromEnvironment("PUT INSTRUMENTATION_KEY HERE");

final client = Client();
BufferedProcessor getProcessor() {
return BufferedProcessor(
next: TransmissionProcessor(
instrumentationKey: instrumentationKey,
httpClient: client,
timeout: const Duration(seconds: 10), // it can be modified according to your needs.
),
);
}

Step 3: Code Implementation

There are several function methods that have been provided and can be used, including:

  • trackEvent() → Used to track custom events.
void trackEvent({
required String name,
Map<String, Object> additionalProperties = const <String, Object>{},
DateTime? timestamp,
})
  • trackPageView() → Used to track the page views that users access.
void trackPageView({
required String name,
String? id,
Duration? duration,
String? url,
Map<String, Object> additionalProperties = const <String, Object>{},
DateTime? timestamp,
})
  • trackRequest() → Used to track and log HTTP requests.
void trackRequest({
required String id,
required Duration duration,
required String responseCode,
String? source,
String? name,
bool? success,
String? url,
Map<String, Object> additionalProperties = const <String, Object>{},
DateTime? timestamp,
})
  • trackTrace()→ Used to track custom traces or log messages.
void trackTrace({
required Severity severity,
required String message,
Map<String, Object> additionalProperties = const <String, Object>{},
DateTime? timestamp,
})
  • trackError() → Used to track and log errors or exceptions.
void trackError({
required Severity severity,
required Object error,
StackTrace? stackTrace,
String? problemId,
Map<String, Object> additionalProperties = const <String, Object>{},
DateTime? timestamp,
})

Let’s create an example implementation for each function method:

  • trackEvent()
    This function method can be used to send information data for customizable event activities.
import 'package:http/http.dart';
import 'package:azure_application_insights/azure_application_insights.dart';

const instrumentationKey = String.fromEnvironment("PUT INSTRUMENTATION_KEY HERE");

final client = Client();
BufferedProcessor getProcessor() {
return BufferedProcessor(
next: TransmissionProcessor(
instrumentationKey: instrumentationKey,
httpClient: client,
timeout: const Duration(seconds: 10),
),
);
}

// trackEvent()
Future customEvent() async {
try {
final processor = getProcessor();
final telemetryClient = TelemetryClient(
processor: processor,
);

// telemetryClient.context contains data about the user performing the activity.
// in telemetryClient.context, we can send comprehensive information (user, session, operation, location, device, cloud, and application version) to Azure Application Insights.
telemetryClient.context.user.accountId = "PUT ACCOUNT_ID HERE";
telemetryClient.context.session.sessionId = "PUT SESION_ID HERE";

// telemetryClient.track...() is the function method that can be used to execute trackEvent().
telemetryClient.trackEvent(
name: 'PUT CUSTOM_EVENT_NAME',
additionalProperties: {
"PUT KEY 1 HERE" : "PUT VALUE 1 HERE",
"PUT KEY 2 HERE" : "PUT VALUE 2 HERE",
}
);

await telemetryClient.flush();
client.close();

} on Object catch (e) {
print('Sending telemetry failed. $e');
}
}
  • trackPageView()
    This function method can be used to send information to Azure Application Insights when a user accesses a specific page.
import 'package:http/http.dart';
import 'package:azure_application_insights/azure_application_insights.dart';

const instrumentationKey = String.fromEnvironment("INSTRUMENTATION_KEY");

final client = Client();
BufferedProcessor getProcessor() {
return BufferedProcessor(
next: TransmissionProcessor(
instrumentationKey: instrumentationKey,
httpClient: client,
timeout: const Duration(seconds: 10),
),
);
}

// trackPageView()
Future pageView() async {
try {
final processor = getProcessor();
final telemetryClient = TelemetryClient(
processor: processor,
);

// telemetryClient.context contains data about the user performing the activity.
// in telemetryClient.context, we can send comprehensive information (user, session, operation, location, device, cloud, and application version) to Azure Application Insights.
telemetryClient.context.user.accountId = "PUT ACCOUNT_ID HERE";
telemetryClient.context.session.sessionId = "PUT SESION_ID HERE";

// telemetryClient.track...() is the function method that can be used to execute trackPageView().
telemetryClient.trackPageView(
id: "PUT ID HERE",
name: "PUT PAGE_NAME HERE",
url: "PUT URL_ADDRESS HERE",
duration: const Duration(minutes: PUT_DURATION_HERE),
timestamp: DateTime(PUT_DATETIME_HERE),
additionalProperties: {
"PUT KEY 1 HERE" : "PUT VALUE 1 HERE",
"PUT KEY 2 HERE" : "PUT VALUE 2 HERE",
}
);

await telemetryClient.flush();
client.close();

} on Object catch (e) {
print('Sending telemetry failed. $e');
}
}
  • trackRequest()
    This function method can be used to send request information to Azure Application Insights for the purpose of tracking user-requested payloads for a specific service.
import 'package:http/http.dart';
import 'package:azure_application_insights/azure_application_insights.dart';

const instrumentationKey = String.fromEnvironment("INSTRUMENTATION_KEY");

final client = Client();
BufferedProcessor getProcessor() {
return BufferedProcessor(
next: TransmissionProcessor(
instrumentationKey: instrumentationKey,
httpClient: client,
timeout: const Duration(seconds: 10),
),
);
}

// trackRequest()
Future request() async {
try {
final processor = getProcessor();
final telemetryClient = TelemetryClient(
processor: processor,
);

// telemetryClient.context contains data about the user performing the activity.
// in telemetryClient.context, we can send comprehensive information (user, session, operation, location, device, cloud, and application version) to Azure Application Insights.
telemetryClient.context.user.accountId = "PUT ACCOUNT_ID HERE";
telemetryClient.context.session.sessionId = "PUT SESION_ID HERE";

// telemetryClient.track...() is the function method that can be used to execute trackRequest().
telemetryClient.trackRequest(
id: "PUT ID HERE",
name: "PUT PAGE_NAME HERE",
source: "PUT SOURCE HERE",
url: "PUT URL_ADDRESS HERE",
responseCode: "PUT RESPONSE_CODE HERE",
success: true, // boolean value (true or false)
duration: const Duration(minutes: PUT_THE_DURATION_HERE),
timestamp: DateTime(PUT_DATETIME_HERE),
additionalProperties: {
"PUT KEY 1 HERE" : "PUT VALUE 1 HERE",
"PUT KEY 2 HERE" : "PUT VALUE 2 HERE",
}
);

await telemetryClient.flush();
client.close();

} on Object catch (e) {
print('Sending telemetry failed. $e');
}
}
  • trackTrace()
    This function method can be used to send messages or report the status of messages related to specific activities performed by the user.
import 'package:http/http.dart';
import 'package:azure_application_insights/azure_application_insights.dart';

const instrumentationKey = String.fromEnvironment("INSTRUMENTATION_KEY");

final client = Client();
BufferedProcessor getProcessor() {
return BufferedProcessor(
next: TransmissionProcessor(
instrumentationKey: instrumentationKey,
httpClient: client,
timeout: const Duration(seconds: 10),
),
);
}

// trackTrace()
Future trace() async {
try {
final processor = getProcessor();
final telemetryClient = TelemetryClient(
processor: processor,
);

// telemetryClient.context contains data about the user performing the activity.
// in telemetryClient.context, we can send comprehensive information (user, session, operation, location, device, cloud, and application version) to Azure Application Insights.
telemetryClient.context.user.accountId = "PUT ACCOUNT_ID HERE";
telemetryClient.context.session.sessionId = "PUT SESION_ID HERE";

// telemetryClient.track...() is the function method that can be used to execute trackTrace().
telemetryClient.trackTrace(
message: "PUT THE MESSAGE HERE",
severity: Severity.warning, // There are several options for the severity parameter, including (critical, error, information, verbose, warning, and values).
timestamp: DateTime(PUT_DATETIME_HERE),
additionalProperties: {
"PUT KEY 1 HERE" : "PUT VALUE 1 HERE",
"PUT KEY 2 HERE" : "PUT VALUE 2 HERE",
}
);

await telemetryClient.flush();
client.close();

} on Object catch (e) {
print('Sending telemetry failed. $e');
}
}
  • trackError()
    This function method can be used to send reports that are specifically designated for errors.
import 'package:http/http.dart';
import 'package:azure_application_insights/azure_application_insights.dart';

const instrumentationKey = String.fromEnvironment("INSTRUMENTATION_KEY");

final client = Client();
BufferedProcessor getProcessor() {
return BufferedProcessor(
next: TransmissionProcessor(
instrumentationKey: instrumentationKey,
httpClient: client,
timeout: const Duration(seconds: 10),
),
);
}

// trackError()
Future error() async {
try {
final processor = getProcessor();
final telemetryClient = TelemetryClient(
processor: processor,
);

// telemetryClient.context contains data about the user performing the activity.
// in telemetryClient.context, we can send comprehensive information (user, session, operation, location, device, cloud, and application version) to Azure Application Insights.
telemetryClient.context.user.accountId = "PUT ACCOUNT_ID HERE";
telemetryClient.context.session.sessionId = "PUT SESION_ID HERE";

// telemetryClient.track...() is the function method that can be used to execute trackError().
telemetryClient.trackError(
problemId: "PUT THE PROBLEM_ID HERE",
error: "PUT THE ERROR_MESSAGE HERE",
severity: Severity.error, // there are several options for the severity parameter, including (critical, error, information, verbose, warning, and values).
stackTrace: StackTrace.current,
timestamp: DateTime(PUT_DATETIME_HERE),
additionalProperties: {
"PUT KEY 1 HERE" : "PUT VALUE 1 HERE",
"PUT KEY 2 HERE" : "PUT VALUE 2 HERE",
}
);

await telemetryClient.flush();
client.close();

} on Object catch (e) {
print('Sending telemetry failed. $e');
}
}

Closing

After creating each function method, they can be used by invoking each respective function method. The above function methods are just simple examples and can be created, adjusted, and improved according to specific needs. For a complete documentation explanation regarding the library, you can refer to this.

Special credit to Kent Boogaart and all contributors.

References

https://pub.dev/packages/azure_application_insights
https://learn.microsoft.com/en-us/azure/azure-monitor/app/opentelemetry-overview

--

--