Flutter崩溃报告与错误追踪插件sentry的使用

发布于 1周前 作者 songsunli 来自 Flutter

Flutter崩溃报告与错误追踪插件sentry的使用


Sentry SDK for Dart

package build pub likes popularity pub points
sentry build pub package likes popularity pub points

Pure Dart SDK used by any Dart application like AngularDart, CLI and Server.

Flutter

For Flutter applications there’s sentry_flutter which builds on top of this package. That will give you native crash support (for Android and iOS), release health, offline caching and more.

Usage

  1. Sign up for a Sentry.io account and get a DSN at Sentry.io.
  2. Follow the installing instructions on pub.dev.
  3. Initialize the Sentry SDK using the DSN issued by Sentry.io:
import 'package:sentry/sentry.dart';

Future<void> main() async {
  await Sentry.init(
    (options) {
      options.dsn = 'https://example@sentry.io/example';
    },
    appRunner: initApp, // Init your App.
  );
}

void initApp() {
  // your app code
}

Or, if you want to run your app in your own error zone runZonedGuarded:

import 'dart:async';

import 'package:sentry/sentry.dart';

Future<void> main() async {
  runZonedGuarded(() async {
    await Sentry.init(
      (options) {
        options.dsn = 'https://example@sentry.io/example';
      },
    );

    // Init your App.
    initApp();
  }, (exception, stackTrace) async {
    await Sentry.captureException(exception, stackTrace: stackTrace);
  });
}

void initApp() {
  // your app code
}

Breadcrumbs for HTTP Requests

The SentryHttpClient can be used as a standalone client like this:

import 'package:sentry/sentry.dart';

var client = SentryHttpClient();
try {
 var uriResponse = await client.post('https://example.com/whatsit/create',
     body: {'name': 'doodle', 'color': 'blue'});
 print(await client.get(uriResponse.bodyFields['uri']));
} finally {
 client.close();
}

The SentryHttpClient can also be used as a wrapper for your own HTTP Client:

import 'package:sentry/sentry.dart';
import 'package:http/http.dart' as http;

final myClient = http.Client();

var client = SentryHttpClient(client: myClient);
try {
var uriResponse = await client.post('https://example.com/whatsit/create',
     body: {'name': 'doodle', 'color': 'blue'});
 print(await client.get(uriResponse.bodyFields['uri']));
} finally {
 client.close();
}

Reporting Bad HTTP Requests as Errors

The SentryHttpClient can catch exceptions that may occur during requests such as SocketExceptions. This is currently an opt-in feature. The following example shows how to enable it.

Furthermore you can track HTTP requests which are considered bad by you. The following example shows how to do it. It captures exceptions for each request with a status code range from 400 to 404 and also for 500.

import 'package:sentry/sentry.dart';

var client = SentryHttpClient(
  failedRequestStatusCodes: [
    SentryStatusCode.range(400, 404),
    SentryStatusCode(500),
  ],
);

try {
var uriResponse = await client.post('https://example.com/whatsit/create',
     body: {'name': 'doodle', 'color': 'blue'});
 print(await client.get(uriResponse.bodyFields['uri']));
} finally {
 client.close();
}

Performance Monitoring for HTTP Requests

The SentryHttpClient starts a span out of the active span bound to the scope for each HTTP Request. This is currently an opt-in feature. The following example shows how to enable it.

import 'package:sentry/sentry.dart';

final transaction = Sentry.startTransaction(
  'webrequest',
  'request',
  bindToScope: true,
);

var client = SentryHttpClient();
try {
var uriResponse = await client.post('https://example.com/whatsit/create',
     body: {'name': 'doodle', 'color': 'blue'});
 print(await client.get(uriResponse.bodyFields['uri']));
} finally {
 client.close();
}

await transaction.finish(status: SpanStatus.ok());

Read more about Automatic Instrumentation.

Tips for catching errors

  • Use a try/catch block.
  • Use a catchError block for Futures, examples on dart.dev.
  • The SDK already runs your callback on an error handler, e.g. using runZonedGuarded, events caught by the runZonedGuarded are captured automatically.
  • Current Isolate errors which is the equivalent of a main or UI thread, are captured automatically (Only for non-Web Apps).
  • For your own Isolates, add an Error Listener by calling isolate.addSentryErrorListener().

Resources

示例代码

The example in this directory throws an error and sends it to Sentry.io. Use it as a source of example code, or to smoke-test your Sentry.io configuration.

To use the example, create a Sentry.io account and get a DSN for your project. In the main.dart file, replace the dsn value with the one you got from Sentry.io. Then run the following command :

dart pub get
dart run

更多关于Flutter崩溃报告与错误追踪插件sentry的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter崩溃报告与错误追踪插件sentry的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter应用中集成Sentry进行崩溃报告与错误追踪可以极大地帮助开发者诊断和解决应用中的问题。以下是一个如何在Flutter项目中集成和使用Sentry的示例代码案例。

1. 添加Sentry依赖

首先,你需要在你的pubspec.yaml文件中添加Sentry的依赖:

dependencies:
  flutter:
    sdk: flutter
  sentry_flutter: ^6.0.0  # 请检查最新版本号

然后运行flutter pub get来安装依赖。

2. 配置Sentry

在Flutter项目的lib目录下创建一个新的Dart文件,例如sentry_config.dart,用于初始化Sentry。

// lib/sentry_config.dart
import 'package:flutter/material.dart';
import 'package:sentry_flutter/sentry_flutter.dart';

void configureSentry(BuildContext context) {
  final SentryClientOptions options = SentryClientOptions(
    dsn: 'https://your-dsn-here@o123456.ingest.sentry.io/1234567',  // 替换为你的DSN
    // 其他可选配置
    environment: kReleaseMode ? 'production' : 'development',
    release: '1.0.0',  // 应用版本号
    dist: '1',  // 分发渠道,比如Google Play或App Store
  );

  SentryFlutter.init((app) {
    app.options = options;
  });
}

3. 在应用启动时初始化Sentry

在你的main.dart文件中,确保在应用启动时调用configureSentry函数。

// lib/main.dart
import 'package:flutter/material.dart';
import 'sentry_config.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  configureSentry(null);  // 在main函数中,context为null,因为此时还没有UI上下文
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Demo Home Page'),
      ),
      body: Center(
        child: Text('Hello, Sentry!'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          // 模拟一个错误
          throw Exception('This is a test exception');
        },
        tooltip: 'Throw Exception',
        child: Icon(Icons.error),
      ),
    );
  }
}

4. 捕获和处理错误

Sentry会自动捕获未处理的异常。如果你想手动捕获和处理错误,可以使用Sentry.captureException方法。

import 'package:sentry_flutter/sentry_flutter.dart';

void someFunctionThatMightFail() {
  try {
    // 可能会抛出异常的代码
  } catch (e, stackTrace) {
    Sentry.captureException(
      e,
      stackTrace: stackTrace,
      extra: {'key': 'value'},  // 可选的额外信息
    );
  }
}

5. 查看Sentry日志

确保你的应用已经发布并且用户正在使用它,当发生崩溃或错误时,这些信息将会被发送到Sentry服务器。你可以登录到Sentry的Web界面来查看和分析这些错误报告。

注意事项

  • 确保你已经在Sentry网站上创建了项目并获取了DSN(Data Source Name)。
  • 在发布应用之前,请仔细检查你的Sentry配置,确保没有泄露敏感信息。
  • Sentry捕获的错误信息可能包含用户的敏感数据,因此请确保你遵循相关的隐私政策和数据保护法规。

通过上述步骤,你就可以在Flutter项目中集成并使用Sentry进行崩溃报告与错误追踪了。

回到顶部