Flutter monitoring API

Instana Flutter agent API

The following section describes the usage of the Instana Flutter agent. You can use the Instana Flutter agent with the InstanaAgent class methods explained as follows:

Setup

To avoid certain actions not being tracked, initialize Instana in initState() of app state class as early as possible by using the following command:

static Future<void> setup({@required String key, @required String reportingUrl}) async

Parameters

Parameter
Description
key (String) The monitoring configuration key of Instana.
reportingURL (String) The URL pointing to the Instana instance to which the monitoring data is sent.
options (SetupOptions, optional) Configuration options (such as collectionEnabled).

Example

@override
void initState() {
  super.initState();
  setupInstana();
}
Future<void> setupInstana() async {
    await InstanaAgent.setup(key: 'Your-Instana-Key', reportingUrl: 'Your-Instana-Reporting-URL', null);

    // Alternatively with configuration options
    var options = SetupOptions();
    options.collectionEnabled = false;
    await InstanaAgent.setup(key: 'Your-Instana-Key', reportingUrl: 'Your-Instana-Reporting-URL', options: options);
}

Supported Dart and Flutter version

Currently, all Dart SDK 2.12.0 or later and all Flutter 1.20.0 and later are supported.

Enabled or Disable Collection

You can enable the data collection at any time during the runtime. If you call Instana.setup API without enabling the data collection, and later enabling the data collection enables the delayed start of the data collection (For example, after user consent).

Property Description Type
setCollectionEnabled Flag to enable or disable data collection. Boolean

Example

InstanaAgent.setCollectionEnabled(true);

Error handling

All the Instana agent's (Android-agent and iOSAgent) interfaces return an asynchronous Future. Errors are wrapped in an exception to the PlatformException type.

You are advised to follow the common error-handling techniques for Futures and to log possible errors.

For example:

InstanaAgent.setup(key: 'KEY', reportingUrl: 'REPORTING_URL')
    .catchError((e) => 
            log("Captured PlatformException during Instana setup: $e")
        );

Similarly, in async functions:

try {
  var result = await InstanaAgent.setup(key: 'KEY', reportingUrl: 'REPORTING_URL');
} catch (e) {
  log("Captured PlatformException during Instana setup: $e");
}

Session identifier

Each Instana agent (Android-agent and iOSAgent) instance has a unique session identifier that you can use for other purposes in your app.

static Future<String> getSessionID() async

Return

Future<String>

Example

var sessionID = await Instana.getSessionID();

Manual HTTP monitoring

HTTP sessions must be captured manually by using Flutter. For more information, see the documentation specific to each platform.

static Future<Marker> startCapture({@required String url, @required String method, String viewName}) async

Parameters

Parameter
Description
url (URL) The URL to capture.
method (String) The HTTP method of the request.
viewName (String, optional) Optional name of the visible view that is related to this request.

Return

Future<Marker>

Example

final url = 'http://www.example.com/album'
var marker = await InstanaAgent.startCapture(url: url, method: 'GET', viewName: 'Album');

Set response details

When the response is finished, you can set the response size and the HTTP response status code on the Marker.

Set response size

marker.responseSizeHeader = 50; // Size of the HTTP header
marker.responseSizeBody = 1000; // Size of the http body
marker.responseSizeBodyDecoded = 2400; // // Size of the decoded http body

Set an HTTP response status code

marker.responseStatusCode = 200; // The http status code 

Set response headers

Note: The headers that are provided here are filtered by Instana based on your setCaptureHeaders setting.

marker.responseHeaders = response.headers;

Set Instana backend tracing ID

Instana backend tracing ID is the identifier to create a backend trace for the HTTP request and response. This identifier is provided in the HTTP header field server-timing. For example, server-timing: intid;desc=be01a91da80e33.

marker.backendTracingID = 'be01a91da80e33'; // the backend tracing id

To extract a response's backend tracing ID, use the BackendTracingIDParser helper class as shown:

var Map<String,String> headers = getResponseHeaders(); // You need to get this map from your `response` object
var backendTracingID = BackendTracingIDParser.fromHeadersMap(headers);

Set an error message

For a failing HTTP request, you can set an arbitrary error message.

marker.errorMessage = 'Download of album failed'; // the backend tracing id

Finish HTTP Capture

After you set the response details, you must call finish on the Marker to finalize the capture as shown in the following command:

marker.finish();

Cancel HTTP Capture

You can also cancel the pending Marker by using the following command:

marker.cancel();

Views

Instana can segment mobile app insights by logical views. To do so, set the view name through the InstanaAgent.setView(String) method. The view is then associated to all monitored beacons until the view changes when you call setView again.

Using readable names to define views, such as product detail page or payment selection instead of technical or generic names, such as the Class (for example, WebViewActivity) allows the team members without intimate knowledge of the codebase to understand the insights provided.

Note: InstanaAgent.setView(String) must be called when a screen is presented to the user, rather than when a screen is created (as in a Fragment, which can be created once but shown multiple times). Setting the view name enables Instana to track page transitions in addition to page loads.

static Future<void> setView(String name) async

Parameters

Parameter
Description
name (String) The name of the view.

Example

await InstanaAgent.setView('Webview: FitBit authorization');

Identifying users

User-specific information can optionally be sent with data that is transmitted to Instana. The information can then be used to unlock more capabilities, such as:

  • Calculate the number of users affected by errors
  • Filter data for specific users
  • See which user initiated a view change or HTTP request

By default, Instana does not associate any user-identifiable information to beacons.

Important: Be aware of the respective data protection laws if you choose to associate any user-identifiable information to beacons.

Identify users by using a user ID to keep the users unique. For Instana, user ID is a transparent String that is used only to calculate certain metrics. userName and userEmail can also be used to have access to more filters and a more pleasant presentation of user information.

In cases in which you are handling anonymous users and thus don't have access to user IDs you can alternatively use session IDs. Session IDs are not as helpful as user IDs to filter data, but they are a good indicator to calculate affected or unique user metrics. Set a username, such as Anonymous to have a clear differentiation between authenticated and unauthenticated users. Session IDs can be sensitive data (depending on the framework or platform used). Consider hashing session IDs to avoid transmitting data to Instana that can grant access.

Important: Data that is already transmitted to the Instana backend cannot be retroactively updated. For this reason, it is important to call the following APIs as early as possible in the app launch process.

static Future<void> setUserID(String userID) async
static Future<void> setUserName(String name) async
static Future<void> setUserEmail(String email) async

Parameters

Parameter
Description
id (String) An identifier for the user.
email (String) The user's email address.
name (String) The user's name.

Example

@override
void initState() {
  super.initState();

  await InstanaAgent.setup(key: 'Your-Instana-Key', reportingUrl: 'Your-Instana-Reporting-URL');
  await InstanaAgent.setUserID('1234567890');
  await InstanaAgent.setUserName('John Appleseed');
  await InstanaAgent.setUserEmail('john@appleseed.com');
}

Metadata

Arbitrary can optionally be attached to all data that is transmitted to Instana. Consider using the metadata to track UI configuration values, settings, feature flags, and any additional context that might be useful for analysis.

Note: Instana currently supports up to 50 meta key or value pairs.

static Future<void> setMeta({@required String key, @required String value}) async

Parameters

Parameter
Description
value (String) The value of the key-value pair you want to add as metadata.
key (String) The key of the key-value pair you want to add as metadata.

Example

await InstanaAgent.setMeta(key: 'exampleKey', value: 'Some Value');

Report custom events

Custom events enable reporting about non-standard activities, important interactions, and custom timings to Instana. Reporting of these events can be helpful when you analyze uncaught errors (breadcrumbs) and track more performance metrics.

static Future<void> reportEvent({@required String name, EventOptions options}) async

Parameters

Parameter
Description
name (String) Defines what kind of event happened in your app that might result in the transmission of a custom beacon.
options (EventOptions, optional) A timestamp in milliseconds since Epoch indicating at which time the event started. Falls back to now() - duration when not defined.

EventOptions

Parameter
Description
startTime (int) A timestamp in milliseconds since Epoch indicating at which time the event started. Falls back to now() - duration when not defined.
duration (int) The duration in milliseconds of how long the event lasted. The default is zero.
viewName (String) You can pass a String to group the request to a view. If you send nil explicitly, the viewName is ignored. Alternatively, you can leave out the parameter viewName to use the current view name that you set in setView(String).
meta (Map<String, String>) A JavaScript object with string values, which can be used to send metadata to Instana just for this singular event. In contrast to the usage of the metadata API, this metadata is not included in subsequent beacons.
backendTracingID (String) Identifier to create a backend trace for this event.
customMetric (double) Custom metric data with precision up to 4 decimal places. Do not include sensitive information in this metric.

Example

await InstanaAgent.reportEvent(
      name: 'advancedCustomEvent',
      options: EventOptions()
        ..viewName = 'customViewName'
        ..startTime = DateTime.now().millisecondsSinceEpoch
        ..duration = 3 * 1000
        ..meta = {
          'customKey1': 'customValue1',
          'customKey2': 'customValue2'
        }
        ..customMetric: 123.4567);

Capture HTTP headers

Optionally, the Instana agent can capture the HTTP headers of every tracked request or response.

A list of regex patterns can be defined to determine which headers are captured.

If the same header name is present in both the request and its response, only the response's header value is kept.

static Future<void> setCaptureHeaders({@required List<String> regex}) async

Example

InstanaAgent.setCaptureHeaders(regex: [
      'x-ratelimit-limit',
      'x-ratelimit-remaining',
      'x-ratelimit-reset'
    ]);

Redact URL Query parameters

Query parameters in collected URLs might contain sensitive data. Therefore, the Instana agent supports the specification of regex patterns for query parameter keys whose values need to be redacted. Any value that needs to be redacted is replaced with the string <redacted>. The redaction happens within the Instana agent before the agent reports to the Instana backend. Therefore, secrets do not reach the Instana backend for processing and are not available for analysis in the Instana UI or can be retrieved by using the Instana API.

By default, the Instana agent is configured with a list of three regex patterns to automatically redact the query parameter values for the keys "password", "key", and "secret".

static Future<void> redactHTTPQuery({@required List<String> regex}) async

Example

InstanaAgent.redactHTTPQuery(regex: [
      'user',
      'id',
      'key'
    ]);

Native HTTP monitoring

Though by default HTTP monitoring is disabled, you can capture the HTTP calls made inside the iOS platform (in Swift or Objective-C language) and Android platform (in Kotlin or Java language).

Example

@override
void initState() {
  super.initState();
  setupInstana();
}
Future<void> setupInstana() async {
  var options = SetupOptions(captureNativeHttp: true);
  await InstanaAgent.setup(key: 'Your-Instana-Key', reportingUrl: 'Your-Instana-Reporting-URL', options: options);
  if (!ret) {
    // Error handling here
    if (kDebugMode) {
      print("InstanaAgent setup failed");
    }
  }
}

Automatic HTTP monitoring

HTTP sessions that are made in the Dart language can be captured automatically. Set your HttpOverrides.global property as shown in the following example:

Example

@override
void main() {
  HttpOverrides.global = InstanaHttpOverrides();
  runApp(const MyApp());
}

If you already have your own version of HttpOverrides class for other purposes, then merge the InstanaHttpOverrides class function to your class and maintain the combined class yourself. Combining multiple HttpOverrides classes causes an error. You can also analyze the InstanaHttpOverrides class, and create your HttpOverrides class similar to InstanaHttpOverrides class instead of using the InstanaHttpOverrides() function.

Slow sending mode

The slow sending mode feature is disabled by default. If required, you can enable this feature.

By default, if a beacon sending fails, the Instana agent tries to resend the beacon until the sending is successful. Resending the beacon doesn't work well with some cellular networks. By enabling the slow sending mode feature, the beacon sending interval is changed to the time value that is assigned to the slowSendIntervalMillis parameter. Each beacon sending consists of only one beacon instead of a batch (maximum 100 beacons in a batch). The Instana agent stays in slow sending mode until one beacon is sent successfully.

The valid time range for slowSendIntervalMillis is 2–3600 seconds.

Example

@override
void initState() {
  super.initState();
  setupInstana();
}
Future<void> setupInstana() async {
  var options = SetupOptions();
  options.slowSendInterval = 60.0;
  await InstanaAgent.setup(key: 'Your-Instana-Key', reportingUrl: 'Your-Instana-Reporting-URL', options: options);
  if (!ret) {
    // Error handling here
    if (kDebugMode) {
      print("InstanaAgent setup failed");
    }
  }
}

User session ID

By default, the user session is tracked, and the ID is a randomly generated Universally Unique Identifier (UUID). This ID remains unchanged while the app is installed. You can configure the expiration time of the user session ID by using the usiRefreshTimeIntervalInHrs parameter.

The following parameter values indicate the status of the user session ID:

  • Negative number: This value indicates that the user session ID never expires. The default value is -1.

  • Positive number: This value means that the user session ID is refreshed after the set time, that is, a new UUID is generated and used.

  • Zero: This value denoted by 0.0 means that the user session ID is disabled.

Example

@override
void initState() {
  super.initState();
  setupInstana();
}
Future<void> setupInstana() async {
  var options = SetupOptions();
  options.usiRefreshTimeIntervalInHrs = 24.0;
  await InstanaAgent.setup(key: 'Your-Instana-Key', reportingUrl: 'Your-Instana-Reporting-URL', options: options);
  if (!ret) {
    // Error handling here
    if (kDebugMode) {
      print("InstanaAgent setup failed");
    }
  }
}

Capture screen names automatically

(Public preview) You can capture screen names automatically by providing observers or go-routers to Instana based on the navigation strategy of your application.

If the base UI of your application is built with MaterialApp, CupertinoApp, or any similar base widget that includes navigatorObservers, then you can add InstanaScreenNameObserver() to the list of observers to capture screen names automatically, which initiates navigation tracking and collects screen names from the specified paths.

InstanaScreenNameObserver() supports three parameters to capture advanced screen names. When you provide the buildContext parameter, screen names are collected from the widget, widget title, or widget child if the route name is not specified. You can further customize your ScreenNameExtractor to capture screen names automatically and RouteFilter, which by default collects names from PageRoute.

If the base navigation of your application is managed by go_router, you can provide the router object to Instana by using InstanaGoRouteObserver(yourRouterObject). Instana then captures screen names from the navigation.

Example

MaterialApp(
    navigatorObservers: [
      InstanaScreenNameObserver(), /*Providing instana observer here*/
    ],
    title: "Title",
    theme: new ThemeData(
      ...,
      ...
    ),
    initialRoute: '/',
    routes: {
      // When navigating to the "/" route, build the FirstScreen widget.
      '/': (context) => FirstScreen(
            ...,
          ),
      // When navigating to the "/second" route, build the SecondScreen widget.
      '/second': (context) => const SecondScreen(),
  })

Parameters

Parameter
Description
buildContext (BuildContext, optional) Provides the build context from the root widget.
screenNameExtractor (ScreenNameExtractor, optional) Provides a ScreenNameExtractor object, which returns a string by applying the extractor mechanism. The default value is taken from the RouteSettings name.
routeFilter (RouteFilter, optional) By default, only PageRoutes are tracked. You can provide classes based on RouteFilter if needed.