Flutter数据追踪与HTTP客户端插件datadog_tracking_http_client的使用

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

Flutter数据追踪与HTTP客户端插件datadog_tracking_http_client的使用

简介

Datadog Tracking HTTP Client Plugin 是一个用于与Datadog SDK一起使用的插件,主要用于跟踪HTTP调用的性能并启用Datadog分布式追踪。

开始使用

要使用此插件,需要在配置SDK时启用它。为了启用Datadog分布式追踪,还需要在配置对象中设置 firstPartyHosts 属性。

import 'package:datadog_tracking_http_client/datadog_tracking_http_client.dart';

final configuration = DatadogConfiguration(
  // 其他配置项
  firstPartyHosts: ['example.com'],
)..enableHttpTracking();

注意,Datadog Tracking HTTP Client 修改了 [HttpOverrides.global]()。如果需要提供自己的 HttpOverrides,请确保在初始化Datadog之前进行初始化。在初始化过程中,Datadog会检查 HttpOverrides.current 的值,并在存在时使用它来创建客户端。

使用http.Client包装

此包还提供了一个可组合的客户端 DatadogClient,可用于 http 包。对于大多数场景,Datadog建议使用上述HTTP跟踪方法,但在某些情况下,使用 DatadogClient 可能更有意义:

  • 如果你使用的是原生HTTP库(如 cronet_httpcupertino_http),这些库不支持上述跟踪方法。
  • 如果你只想跟踪特定的资源请求。

如果你使用 cronet_httpcupertino_http,可以将 DatadogClient 与上述跟踪方法结合使用。否则,这两种方法可能会相互干扰。

要使用 DatadogClient,可以从 http 包中创建并组合 Client

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

final configuration = DatadogConfiguration(
  // 需要指定 firstPartyHosts 以启用分布式追踪
  firstPartyHosts: ['example.com'],
);

final httpClient = http.Client();
final datadogClient = DatadogClient(datadogSdk: DatadogSdk.instance, innerClient: httpClient);

innerClient 参数是可选的。如果不提供,DatadogClient 将为你创建一个具有默认选项的 Client

Flutter 2.8 支持

Flutter 3.0 更新到 Dart 2.17,这增加了两个 HttpClient 方法。

目前,version 1.1.x 设置了 Dart >= 2.17 的版本约束。如果你需要支持 Flutter 3.0 之前的版本(例如 Flutter 2.8),请使用 version 1.0.x。这两个版本之间的唯一区别是支持较低版本的 Dart。

贡献

欢迎提交拉取请求。首先,请打开一个议题讨论你希望更改的内容。更多信息,请阅读根仓库中的 贡献指南

许可证

Apache License, v2.0

示例代码

以下是一个完整的示例代码,展示了如何在Flutter应用中使用 datadog_tracking_http_client 插件。

main.dart

// Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-Present Datadog, Inc.

import 'dart:io';

import 'package:datadog_common_test/datadog_common_test.dart';
import 'package:datadog_flutter_plugin/datadog_flutter_plugin.dart';
import 'package:datadog_tracking_http_client/datadog_tracking_http_client.dart';
import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

import 'scenario_config.dart';
import 'scenario_select_screen.dart';

// This file sets up a different application for testing auto instrumentation
// Using the widgets in this library by themselves won't send any RUM events
// but, by utilizing this entry point instead, we can test that
// auto-instrumentation added to an existing app gives us the expected results.
TestingConfiguration? testingConfiguration;

Future<void> main() async {
  await dotenv.load(mergeWith: Platform.environment);

  var clientToken = dotenv.get('DD_CLIENT_TOKEN', fallback: '');
  var applicationId = dotenv.maybeGet('DD_APPLICATION_ID');
  String? customEndpoint = dotenv.maybeGet('DD_CUSTOM_ENDPOINT');

  if (testingConfiguration != null) {
    if (testingConfiguration!.customEndpoint != null) {
      customEndpoint = testingConfiguration!.customEndpoint;
    }
    if (testingConfiguration!.clientToken != null) {
      clientToken = testingConfiguration!.clientToken!;
    }
    if (testingConfiguration!.applicationId != null) {
      applicationId = testingConfiguration!.applicationId;
    }
  }

  final firstPartyHosts = ['datadoghq.com'];
  if (testingConfiguration != null) {
    firstPartyHosts.addAll(testingConfiguration!.firstPartyHosts);
  }

  DatadogSdk.instance.sdkVerbosity = CoreLoggerLevel.debug;

  final configuration = DatadogConfiguration(
    clientToken: clientToken,
    env: dotenv.get('DD_ENV', fallback: ''),
    site: DatadogSite.us1,
    uploadFrequency: UploadFrequency.frequent,
    batchSize: BatchSize.small,
    nativeCrashReportEnabled: true,
    firstPartyHosts: firstPartyHosts,
    loggingConfiguration: DatadogLoggingConfiguration(
      customEndpoint: customEndpoint,
    ),
    rumConfiguration: applicationId != null
        ? DatadogRumConfiguration(
            detectLongTasks: false,
            applicationId: applicationId,
            traceSampleRate: 100,
            customEndpoint: customEndpoint,
          )
        : null,
  );
  if (testingConfiguration != null) {
    // Add clear text if we're running an actual test.
    configuration.additionalConfig['_dd.needsClearTextHttp'] = true;
  }

  if (RumAutoInstrumentationScenarioConfig.instance.enableIoHttpTracking) {
    configuration.enableHttpTracking();
  }

  await DatadogSdk.runApp(configuration, TrackingConsent.granted, () async {
    runApp(const DatadogAutoIntegrationTestApp());
  });
}

class DatadogAutoIntegrationTestApp extends StatelessWidget {
  const DatadogAutoIntegrationTestApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final navObserver =
        DatadogNavigationObserver(datadogSdk: DatadogSdk.instance);
    return DatadogNavigationObserverProvider(
      navObserver: navObserver,
      child: MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          navigatorObservers: [
            navObserver,
          ],
          home: const ScenarioSelectScreen()),
    );
  }
}

scenario_config.dart

class TestingConfiguration {
  final String? clientToken;
  final String? applicationId;
  final String? customEndpoint;
  final List<String> firstPartyHosts;

  TestingConfiguration({
    this.clientToken,
    this.applicationId,
    this.customEndpoint,
    this.firstPartyHosts = const [],
  });
}

scenario_select_screen.dart

import 'package:flutter/material.dart';

class ScenarioSelectScreen extends StatelessWidget {
  const ScenarioSelectScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Scenario Select'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            ElevatedButton(
              onPressed: () {
                // Navigate to a specific scenario
              },
              child: Text('Scenario 1'),
            ),
            ElevatedButton(
              onPressed: () {
                // Navigate to another specific scenario
              },
              child: Text('Scenario 2'),
            ),
          ],
        ),
      ),
    );
  }
}

通过以上代码,你可以看到如何在Flutter应用中集成 datadog_tracking_http_client 插件,以实现HTTP调用的性能跟踪和分布式追踪。希望这些信息对你有所帮助!


更多关于Flutter数据追踪与HTTP客户端插件datadog_tracking_http_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter数据追踪与HTTP客户端插件datadog_tracking_http_client的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成并使用datadog_tracking_http_client插件进行数据追踪与HTTP请求的一个示例。

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  datadog_flutter_plugin: ^x.y.z  # 确保使用最新版本
  datadog_tracking_http_client: ^x.y.z  # 确保使用最新版本

替换^x.y.z为实际的最新版本号。

2. 初始化DataDog

在你的应用入口文件(通常是main.dart)中初始化DataDog插件:

import 'package:flutter/material.dart';
import 'package:datadog_flutter_plugin/datadog_flutter_plugin.dart';
import 'package:datadog_tracking_http_client/datadog_tracking_http_client.dart';

void main() {
  // 初始化DataDog
  DatadogFlutterPlugin.initialize(
    androidConfig: DatadogConfig(
      clientToken: 'YOUR_CLIENT_TOKEN',  // 替换为你的DataDog客户端令牌
      environment: 'production',  // 设置环境,例如:production, staging, development
      serviceName: 'your_service_name',  // 设置服务名称
      // 其他可选配置
    ),
    iosConfig: DatadogConfig(
      clientToken: 'YOUR_CLIENT_TOKEN',  // 替换为你的DataDog客户端令牌
      environment: 'production',  // 设置环境
      serviceName: 'your_service_name',  // 设置服务名称
      // 其他可选配置
    ),
  );

  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('DataDog Tracking Example'),
        ),
        body: Center(
          child: MyHomePage(),
        ),
      ),
    );
  }
}

3. 使用DataDog HTTP客户端

在你的应用中,使用DatadogTrackingHttpClient来替代标准的HttpClient进行HTTP请求,并自动追踪这些请求。

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:datadog_tracking_http_client/datadog_tracking_http_client.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String responseData = '';

  void fetchData() async {
    var client = DatadogTrackingHttpClient.create();
    var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');

    var request = HttpRequest.newBuilder()
      ..uri = url
      ..method = 'GET'
      ..build();

    var response = await client.send(request);

    response.body.pipe(new StreamControllers.text().sink)
      .then((value) {
        setState(() {
          responseData = value;
        });
      });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Fetch Data from API using DataDog Tracking HTTP Client'),
        ElevatedButton(
          onPressed: fetchData,
          child: Text('Fetch Data'),
        ),
        if (responseData.isNotEmpty)
          Text('Response Data:\n$responseData')
      ],
    );
  }
}

4. 运行应用

确保你已经替换了YOUR_CLIENT_TOKEN为你的实际DataDog客户端令牌,然后运行你的Flutter应用。你应该能够看到你的HTTP请求被DataDog自动追踪,并且可以在DataDog的仪表板上查看这些请求的数据。

注意事项

  • 确保你的DataDog账户已经配置好,并且你有权限查看和配置DataDog追踪。
  • 替换示例中的URL和请求方法为实际的API端点和请求类型。
  • 在生产环境中使用时,请确保遵循DataDog的最佳实践和隐私政策。

这个示例展示了如何在Flutter应用中使用datadog_tracking_http_client插件进行HTTP请求和数据追踪。如果你有更复杂的需求,可以参考DataDog的官方文档进行进一步的配置和自定义。

回到顶部