middleware_flutter_opentelemetry 1.0.2
middleware_flutter_opentelemetry: ^1.0.2 copied to clipboard
A Flutter package for OpenTelemetry based on middleware_dart_opentelemetry
Middleware Flutter OpenTelemetry SDK for Flutter #
Middleware Flutter OTel is an OpenTelemetry SDK for Flutter applications built on the Middleware OpenTelemetry SDK, providing comprehensive observability for Flutter applications across all platforms.
Demo #
The Wondrous OpenTelemetry project instruments the Wondrous App for observability with Middleware Flutter OTel.
The main.dart and router.dart show how to set up your app with Middleware Flutter 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.
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
- ๐น Session Replay: Lightweight Session replay of application.
- ๐ 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:
middleware_flutter_opentelemetry: ^1.0.0
2. Initialize OpenTelemetry #
import 'package:flutter/material.dart';
import 'package:middleware_flutter_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',
middlewareAccountKey: "*****", // Obtain from RUM Flutter installation page
endpoint: 'https://<account>.middleware.io',
// Configure your exporter endpoint
resourceAttributes: {
'env': '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 #
Middleware 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=Authorization=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 #
- Basic Integration Example
- Flutter_Wonderous OpenTelemetry - Complete app example based on Wonderous
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/middleware-labs/flutter-sdk.git
cd flutter-sdk
# 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 #
- GitHub Issues - Bug reports and feature requests
- OpenTelemetry Community - Broader OpenTelemetry community
Acknowledgments #
Built on the foundation of: