How to send telemetry from a .NET MAUI app to Flare
Send traces, logs, metrics and unhandled exceptions from a .NET MAUI app (Android, iOS, macOS, Windows) to Flare with the stock OpenTelemetry .NET packages. HTTP calls the app makes share a trace ID with your backend, so a slow screen can be followed into the API call and its database queries.
There is no Flare-specific MAUI package. Flare's OTLP/HTTP receiver accepts the SDK's protobuf exports directly, and a phone has a few constraints a server does not (see Limits).
Prerequisites
- A running Flare instance with the OTLP/HTTP port (
4318) reachable from your users' devices, ideally over HTTPS. - A MAUI app you can add NuGet packages to.
Use the Flare.Maui package
Flare.Maui does the setup below in one call: OTLP/HTTP export, an offline retry queue, device and session attributes, HttpClient and Shell navigation spans, unhandled-exception capture and a flush when the app is backgrounded. It is not on NuGet yet; for now reference src/Flare.Maui from this repository.
builder.UseMauiApp<App>()
.UseFlare(o =>
{
o.Endpoint = new Uri("https://flare.example.com:4318");
o.ServiceName = "my-maui-app";
o.IngestKey = "<key pinned to my-maui-app>";
});
Add your own ActivitySource and Meter names to o.AdditionalSources and o.AdditionalMeters, and call FlareMaui.RecordException(ex) for exceptions you handle. Native crashes are reported on the next launch (details); Windows is not covered yet. The rest of this page, from Use OTLP/HTTP, shows the equivalent hand-wired OpenTelemetry setup, which you need only if you want full control; Ingest keys, local-development and Limits apply to both.
Use OTLP/HTTP, not gRPC
gRPC is unreliable on iOS and Android, so export with the HttpProtobuf
protocol. When you set the endpoint in code, include the signal path
(/v1/traces, /v1/logs, /v1/metrics).
Install the packages
dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Instrumentation.Http
Configure the SDK
MAUI has no generic host, so the hosted service that AddOpenTelemetry() relies
on never starts. Build the providers directly and keep a reference for the life
of the app. Put this in MauiProgram.cs:
using OpenTelemetry;
using OpenTelemetry.Exporter;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
public static class MauiProgram
{
const string FlareUrl = "https://flare.example.com:4318";
const string IngestKey = "<ingest key>"; // ships in the binary: see "Ingest keys"
// Held for the app's lifetime; disposing them flushes and stops export.
public static TracerProvider? Tracing;
public static MeterProvider? Metering;
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>();
var resource = ResourceBuilder.CreateDefault()
.AddService("my-maui-app", serviceVersion: AppInfo.Current.VersionString)
.AddAttributes(new KeyValuePair<string, object>[]
{
new("os.type", DeviceInfo.Platform.ToString().ToLowerInvariant()),
new("os.version", DeviceInfo.VersionString),
new("device.manufacturer", DeviceInfo.Manufacturer),
new("device.model.identifier", DeviceInfo.Model),
new("app.build", AppInfo.Current.BuildString),
});
void Configure(OtlpExporterOptions o, string path)
{
o.Endpoint = new Uri($"{FlareUrl}{path}");
o.Protocol = OtlpExportProtocol.HttpProtobuf;
o.Headers = $"Authorization=Bearer {IngestKey}";
}
Tracing = Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(resource)
.AddSource("MyApp")
.AddHttpClientInstrumentation()
.AddOtlpExporter(o => Configure(o, "/v1/traces"))
.Build();
Metering = Sdk.CreateMeterProviderBuilder()
.SetResourceBuilder(resource)
.AddMeter("MyApp")
.AddHttpClientInstrumentation()
.AddOtlpExporter(o => Configure(o, "/v1/metrics"))
.Build();
builder.Logging.AddOpenTelemetry(o =>
{
o.SetResourceBuilder(resource);
o.IncludeFormattedMessage = true;
o.AddOtlpExporter(e => Configure(e, "/v1/logs"));
});
return builder.Build();
}
}
Create your own spans from an ActivitySource named MyApp:
static readonly ActivitySource Source = new("MyApp");
using var activity = Source.StartActivity("OpenOrder");
activity?.SetTag("order.id", id);
AddHttpClientInstrumentation() traces HttpClient calls and sends the
traceparent header to your API, so the trace continues server side.
Add a session ID
Group a launch's telemetry with a session.id attribute. Generate one per
launch and stamp it on every span with a small processor:
sealed class SessionProcessor : BaseProcessor<Activity>
{
static readonly string SessionId = Guid.NewGuid().ToString("N");
public override void OnStart(Activity activity) => activity.SetTag("session.id", SessionId);
}
Register it with .AddProcessor(new SessionProcessor()) before the exporter.
Filter on session.id in Traces to see one launch end to end.
The Sessions page (in the ⋯ menu) lists every launch in the window with its
app version, device, screens, trace count and error count. Filter by app version or
errors only, and click a session to open its traces. The package sets session.id
for you, on spans and on ILogger log records (filter Logs on session.id); a hand-rolled setup needs the processor above.
Leave breadcrumbs
The package records a breadcrumb span for each foreground and background change, button tap, page
appearing and ILogger record at Information or above. They show on the session page next to the spans,
so a crash comes with what the user did just before it. Add your own with
FlareMaui.AddBreadcrumb("checkout", "payment sheet opened").
Button text and page titles can contain personal data, so they are left out unless you set
IncludeTextInBreadcrumbs or IncludeTitleInBreadcrumbs. Taps then record the button's AutomationId
(or its type) and pages their type name. Raise BreadcrumbLogLevel, or set it to None, to limit log
breadcrumbs, and set Breadcrumbs = false to turn all of them off.
Each HttpClient call also leaves an http breadcrumb (GET api.example.com/orders 200, 2 KB, 85 ms, with the
host and path but never the query string) and its span gets http.request.body.size and
http.response.body.size from Content-Length; a chunked body has no size. A call that fails while the device
has no internet access is tagged network.offline = true and its breadcrumb says failed: offline, so a lost
connection reads differently from a server error. InstrumentHttpClient = false turns all of this off.
Attach a user, tags and scrub data
FlareMaui.SetUser("account-42"); // user.id on every span and log; null on sign-out
FlareMaui.SetTag("plan", "pro"); // any global attribute
FlareMaui.SetContext("cart", new Dictionary<string, string> { ["items"] = "3" }); // cart.items
Only the user id is sent. A name or e-mail passed to SetUser is dropped unless you set SendDefaultPii = true.
To redact or remove anything else before it leaves the device, set ScrubAttribute; it sees every span tag and log
attribute and returns the value to send, or null to remove it:
o.ScrubAttribute = (key, value) => key == "http.url" ? Redact((string?)value) : value;
No device identifier is sent either way.
To drop a span entirely, set BeforeSend, which returns false for spans you do not want sent (use BeforeSendLog
for log records). ScrubAttribute also receives span names (key span.name), span status messages (status.message) and, for
exceptions Flare reports itself, exception.type, exception.message and exception.stacktrace. Exceptions
recorded by other instrumentation are not scrubbed, because an exception event cannot be changed once added. It also
runs over resource attributes (service.name is never removed). BeforeSendLog receives each log record after
scrubbing and returns false to drop it.
Failed exports are retried from disk. At startup Flare deletes queued files older than OfflineQueueMaxAge
(2 days) and then the oldest ones until the queue fits OfflineQueueMaxBytes (25 MB). It repeats every
OfflineQueueTrimInterval (1 minute) while the app runs, so the queue can exceed the size only briefly between trims.
Check release health
The top of the Sessions page shows each app version's crash-free sessions and crash-free users for the window,
so you can compare a new release with the last one. A session counts as crashed when the app reported a fatal
unhandled exception; the rate is red below 99%. Users are counted from a user.id attribute on spans or the
resource. Flare.Maui does not set one, so the user columns show a dash until your app adds it.
Below the table, a chart plots each version's crash-free rate over time (the busiest six versions), so you can see whether a release got worse or recovered instead of reading one number for the whole window. Each session is counted once, in the bucket where it started.
To be paged when it drops, create an alert rule with the condition Crash-free sessions drop. Pick the services to watch (all when none is chosen), a threshold such as < 99 (percent) and a window such as 3600 seconds. The rule rates each version over the window and compares the lowest rate with the threshold, so an old, bad version keeps it firing until the window moves past it. Turn on Require a minimum number of sessions so a version with a handful of launches can't trip it; a version below the minimum is skipped, and if none qualifies the rule is neither fired nor resolved. It has no no-data option. Over the API it is conditionKind: "CrashFreeRate", metricThresholdValue as the percentage, minDataPoints as the minimum sessions, and exceptionCondition: { "exceptionType": "", "filter": { "services": ["shop-app"] } } for the scope.
Detect app hangs
A watchdog pings the UI thread and, when it does not answer for AppHangThreshold (2 seconds by default,
at least 500 ms), reports an app.hang span with an error status. It shows on the session page with a
hang breadcrumb, so a frozen screen is visible even when the OS then kills the app. It is paused while
the app is in the background. On Android the span also carries hang.stacktrace, the blocked thread's Java stack (managed
frames show as the runtime's native ones); iOS has no way to read another thread's stack. A paused debugger looks
like a hang, so set DetectAppHangs = false while debugging if it is noisy.
Measure app performance
Three spans feed the Performance section of the Sessions page, next to release health:
app.start, withapp.start.typeofcoldorwarm. A cold start runs from process start (Android) or from theUseFlarecall (iOS,app.start.originsays which) until the app is in the foreground. A warm start runs from returning to the foreground. A dialog or the notification shade closing is not a start.screen.load: a Shell navigation, fromNavigatinguntil the screen is shown, withscreen.name.screen.frames: one per screen visit (and when the app goes to the background), withframes.total,frames.slowandframes.frozen. A frame is slow atSlowFrameThreshold(20 ms by default) and frozen atFrozenFrameThreshold(700 ms); a frozen frame counts as slow too. Android readsFrameMetrics(API 26+), iOS times aCADisplayLink.
TracePerformance = false turns all three off. On a 90 or 120 Hz device the default slow threshold lets frames
between the display's budget and 20 ms through; lower it if that matters for your app.
Find out why a screen loads slowly
On Android, a screen.load that takes at least ProfileSlowLoadThreshold (500 ms by default) carries a sampled profile
of the UI thread: profile.samples and profile.stacks. The stack is read every ProfileSampleInterval (50 ms)
during the load only, then folded into one line per distinct stack, count root;...;leaf, most frequent first. The
frames are Android's Java frames, so they show which platform call was busy, not the C# method. iOS records no profile.
ProfileSlowLoads = false turns it off.
Attach screenshots to errors
Set CaptureScreenshotOnError = true to upload a screenshot of the current page whenever an exception is
reported. It appears as a Screenshot button on that row of the session page. It is off by default because a
screenshot shows whatever was on screen, including text the user typed. Images are JPEG, kept under
ScreenshotMaxBytes (300 KB by default, at most 512 KB) by lowering the quality, and limited to 5 per launch and
one per 10 seconds. The upload goes to POST /v1/screenshots on the same endpoint and ingest key as the rest, and
follows the Traces retention setting. Text inputs are hidden in every screenshot, and so is any view you mark; see Replay a session.
Replay a session
Set ScreenshotInterval = TimeSpan.FromSeconds(10) (at least 5 seconds) to also upload a screenshot of the foreground
page on that schedule. The session page then shows a Session replay player above the timeline: a scrubber and play
button over the frames, with the span the app was in at each moment, so you can see what the user saw before an error
and not only at it. It is off by default, takes no frames while the app is in the background, and stops after
MaxReplayScreenshots frames per launch (120 by default; the player shows up to 720 per session). Frames are the same
JPEGs as error screenshots (ScreenshotMaxBytes), follow the Traces retention setting, and need
migration 0081 on an existing ClickHouse.
Masking applies to both error screenshots and replay frames. Before each capture, Entry, Editor and SearchBar views
are made transparent for an instant and restored right after; set MaskTextInputs = false to keep them (a password
Entry is always hidden). Hide anything else by marking it, in XAML or code:
<Label Text="{Binding AccountBalance}" flare:FlareMask.IsMasked="True" />
FlareMask.SetIsMasked(balanceLabel, true);
A masked container hides its children. Masking only covers what MAUI renders on the main page: a native dialog or a system keyboard is not part of the capture.
Collect user feedback
Let users tell you what went wrong, with the session attached. The built-in prompt asks for a message (and optionally an e-mail address) and sends it:
// from a page, e.g. a "Report a problem" button
await FlareFeedback.PromptAsync(this, askForEmail: true);
For your own form, call FlareMaui.SendFeedbackAsync(message, email, name); it returns false when nothing was stored
(offline, empty message, rejected). Messages go to POST /v1/feedback on the same endpoint and ingest key as the rest,
carry the session id, the user set with SetUser and the app version, and follow the Traces retention setting. They appear
under Sessions > Feedback, newest first, with an Open session button to the timeline (and replay) that led to the
report. The message is free text the user typed and is not scrubbed; the e-mail and name are sent as the user gave them,
independent of SendDefaultPii. An existing ClickHouse needs migration 0082.
Report unhandled exceptions
Flare's Errors page groups exceptions recorded on spans. Report each crash as a short span with an exception event, then flush before the process dies:
static readonly ActivitySource Errors = new("MyApp");
static void Report(Exception ex, bool fatal)
{
using var span = Errors.StartActivity("app.unhandled_exception");
span?.AddException(ex);
span?.SetStatus(ActivityStatusCode.Error, ex.Message);
span?.SetTag("exception.escaped", fatal);
span?.Stop();
if (fatal) MauiProgram.Tracing?.ForceFlush(2000);
}
AppDomain.CurrentDomain.UnhandledException += (_, e) =>
Report((Exception)e.ExceptionObject, fatal: true);
TaskScheduler.UnobservedTaskException += (_, e) => Report(e.Exception, fatal: false);
Install the handlers in CreateMauiApp, after the providers are built. Errors
group by exception type and message. Add the resource filter
os.type = android (or ios) to the Errors page to see one platform.
Fatal native crashes (a SIGSEGV, an iOS watchdog kill) never reach a managed
handler. The Flare.Maui package reports them on the next launch, see
Report native crashes; hand-wired setups do not.
Report native crashes
Some crashes end the process before any managed handler runs: a SIGSEGV, an Android ANR or low-memory kill, an iOS
watchdog termination. Flare.Maui reads what the operating system recorded about the previous launch when the app
starts again, and sends each one as an app.unhandled_exception span with exception.escaped = true. The span carries
the earlier launch's session ID and app version, so release health counts it as a crash for that release, and the
Errors page groups it under a Native.* type.
- Android 11+ reads
ApplicationExitInfo: native crashes, ANRs (with the trace text), initialization failures, excessive resource use, and low-memory kills while the app was visible. - iOS 14+ read MetricKit crash diagnostics. iOS delivers them up to a day late, so the time is estimated from the launch's last foreground or background event, and the stack is MetricKit's raw call-stack JSON, not symbolicated.
A crash whose managed fatal exception was already reported is not counted twice. The package keeps a small journal of
the last ten launches (session ID, version, whether the app was in the foreground) in flare/runs.json in the app
data directory; no device identifier is stored. Turn the feature off with o.CaptureNativeCrashes = false. It has
not been verified on a device yet.
Symbolicate release stack traces
Release builds are trimmed and often AOT-compiled, and ship no PDBs, so a crash
reads at MyApp.Cart.Add (System.String sku) [0x0001a] in <8e3f…>:0. Upload the
symbols of each release from CI, with the --release value your app reports as
service.version:
flare sourcemaps upload-dotnet obj/Release/net11.0-android \
--service my-app --release 1.4.2 --url https://flare.example.com --token $FLARE_API_TOKEN
The command reads each dll and its portable PDB (<DebugType>portable</DebugType>,
the default), and the Errors page then shows File.cs:line 23 for the frames it
can resolve.
For a Native AOT build (PublishAot, iOS), frames read at MyApp.Cart.Add(String) + 0x48.
Upload the .dSYM that dotnet publish writes next to the binary:
flare sourcemaps upload-native bin/Release/net11.0-ios/ios-arm64/publish/MyApp.dSYM \
--managed obj/Release/net11.0-ios/ios-arm64 \
--service my-app --release 1.4.2 --url https://flare.example.com --token $FLARE_API_TOKEN
--managed takes the dll and portable PDB the app was compiled from (a file or a
directory, repeatable; use the ones in obj/, not a copy from another build). Without
it, a method that has overloads stays unresolved, because the compiler numbers them
Add, Add_0, Add_1 and the .dSYM alone cannot say which is which. With it, Flare
reads the same order from the dll's metadata and matches the parameter types in the
frame (Add(String), Add(Int32)). A function whose lines don't match the PDB is left
unmatched, with a note, so a stale dll never gives a wrong line.
Flush when the app is backgrounded
Mobile OSes suspend or kill a backgrounded app without warning. Flush from the
window's Stopped event so the last batch leaves the device:
protected override Window CreateWindow(IActivationState? state)
{
var window = base.CreateWindow(state);
window.Stopped += (_, _) =>
{
MauiProgram.Tracing?.ForceFlush(2000);
MauiProgram.Metering?.ForceFlush(2000);
};
return window;
}
Ingest keys
If ingest API keys are required,
the exporter needs the Authorization header shown above. The key is compiled
into your app, so anyone who unpacks the binary can read it. Treat it as
public:
- Create a dedicated key for the app, not one shared with your servers.
- Pin it to the app's service name so it cannot write telemetry under any other
service:
flare apikey scopeorPUT /api/ingest-keys/{id}/serviceswith{ "services": ["my-maui-app"] }. An export containing any other (or no)service.nameis refused with403. - Set per-key limits to cap what
a leaked key can send. A key at its cap gets
429withRetry-After. - Do not set allowed origins. An origin-restricted key only works from a
browser request whose
Originheader matches, and a native app sends none, so it would be refused. Origins andOtlp__AllowedOriginsare for browser apps. - Rotate the key by shipping a new app version, then revoke the old key once its traffic has drained.
Run against a local Flare
An Android emulator reaches your computer at 10.0.2.2, not localhost, so use
http://10.0.2.2:4318. The iOS simulator and Windows use localhost. Plain
http:// is blocked by default on both mobile platforms; for development only,
allow cleartext on Android (android:usesCleartextTraffic="true" on the
<application> element) and add an App Transport Security exception for your
host on iOS. Use HTTPS in anything you ship.
Check it worked
Open the Traces page and filter by service my-maui-app. An HttpClient
call appears as a client span, and as one trace across both services when your
API propagates traceparent. Open Logs and filter by the same service to
see ILogger output. Throw an exception from a button handler to confirm it
lands on Errors.
Limits
- Nothing is queued on disk. A batch that fails to send (no signal, airplane mode) is retried briefly and then dropped, and anything buffered when the OS kills the app is lost.
- Native crashes and stack traces from trimmed or AOT builds are not symbolicated: frames show runtime method names without source lines.
- The OpenTelemetry SDK is not trimming/AOT-annotated end to end. Test a release build with trimming enabled before relying on it.
- Telemetry carries whatever you attach. Don't put names, emails or other personal data in attributes, and treat any stable device identifier as opt-in.
Last updated: