kubesense_flutter_plugin 1.0.1
kubesense_flutter_plugin: ^1.0.1 copied to clipboard
Flutter bindings and tools for utilizing Kubesense Mobile SDks
Overview #
Kubesense Real User Monitoring (RUM) enables you to visualize and analyze the real-time performance and user journeys of your Flutter application’s individual users.
The Kubesense Flutter plugin supports Flutter 3.27+.
For complete documentation, see the official Kubesense documentation.
Current Kubesense SDK Versions #
| iOS SDK | Android SDK | Browser SDK |
|---|---|---|
| 1.0.0 | 2.1.0 | v7 (2.0.0) |
iOS #
Your iOS Podfile must have use_frameworks! (which is true by default in Flutter) and target iOS version >= 15.0.
Android #
On Android, your minSdkVersion must be >= 23, and if you are using Kotlin, it should be version >= 2.1.0.
The plugin depends on the Kubesense Android SDK, published through
Sonatype Central under the ai.kubesense
group. Gradle resolves release artifacts with mavenCentral(); no custom
Kubesense Maven repository is required. If settings.gradle sets
repositoriesMode to FAIL_ON_PROJECT_REPOS, ensure Maven Central is listed
there:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
}
}
Web #
The Flutter plugin uses the Kubesense browser SDK from npm, loaded before Flutter starts. The Dart
bridge initializes RUM through the window.KUBESENSE_SDK global it registers.
-
From your Flutter project folder, install the browser SDK and a bundler:
npm init -y # only if you don't have a package.json yet npm install @kubesense/kubesense-browser-rum-slim@1.8.0 npm install --save-dev esbuild -
Create
web/kubesense-browser-entry.js. Importing the package registerswindow.KUBESENSE_SDK:import '@kubesense/kubesense-browser-rum-slim'; -
Bundle it into
web/:npx esbuild web/kubesense-browser-entry.js --bundle --format=iife --outfile=web/kubesense-browser.js -
In
web/index.html, load the bundle beforeflutter_bootstrap.js(orflutter.js):<script src="kubesense-browser.js"></script> -
If your site has a Content Security Policy, allow
connect-src https://<collector host>.
Don't initialize the browser SDK yourself in JavaScript: the Flutter plugin does it.
Flutter web Logs additionally require window.KUBESENSE_LOGS. The public
@kubesense/kubesense-browser-logs npm package is currently unpublished, so
the Logs source must be confirmed before enabling web Logs. The upload
collector is chosen by the Dart configuration below.
Setup #
Use the Kubesense Flutter Plugin to set up Log Management or Real User Monitoring (RUM). The setup instructions may vary based on your decision to use Logs, RUM, or both, but most of the setup steps are consistent.
Create configuration object #
Create a configuration object for each Kubesense feature (such as Logs and RUM) with the following snippet. By not passing a configuration for a given feature, it is disabled.
// Determine the user's consent to be tracked
final trackingConsent = ...
final configuration = KubesenseConfiguration(
clientToken: '<CLIENT_TOKEN>',
env: '<ENV_NAME>',
kubesenseRumEndpoint: 'us2.kubesense.ai',
nativeCrashReportEnabled: true,
loggingConfiguration: KubesenseLoggingConfiguration(),
rumConfiguration: KubesenseRumConfiguration(
applicationId: '<RUM_APPLICATION_ID>',
)
);
For more information on available configuration options, see the KubesenseConfiguration object documentation.
Choose the collector #
kubesenseRumEndpoint is required: it is the host of the Kubesense collector, with an optional
port, and every feature (RUM, Logs, Session Replay and Flags) uploads to it. Use
us2.kubesense.ai for the production collector, or the host of a collector of your own:
final configuration = KubesenseConfiguration(
clientToken: '<CLIENT_TOKEN>',
env: '<ENV_NAME>',
kubesenseRumEndpoint: 'collector.example.com',
// ...
);
Data is always uploaded over https, to https://<host>/rum/api/v1/.... There is no site to
choose on any platform.
remoteConfigurationEnabled controls whether the configuration managed from the Kubesense
dashboard is applied. Left unset, each platform keeps its default: enabled on Android and iOS,
disabled on Web.
Initialize the library #
You can initialize RUM using one of two methods in the main.dart file.
-
Use
KubesenseSdk.runApp, which automatically sets up error reporting.await KubesenseSdk.runApp(configuration, () async { runApp(const MyApp()); }) -
Alternatively, you can manually set up error tracking and resource tracking. Because
KubesenseSdk.runAppcallsWidgetsFlutterBinding.ensureInitialized, if you are not usingKubesenseSdk.runApp, you need to call this method prior to callingKubesenseSdk.instance.initialize.
WidgetsFlutterBinding.ensureInitialized();
final originalOnError = FlutterError.onError;
FlutterError.onError = (details) {
FlutterError.presentError(details);
KubesenseSdk.instance.rum?.handleFlutterError(details);
originalOnError?.call(details);
};
final platformOriginalOnError = PlatformDispatcher.instance.onError;
PlatformDispatcher.instance.onError = (e, st) {
KubesenseSdk.instance.rum?.addErrorInfo(
e.toString(),
RumErrorSource.source,
stackTrace: st,
);
return platformOriginalOnError?.call(e, st) ?? false;
};
await KubesenseSdk.instance.initialize(configuration);
runApp(const MyApp());
Send Logs #
After initializing Kubesense with a KubesenseLoggingConfiguration, you can create an instance of a KubesenseLogger to send logs to Kubesense.
final logger = KubesenseSdk.instance.logs?.createLogger(
KubesenseLoggerConfiguration(
remoteLogThreshold: LogLevel.warning,
),
);
logger?.debug("A debug message.");
logger?.info("Some relevant information?");
logger?.warn("An important warning…");
logger?.error("An error was met!");
You can name loggers or customize their service:
final secondLogger = KubesenseSdk.instance.createLogger(
LoggingConfiguration({
service: 'my_app.additional_logger',
name: 'Additional logger'
})
);
secondLogger.info('Info from my additional logger.');
Tags and attributes set on loggers are local to each logger.
Track RUM views #
The Kubesense Flutter Plugin can automatically track named routes using the KubesenseNavigationObserver on your MaterialApp.
MaterialApp(
home: HomeScreen(),
navigatorObservers: [
KubesenseNavigationObserver(KubesenseSdk.instance),
],
);
This works if you are using named routes or if you have supplied a name to the settings parameter of your PageRoute.
Alternately, you can use the KubesenseRouteAwareMixin property in conjunction with the KubesenseNavigationObserverProvider property to start and stop your RUM views automatically. With KubesenseRouteAwareMixin, move any logic from initState to didPush.
Note that, by default, KubesenseRouteAwareMixin uses the name of the widget as the name of the View. However, this does not work with obfuscated code as the name of the Widget class is lost during obfuscation. To keep the correct view name, override rumViewInfo:
To rename your views or supply custom paths, provide a viewInfoExtractor callback. This function can fall back to the default behavior of the observer by calling defaultViewInfoExtractor. For example:
RumViewInfo? infoExtractor(Route<dynamic> route) {
var name = route.settings.name;
if (name == 'my_named_route') {
return RumViewInfo(
name: 'MyDifferentName',
attributes: {'extra_attribute': 'attribute_value'},
);
}
return defaultViewInfoExtractor(route);
}
var observer = KubesenseNavigationObserver(
kubesenseSdk: KubesenseSdk.instance,
viewInfoExtractor: infoExtractor,
);
class _MyHomeScreenState extends State<MyHomeScreen>
with RouteAware, KubesenseRouteAwareMixin {
@override
RumViewInfo get rumViewInfo => RumViewInfo(name: 'MyHomeScreen');
}
Automatic Resource Tracking #
You can enable automatic tracking of resources and HTTP calls from your RUM views using the Kubesense Tracking HTTP Client package. Add the package to your pubspec.yaml, and add the following to your initialization:
final configuration = KubesenseConfiguration(
// configuration
firstPartyHosts: ['example.com'],
)..enableHttpTracking()
In order to enable Kubesense Distributed Tracing, the KubesenseConfiguration.firstPartyHosts property in your configuration object must be set to a domain that supports distributed tracing. You can also modify the sampling rate for Kubesense distributed tracing by setting the traceSampleRate on your KubesenseRumConfiguration.
License #
Licensed under the Apache License, Version 2.0.