flutterrific_opentelemetry 0.3.4 copy "flutterrific_opentelemetry: ^0.3.4" to clipboard
flutterrific_opentelemetry: ^0.3.4 copied to clipboard

A Flutter package for OpenTelemetry based on dartastic_opentelemetry

Flutterrific OpenTelemetry SDK for Flutter #

pub.dev

License

Flutterrific OTel is an OpenTelemetry SDK for Flutter applications built on the Dartastic OpenTelemetry SDK, providing comprehensive observability for Flutter applications across all platforms.

Demo #

The Wondrous OpenTelemetry project instruments the Wondrous App for observability with Flutterrific OTel. The main.dart and router.dart show how to set up your app with Flutterrific OpenTelemetry.

Overview #

This Flutter SDK implements the OpenTelemetry specification, enabling developers to collect distributed traces and metrics from Flutter applications (logs coming soon). OpenTelemetry is a vendor-neutral standard for observability and is the second most active Cloud Native Computing Foundation (CNCF) project, after Kubernetes.

The CNCF OpenTelemetry Client Group is currently working on the specification for how OTel works on client apps. Flutterrific will follow the client spec as it matures.

Why OpenTelemetry for Flutter? #

  • Report Errors: Get notified of errors in real time.
  • App Lifecycle: When users launch, pause, resume and quit an application.
  • Watch Your Users: Where do users spend their time? Increase conversion rates.
  • Get Metrics: How fast do your routes load IRL?
  • Future-Proof: OpenTelemetry is an industry standard with broad ecosystem support
  • Vendor Neutral: Works with any OpenTelemetry-compatible backend
  • Comprehensive: Covers traces, metrics, and logs in a unified approach
  • Cross-Platform: Supports all Flutter platforms (Android, iOS, Web, Desktop)
  • Performance: Designed for minimal overhead in production applications

Features #

  • ๐Ÿš€ Simple Integration: Get started with just a few lines of code
  • ๐Ÿ‘ฃ Automatic Instrumentation: Navigation, app lifecycle, and user interaction tracking
  • ๐Ÿ“Š Performance Metrics: Web vitals, APDEX scores, and custom performance metrics
  • ๐Ÿงฉ Widget Extensions: Easy-to-use extensions for widget-level observability
  • ๐Ÿž Error Tracking: Comprehensive error handling and reporting
  • ๐Ÿ“ Standards Compliant: Full adherence to OpenTelemetry specification
  • ๐ŸŒ Multi-Platform: Supports Android, iOS, Web, and Desktop platforms
  • ๐Ÿ’ช Context Propagation: Seamless trace correlation across async boundaries
  • ๐Ÿ”ง Configurable Sampling: Multiple sampling strategies for cost optimization
  • ๐Ÿงท Type-Safe Semantics: Strongly-typed semantic conventions

Quick Start #

1. Add Dependency #

dependencies:
  flutterrific_opentelemetry: ^0.3.3

2. Initialize OpenTelemetry #

import 'package:flutter/material.dart';
import 'package:flutterrific_opentelemetry/flutterrific_otel.dart';

void main() {
  // Initialize error handling
  FlutterError.onError = (FlutterErrorDetails details) {
    FlutterOTel.reportError('FlutterError.onError', details.exception, details.stack);
  };

  runZonedGuarded(() {
    // Initialize OpenTelemetry
    FlutterOTel.initialize(
      serviceName: 'my-flutter-app',
      serviceVersion: '1.0.0',
      tracerName: 'main',
      // Configure your exporter endpoint
      resourceAttributes: {
        'deployment.environment': 'production',
        'service.namespace': 'mobile-apps',
      }
    );
    
    runApp(MyApp());
  }, (error, stack) {
    FlutterOTel.reportError('Zone Error', error, stack);
  });
}

3. Automatic Instrumentation #

The SDK automatically instruments:

  • Navigation: Track route changes and user flows
  • App Lifecycle: Monitor foreground/background transitions
  • Performance: Collect frame rates and rendering metrics
  • Errors: Capture and report exceptions with context

Platform Support #

Platform Support Level Protocol Notes
Android Full OTLP/gRPC Complete feature support
iOS Full OTLP/gRPC Complete feature support
Web Full OTLP/HTTP Auto-switches due to browser limitations
Windows Beta OTLP/gRPC Desktop support
macOS Beta OTLP/gRPC Desktop support
Linux Beta OTLP/gRPC Desktop support

Environment Variables #

Dartastic OpenTelemetry supports standard OpenTelemetry environment variables as defined in the OpenTelemetry Specification.

These environment variables can be set to configure the SDK behavior without changing code. Signal-specific variables take precedence over general ones.

Service Configuration #

Variable Description Example
OTEL_SERVICE_NAME Sets the service name my-dart-app
OTEL_SERVICE_VERSION Sets the service version 1.0.0
OTEL_RESOURCE_ATTRIBUTES Additional resource attributes as comma-separated key=value pairs environment=production,region=us-west

OTLP Exporter Configuration #

Variable Description Default Example
OTEL_EXPORTER_OTLP_ENDPOINT The OTLP endpoint URL http://localhost:4317 for gRPC, http://localhost:4318 for HTTP https://otel-collector:4317
OTEL_EXPORTER_OTLP_PROTOCOL The protocol to use http/protobuf grpc, http/protobuf, http/json
OTEL_EXPORTER_OTLP_HEADERS Additional headers as comma-separated key=value pairs None api-key=secret,tenant=acme
OTEL_EXPORTER_OTLP_INSECURE Whether to use insecure connection false true
OTEL_EXPORTER_OTLP_TIMEOUT Export timeout in milliseconds 10000 5000
OTEL_EXPORTER_OTLP_COMPRESSION Compression to use None gzip

Signal-Specific Configuration #

Traces

Variable Description Default Example
OTEL_TRACES_EXPORTER Trace exporter to use otlp console, none
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT Traces-specific endpoint Uses general endpoint https://traces.example.com
OTEL_EXPORTER_OTLP_TRACES_PROTOCOL Traces-specific protocol Uses general protocol grpc
OTEL_EXPORTER_OTLP_TRACES_HEADERS Traces-specific headers Uses general headers trace-key=value
OTEL_EXPORTER_OTLP_TRACES_INSECURE Traces-specific insecure setting Uses general setting true
OTEL_EXPORTER_OTLP_TRACES_TIMEOUT Traces-specific timeout Uses general timeout 30000
OTEL_EXPORTER_OTLP_TRACES_COMPRESSION Traces-specific compression Uses general compression gzip

Metrics

Variable Description Default Example
OTEL_METRICS_EXPORTER Metrics exporter to use otlp console, none
OTEL_EXPORTER_OTLP_METRICS_ENDPOINT Metrics-specific endpoint Uses general endpoint https://metrics.example.com
OTEL_EXPORTER_OTLP_METRICS_PROTOCOL Metrics-specific protocol Uses general protocol http/protobuf
OTEL_EXPORTER_OTLP_METRICS_HEADERS Metrics-specific headers Uses general headers metric-key=value
OTEL_EXPORTER_OTLP_METRICS_INSECURE Metrics-specific insecure setting Uses general setting false
OTEL_EXPORTER_OTLP_METRICS_TIMEOUT Metrics-specific timeout Uses general timeout 60000
OTEL_EXPORTER_OTLP_METRICS_COMPRESSION Metrics-specific compression Uses general compression gzip

Logging Configuration #

Variable Description Example
OTEL_LOG_LEVEL SDK internal log level TRACE, DEBUG, INFO, WARN, ERROR, FATAL
OTEL_LOG_METRICS Enable metrics logging true, 1, yes, on
OTEL_LOG_SPANS Enable spans logging true, 1, yes, on
OTEL_LOG_EXPORT Enable export logging true, 1, yes, on
OTEL_CONSOLE_EXPORTER Add console exporter for debugging true, 1, yes, on

Usage Example with Flutter #

When running a Flutter app:

flutter run \
  --dart-define=OTEL_SERVICE_NAME=my-flutter-app \
  --dart-define=OTEL_SERVICE_VERSION=1.0.0 \
  --dart-define=OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4317 \
  --dart-define=OTEL_EXPORTER_OTLP_PROTOCOL=grpc \
  --dart-define=OTEL_EXPORTER_OTLP_HEADERS=api-key=your-api-key

Advanced Usage #

Custom Tracing #

void fetchUserData() async {
  final tracer = FlutterOTel.tracer;
  
  final span = tracer.startSpan('fetch_user_data', attributes: {
    'user.id': userId,
    'api.endpoint': '/users',
  });
  
  try {
    final result = await apiClient.getUser(userId);
    span.setStatus(SpanStatusCode.Ok);
    return result;
  } catch (e, stackTrace) {
    span.recordException(e, stackTrace: stackTrace);
    span.setStatus(SpanStatusCode.Error, e.toString());
    rethrow;
  } finally {
    span.end();
  }
}

Widget-Level Tracking #

// Track button interactions
ElevatedButton(
  onPressed: handleSubmit,
  child: Text('Submit'),
).withOTelButtonTracking('submit_form');

// Monitor widget performance
ComplexWidget().withOTelPerformanceTracking('complex_widget');

// Error boundaries
RiskyWidget().withOTelErrorBoundary('risky_operation');
## Configuration

### Environment Variables

Standard OpenTelemetry environment variables are supported:

```bash
# Exporter endpoint
--dart-define=OTEL_EXPORTER_OTLP_ENDPOINT=https://your-collector:4317

# Protocol selection (default is http/protobuf as per OTel spec)
--dart-define=OTEL_EXPORTER_OTLP_PROTOCOL=grpc

# Service information
--dart-define=OTEL_SERVICE_NAME=my-flutter-app
--dart-define=OTEL_SERVICE_VERSION=1.0.0
```

### Local Development

For local development, run an OpenTelemetry collector on localhost:4317, the default. 

```bash
docker run -p 3000:3000 -p 4317:4317 -p 4318:4318 --rm -ti grafana/otel-lgtm
```

Examples #

Contributing #

We are looking for contributors and maintainers! Please see our Contributing Guide for details.

Development Setup #

# Clone the repository
git clone https://github.com/MindfulSoftwareLLC/flutterrific_opentelemetry.git
cd flutterrific_opentelemetry

# Install dependencies
make install

# Run tests
make test

# Run all checks
make all

Governance #

This project follows the CNCF Code of Conduct and maintains open governance. We welcome community participation and contributions.

Security #

Security vulnerabilities should be reported privately to the maintainers. See our Security Policy for details.

Compatibility #

  • Flutter: 3.7.0+
  • Dart: 3.7.0+
  • OpenTelemetry Specification: 1.31.0
  • Platforms: Android, iOS, Web, Windows, macOS, Linux

Roadmap #

See our Roadmap for planned features and improvements.

License #

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Community #

Acknowledgments #

Built on the foundation of:

Maintained by Michael Bushe and Mindful Software LLC.


This project aims to be contributed to the OpenTelemetry organization under the Cloud Native Computing Foundation.