Flutter错误追踪与日志记录插件sentry_dio4的使用

Flutter错误追踪与日志记录插件sentry_dio4的使用


Sentry集成用于dio包

package build pub likes popularity pub points
sentry_dio build pub package likes popularity pub points

此集成适用于dio包。

使用方法

  1. 注册一个Sentry.io账户,并在<sentry.io>获取DSN。
  2. 按照<sentry.io>上的安装说明进行操作。
  3. 使用由Sentry.io发出的DSN初始化Sentry SDK。
  4. 调用dio.addSentry()。这必须是Dio设置的最后一个初始化步骤,否则你配置的Dio可能会覆盖Sentry配置。
import 'package:sentry/sentry.dart';
import 'package:sentry_dio/sentry_dio.dart';

Future<void> main() async {
  await Sentry.init(
    (options) {
      options.dsn = 'https://example@sentry.io/example';
    },
    appRunner: initDio, // 初始化你的App
  );
}

void initDio() {
  final dio = Dio();
  /// 这必须是Dio设置的最后一个初始化步骤,否则你配置的Dio可能会覆盖Sentry配置。
  dio.addSentry(...);
}

根据你的配置,这会添加性能跟踪和HTTP面包屑(http breadcrumbs)。此外,无效HTTP状态码或解析异常引发的异常将自动捕获。

示例代码

import 'package:dio/dio.dart';
import 'package:sentry/sentry.dart';
import 'package:sentry_dio/sentry_dio.dart';

Future<void> main() async {
  // 注意:更改下面的DSN以查看Sentry中的事件。可以在sentry.io获取一个。
  const dsn =
      'https://e85b375ffb9f43cf8bdf9787768149e0@o447951.ingest.sentry.io/5428562';

  await Sentry.init(
    (options) {
      options.dsn = dsn;
      options.tracesSampleRate = 1.0; // 需要Dio的`captureFailedRequests`功能
      options.debug = true;
      options.sendDefaultPii = true;

      options.maxRequestBodySize = MaxRequestBodySize.small;
      options.maxResponseBodySize = MaxResponseBodySize.small;
    },
    appRunner: runApp, // 初始化你的App
  );
}

Future<void> runApp() async {
  final dio = Dio();
  dio.addSentry();

  final transaction = Sentry.startTransaction(
    'dio-web-request',
    'request',
    bindToScope: true,
  );

  try {
    final response = await dio
        .get<Map<String, Object?>>('https://www.google.com/idontexist');

    print(response.toString());

    transaction.status =
        SpanStatus.fromHttpStatusCode(response.statusCode ?? -1);
  } catch (exception) {
    transaction.throwable = exception;
    transaction.status = const SpanStatus.internalError();
  } finally {
    await transaction.finish();
  }

  await Sentry.close();
}

更多关于Flutter错误追踪与日志记录插件sentry_dio4的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter错误追踪与日志记录插件sentry_dio4的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


Sentry 是一个流行的错误追踪和日志记录服务,它可以帮助开发者监控应用程序的健康状况,捕获并报告错误。sentry_dio 是一个用于 Flutter 的 Sentry 插件,它专门用于捕获和报告通过 Dio 库发出的 HTTP 请求中的错误。sentry_dio4 是针对 Dio 4.x 版本的 Sentry 插件。

安装 sentry_dio4

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

dependencies:
  flutter:
    sdk: flutter
  sentry_flutter: ^6.0.0
  sentry_dio4: ^6.0.0
  dio: ^4.0.0

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

初始化 Sentry

在你的 Flutter 应用程序中初始化 Sentry,通常在 main.dart 文件中进行:

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

void main() async {
  await SentryFlutter.init(
    (options) {
      options.dsn = 'YOUR_SENTRY_DSN_HERE'; // 你的 Sentry DSN
      options.tracesSampleRate = 1.0; // 采样率,1.0 表示100%采样
    },
    appRunner: () => runApp(MyApp()),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Sentry Demo',
      home: MyHomePage(),
    );
  }
}

使用 sentry_dio4 插件

在你的代码中,使用 sentry_dio4 来包装 Dio 实例,以便捕获 HTTP 请求中的错误:

import 'package:dio/dio.dart';
import 'package:sentry_dio4/sentry_dio4.dart';

class MyHomePage extends StatelessWidget {
  final Dio dio = Dio();

  MyHomePage() {
    // 使用 SentryDio 包装 Dio 实例
    dio.interceptors.add(SentryDioInterceptor());
  }

  Future<void> fetchData() async {
    try {
      final response = await dio.get('https://example.com/api/data');
      print(response.data);
    } catch (e, stackTrace) {
      // 捕获到的错误会自动发送到 Sentry
      print('Error: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Sentry Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: fetchData,
          child: Text('Fetch Data'),
        ),
      ),
    );
  }
}

解释

  1. 初始化 Sentry: SentryFlutter.init 用于初始化 Sentry,并设置 DSN 和其他配置项。

  2. 包装 Dio 实例: SentryDioInterceptor 是一个 Dio 的拦截器,它会在 HTTP 请求发生错误时自动捕获错误并将其发送到 Sentry。

  3. 捕获错误: 在 fetchData 方法中,如果 HTTP 请求发生错误,sentry_dio4 会自动捕获并发送错误到 Sentry。

其他配置

你可以根据需要配置 SentryDioInterceptor 的行为,例如:

  • 添加自定义标签: 你可以在 SentryDioInterceptor 中添加自定义标签来进一步分类错误。
  • 过滤错误: 你可以配置 SentryDioInterceptor 来过滤掉某些特定的错误。
dio.interceptors.add(SentryDioInterceptor(
  captureFailedRequests: true, // 是否捕获失败的请求
  maxRequestBodySize: MaxRequestBodySize.small, // 请求体大小限制
));
回到顶部