monoscope_flutter 0.3.1
monoscope_flutter: ^0.3.1 copied to clipboard
Monoscope SDK for Flutter: OpenTelemetry tracing, error and crash reporting, and session replay.
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:monoscope_flutter/monoscope_flutter.dart';
/// Demonstrates every part of the Monoscope Flutter SDK: tracing, error
/// capture, session replay, navigation tracking and traced HTTP.
///
/// Replace the API key with your own from the Monoscope project settings, then
/// `flutter run`. With `debug: true` the SDK logs what it sends.
const apiKey = String.fromEnvironment(
'MONOSCOPE_API_KEY',
defaultValue: 'YOUR_API_KEY',
);
/// Drives the app without a human, for verifying the SDK on a device or
/// emulator. `--dart-define=E2E=telemetry` sends one of everything;
/// `--dart-define=E2E=crash` sends telemetry and then crashes natively, so the
/// next launch should report the crash. Empty in normal use.
const e2eMode = String.fromEnvironment('E2E');
const e2eMarker = String.fromEnvironment('MARKER', defaultValue: 'manual');
/// Overridable so a run can target a specific ingest host. See "Choosing an
/// ingest endpoint" in the README.
const tracesEndpoint = String.fromEnvironment(
'TRACES_ENDPOINT',
defaultValue: 'https://otel.monoscopehq.com/v1/traces',
);
Future<void> main() async {
await Monoscope.start(
const MonoscopeConfig(
apiKey: apiKey,
serviceName: 'monoscope-flutter-example',
exporterEndpoint: tracesEndpoint,
debug: true,
),
);
// Identify the user so replays and traces are attributable.
Monoscope.instance?.setUser(
const MonoscopeUser(
id: 'user-123',
email: 'ada@example.com',
fullName: 'Ada Lovelace',
),
);
// MonoscopeWidget supplies the capture boundary, tap positions and the
// lifecycle hooks that flush a recording before the app is suspended.
runApp(const MonoscopeWidget(child: ExampleApp()));
if (e2eMode.isNotEmpty) _runE2E();
}
/// Exercises every signal, then optionally crashes the process natively.
///
/// Logs each step with an `[e2e]` prefix so an automated run can assert on
/// logcat without needing to drive the UI.
Future<void> _runE2E() async {
final monoscope = Monoscope.instance!;
debugPrint('[e2e] mode=$e2eMode marker=$e2eMarker session=${monoscope.sessionId}');
// Let the first frame render so replay has something to capture.
await Future<void>.delayed(const Duration(seconds: 3));
monoscope.recordEvent(
'monoscope.flutter.e2e',
attributes: {'e2e.marker': e2eMarker, 'e2e.platform': 'android'},
);
monoscope.captureException(
StateError('e2e verification error $e2eMarker'),
stackTrace: StackTrace.current,
);
monoscope.recordNavigation('/e2e/$e2eMarker');
// A real outbound request, traced by the global HttpClient override with no
// client-side changes at the call site.
try {
final response = await http.get(Uri.parse('https://httpbin.org/get'));
debugPrint('[e2e] traced http status=${response.statusCode}');
} catch (e) {
debugPrint('[e2e] traced http failed: $e');
}
await monoscope.replay.captureFrameNow();
await monoscope.flush();
debugPrint('[e2e] flushed; replay queue=${monoscope.replay.eventCount}');
if (e2eMode == 'crash') {
debugPrint('[e2e] crashing natively now');
await Future<void>.delayed(const Duration(milliseconds: 500));
await monoscope.crashNativelyForTesting();
} else {
debugPrint('[e2e] done');
}
}
class ExampleApp extends StatelessWidget {
const ExampleApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Monoscope Example',
theme: ThemeData(colorSchemeSeed: Colors.indigo, useMaterial3: true),
// Reports every push/pop as a navigation span, a breadcrumb, and a marker
// on the replay timeline.
navigatorObservers: [MonoscopeNavigatorObserver()],
routes: {
'/': (_) => const HomeScreen(),
'/details': (_) => const DetailsScreen(),
},
);
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final _client = MonoscopeClient();
String _status = 'Nothing yet.';
@override
void dispose() {
_client.close();
super.dispose();
}
Future<void> _fetch() async {
setState(() => _status = 'Loading…');
try {
// A client span, with a traceparent header so an instrumented backend
// joins the same trace.
final response = await _client.get(
Uri.parse('https://httpbin.org/get'),
);
setState(() => _status = 'HTTP ${response.statusCode}');
} catch (e) {
setState(() => _status = 'Failed: $e');
}
}
Future<void> _tracedWork() async {
await Monoscope.instance?.startSpanAsync('checkout', (span) async {
span.setAttributes([]);
// Spans started in here nest underneath automatically.
await Future<void>.delayed(const Duration(milliseconds: 150));
Monoscope.instance?.recordEvent(
'checkout.completed',
attributes: {'items': 3, 'currency': 'USD'},
);
});
setState(() => _status = 'Traced work done.');
}
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Monoscope Example')),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Text(_status, style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 16),
const TextField(
decoration: InputDecoration(
labelText: 'Card number (masked in replays)',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 8),
const Text(
'Text fields are redacted in replay frames by default, so whatever '
'you type above never leaves the device.',
),
const Divider(height: 32),
FilledButton(
onPressed: _tracedWork,
child: const Text('Run traced work'),
),
const SizedBox(height: 8),
FilledButton.tonal(
onPressed: _fetch,
child: const Text('Traced HTTP request'),
),
const SizedBox(height: 8),
OutlinedButton(
onPressed: () => Navigator.of(context).pushNamed('/details'),
child: const Text('Navigate (adds a replay marker)'),
),
const SizedBox(height: 8),
OutlinedButton(
onPressed: () => Monoscope.instance?.captureException(
StateError('a handled failure'),
stackTrace: StackTrace.current,
),
child: const Text('Report a caught error'),
),
const SizedBox(height: 8),
OutlinedButton(
// Caught by PlatformDispatcher.onError with no extra wiring.
onPressed: () => Future<void>.error(
Exception('an uncaught async error'),
),
child: const Text('Throw an uncaught async error'),
),
const SizedBox(height: 8),
OutlinedButton(
onPressed: () async {
final ok = await Monoscope.instance?.test() ?? false;
setState(() => _status = ok ? 'Test span sent.' : 'Test failed.');
},
child: const Text('Verify setup'),
),
const SizedBox(height: 8),
OutlinedButton(
// Kills the process. The crash is reported on the next launch, which
// is the only way a crash reporter can report a fatal crash.
onPressed: () => Monoscope.instance?.crashNativelyForTesting(),
child: const Text('Crash natively (reports on next launch)'),
),
],
),
);
}
class DetailsScreen extends StatelessWidget {
const DetailsScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(title: const Text('Details')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('This navigation is a marker on the replay timeline.'),
const SizedBox(height: 16),
FilledButton(
// Throws during build on the next frame, exercising
// FlutterError.onError.
onPressed: () => throw StateError('thrown from a callback'),
child: const Text('Throw synchronously'),
),
],
),
),
);
}