Flutter应用性能监控插件azure_application_insights的使用
Flutter应用性能监控插件azure_application_insights的使用
Azure Application Insights简介
Azure Application Insights 是一个强大的工具,用于理解你的软件系统是如何运作的。在Flutter应用程序的上下文中,它允许你深入了解用户交互、性能和应用程序中的故障。
如何使用?
安装与导入
首先,你需要安装azure_application_insights
包,然后将其导入到你的Dart代码中:
import 'package:azure_application_insights/azure_application_insights.dart';
配置TelemetryClient
要与Application Insights集成,唯一需要的信息是你的连接字符串,可以在Azure门户中的“概览”选项卡找到它。
一旦有了连接字符串,你可以构造一个TelemetryClient
实例,如下所示:
final processor = BufferedProcessor(
next: TransmissionProcessor(
connectionString: connectionString,
httpClient: client,
timeout: const Duration(seconds: 10),
),
);
final telemetryClient = TelemetryClient(
processor: processor,
);
这是一般的设置,其中遥测项在传输前会被缓冲。根据你的处理需求,可能需要在一个应用程序中拥有多个TelemetryClient
实例。例如,你可能有一个TelemetryClient
用于缓冲所有非错误遥测项,另一个不进行缓冲,专门用于尽快提交错误。
发送遥测数据
一旦创建了TelemetryClient
,可以通过调用各种方法来捕获遥测项:
telemetryClient.trackTrace(
severity: Severity.information,
message: 'Hello from Dart!',
);
还可以配置额外的属性与遥测项一起提交。这些属性可以在两个地方配置:
- 关联的
TelemetryContext
:这些属性将附加到通过该客户端提交的所有遥测项。 - 每个遥测项的方法参数:这些属性仅附加到特定的遥测项。
示例代码如下:
// 设置全局属性
telemetryClient.context
..applicationVersion = 'my version'
..device.type = 'Android'
..properties['environmentName'] = 'dev';
// 发送带有个别属性的遥测项
telemetryClient.trackTrace(
severity: Severity.information,
message: 'An example',
additionalProperties: {'answer': 42},
);
Flutter集成
为了在Flutter应用中提交崩溃信息作为遥测数据,可以使用以下代码片段:
void main() {
if (kReleaseMode) {
runWithCrashReporting(codeToExecute: run);
} else {
run();
}
}
void run() => runApp(MyApp());
Future<void> runWithCrashReporting({
required VoidCallback codeToExecute,
}) async {
FlutterError.onError = (details) => submitErrorAsTelemetry(
isFatal: true,
error: details.exception,
trace: details.stack,
);
runZonedGuarded(
codeToExecute,
(error, trace) => submitErrorAsTelemetry(
isFatal: true,
error: error,
trace: trace,
),
);
}
Future<void> submitErrorAsTelemetry({
required bool isFatal,
required Object error,
required StackTrace trace,
}) async {
try {
final telemetryClient = ...;
final errorProperties = ...;
telemetryClient.trackError(
error: error,
stackTrace: trace,
severity: isFatal ? Severity.critical : Severity.error,
additionalProperties: errorProperties,
);
if (isFatal) {
await telemetryClient.flush();
}
} on Object catch (e, t) {
debugPrintSynchronously('Sending error telemetry failed: $e\r\n$t');
debugPrintSynchronously('Original error: $error');
} finally {
if (isFatal && kReleaseMode) {
debugPrintSynchronously('Forcing exit');
}
}
}
HTTP中间件
对于HTTP请求,可以使用TelemetryHttpClient
自动记录依赖项遥测信息:
final telemetryHttpClient = TelemetryHttpClient(
telemetryClient: telemetryClient,
inner: Client(),
);
await telemetryHttpClient.get('https://example.com/');
示例完整代码
下面是一个完整的示例代码,展示了如何在Flutter应用中使用azure_application_insights
插件:
// ignore_for_file: cascade_invocations
import 'package:azure_application_insights/azure_application_insights.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
const connectionString = 'TODO'; // 替换为你的连接字符串
void main() {
if (kReleaseMode) {
runWithCrashReporting(codeToExecute: () => runApp(MyApp()));
} else {
runApp(MyApp());
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
sendTelemetry();
}
Future<void> sendTelemetry() async {
print('Sending telemetry...');
try {
final client = http.Client();
final processor = BufferedProcessor(
next: TransmissionProcessor(
connectionString: connectionString,
httpClient: client,
timeout: const Duration(seconds: 10),
),
);
final telemetryClient = TelemetryClient(
processor: processor,
);
telemetryClient.context
..applicationVersion = 'example'
..user.id = 'somebody'
..properties['custom'] = 'a custom property value';
telemetryClient.trackTrace(
severity: Severity.information,
message: 'Hello from Dart!',
);
telemetryClient.trackTrace(
severity: Severity.verbose,
message: 'Here is a trace with additional properties',
additionalProperties: {'answer': 42},
);
telemetryClient.trackEvent(
name: 'started',
additionalProperties: {
'timestamp': DateTime.now().toUtc().toIso8601String(),
},
);
final telemetryHttpClient = TelemetryHttpClient(
telemetryClient: telemetryClient,
inner: client,
);
await telemetryHttpClient.get(Uri.parse('https://example.com/'));
await telemetryClient.flush();
client.close();
print('...sent!');
} on Object catch (e) {
print('...failed! $e');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Future<void> runWithCrashReporting({
required VoidCallback codeToExecute,
}) async {
FlutterError.onError = (details) => submitErrorAsTelemetry(
isFatal: true,
error: details.exception,
trace: details.stack,
);
runZonedGuarded(
codeToExecute,
(error, trace) => submitErrorAsTelemetry(
isFatal: true,
error: error,
trace: trace,
),
);
}
Future<void> submitErrorAsTelemetry({
required bool isFatal,
required Object error,
required StackTrace trace,
}) async {
try {
final telemetryClient = ...; // 获取TelemetryClient实例
final errorProperties = ...; // 获取任何其他属性
telemetryClient.trackError(
error: error,
stackTrace: trace,
severity: isFatal ? Severity.critical : Severity.error,
additionalProperties: errorProperties,
);
if (isFatal) {
await telemetryClient.flush();
}
} on Object catch (e, t) {
debugPrintSynchronously('Sending error telemetry failed: $e\r\n$t');
debugPrintSynchronously('Original error: $error');
} finally {
if (isFatal && kReleaseMode) {
debugPrintSynchronously('Forcing exit');
}
}
}
通过上述步骤,你可以在Flutter应用中成功集成并使用azure_application_insights
插件进行性能监控。
更多关于Flutter应用性能监控插件azure_application_insights的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter应用性能监控插件azure_application_insights的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter应用中使用 azure_application_insights
插件来进行性能监控,可以帮助你收集和分析应用运行时的数据。以下是一个基本的代码示例,展示了如何集成和使用 azure_application_insights
插件。
步骤 1: 添加依赖
首先,你需要在 pubspec.yaml
文件中添加 azure_application_insights
插件的依赖:
dependencies:
flutter:
sdk: flutter
azure_application_insights: ^x.y.z # 请替换为最新版本号
然后运行 flutter pub get
来获取依赖。
步骤 2: 初始化 Application Insights
在你的 Flutter 应用的入口文件(通常是 main.dart
)中,初始化 Application Insights 客户端:
import 'package:flutter/material.dart';
import 'package:azure_application_insights/azure_application_insights.dart';
void main() {
// 替换为你的 Application Insights Instrumentation Key
const instrumentationKey = 'your-instrumentation-key-here';
// 初始化 Application Insights 客户端
ApplicationInsights.configure(instrumentationKey: instrumentationKey);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Application Insights Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Click the button to track an event.',
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () {
_trackEvent('button_clicked');
},
child: Text('Track Event'),
),
],
),
),
);
}
void _trackEvent(String eventName) {
// 跟踪自定义事件
ApplicationInsights.trackEvent(
name: eventName,
properties: <String, String>{
'category': 'user_interaction',
},
);
}
}
步骤 3: 跟踪其他类型的数据
除了自定义事件,你还可以跟踪页面视图、异常、依赖项调用等。以下是几个示例:
跟踪页面视图
@override
void initState() {
super.initState();
// 跟踪页面视图
ApplicationInsights.trackPageView(
name: 'HomeScreen',
);
}
跟踪异常
try {
// 可能会抛出异常的代码
} catch (error, stackTrace) {
// 跟踪异常
ApplicationInsights.trackException(
exception: error,
stackTrace: stackTrace,
properties: <String, String>{
'error_type': 'unexpected',
},
);
}
跟踪依赖项调用(例如 API 请求)
void _fetchData() async {
try {
// 模拟 API 请求
await Future.delayed(Duration(seconds: 2));
// 跟踪成功的依赖项调用
ApplicationInsights.trackDependency(
type: 'HTTP',
target: 'https://api.example.com/data',
data: 'GET',
duration: 2000, // 持续时间,单位为毫秒
success: true,
resultCode: '200',
);
} catch (error, stackTrace) {
// 跟踪失败的依赖项调用
ApplicationInsights.trackDependency(
type: 'HTTP',
target: 'https://api.example.com/data',
data: 'GET',
duration: 2000, // 持续时间,单位为毫秒
success: false,
resultCode: '500',
properties: <String, String>{
'error_message': error.toString(),
},
);
}
}
通过上述代码,你可以在 Flutter 应用中集成 azure_application_insights
插件,并跟踪各种性能数据和用户交互事件。请确保替换示例代码中的 instrumentationKey
和其他占位符为你的实际值。