# Add useful telemetry

Get the .NET client, connect events and logs to handled exceptions, and investigate the session timeline with automatic lifecycle context.

Source: https://appportal.io/docs/sdks/dotnet/telemetry

After [initializing at native startup](https://appportal.io/docs/sdks/dotnet), add the context only your application knows:
what the user was doing, which operation failed, and how the app recovered. AppPortal connects that
context with sessions, lifecycle changes, crashes, and performance measurements.

## Get the client

`IAppPortalClient` is the running SDK. If you chose the DI setup in your host guide, your
service receives the registered client through its constructor:

```csharp
using AppPortal;
using AppPortal.Logging;

public sealed class CatalogTelemetry(IAppPortalClient portal)
{
    public void RefreshStarted() => portal.Info("Catalog refresh started");
}
```

Register `CatalogTelemetry` with the same container, for example
`services.AddTransient<CatalogTelemetry>()` (or `builder.Services` in MAUI), using
`Microsoft.Extensions.DependencyInjection`. The container supplies `portal` when it creates your
service. Do not create a new SDK client for each service or view model.

For application code without DI, get the active client after startup:

```csharp
using AppPortal;
using AppPortal.Logging;

IAppPortalClient portal = AppPortalSdk.Current;
portal.Info("Catalog refresh started");
```

The static `AppPortalSdk` convenience methods reach that same instance.
This direct SDK path is supported for non-Prism apps and background/headless work without a
Prism logger. Inside an initialized Prism application, use its existing logging and identity
interfaces with the [optional adapter](https://appportal.io/docs/sdks/dotnet/prism).
The following examples use `portal = AppPortalSdk.Current`; an injected client works identically.

## Connect your consent UI

Collection starts **pending**: records stay in local quarantine until the user chooses.
Connect these methods to separate actions in your existing privacy settings:

```csharp
void AllowTelemetry() => AppPortalSdk.GrantConsent();
void DeclineTelemetry() => AppPortalSdk.RevokeConsent();
```

The SDK remembers the decision for this credential after durable persistence completes. Revocation
stops capture and erases unsent records; it cannot recall data already delivered. `ResetConsent()`
returns to pending. OS notification and location permissions are separate decisions.

On native Android and Apple runtimes, reset and revocation immediately restrict new capture and
delivery admission without waiting for a journal write. Durable persistence and cleanup follow on
the SDK's worker. A send admitted before the restriction may finish. Regrant cannot overtake
unfinished or failed cleanup, and old queued observations cannot acquire the new user's identity.
The immediate return confirms the process-local restriction, not a durable saved decision: a
process kill before persistence finishes can retain the previous saved choice. Graceful SDK cleanup
drains pending consent controls.

If your workforce app has an established collection policy, configure
`.WithInitialConsent(AppPortalConsentState.Granted)` at startup. A saved user decision takes
precedence. Avoid granting consent on every launch.

## Understand automatic lifecycle tracking

The SDK observes native lifecycle changes from root initialization and attaches them to the session. You do not need
to emit your own `app.started`, `app.backgrounded`, or `app.resumed` events just to reconstruct a run.
The SDK reports foreground/background transitions and active time; background wall time is not
counted as active use when those transitions are available.

Android observes Activity lifecycle; Apple observes native application and window lifecycle.
Android's cold-start clock begins in the native Application root before SDK runtime/storage
recovery and ends at the first Activity resume, including the work before MainActivity is created.
Windows, macOS and Linux/X11 desktop observation also belongs to the SDK. BrowserWasm observes
document visibility and page suspension/restoration directly. MAUI and Uno DI registration
expose the already running client without starting or replacing the native runtime. MAUI also
attaches visible-page observation automatically; Uno navigation requires separate registration. Linux framebuffer is a current limitation: automatic display
lifecycle, active-time and display-based startup tracking are unavailable on that backend. Root
initialization, crash capture and explicit telemetry remain available with the same startup setup.
Uno's fallback can observe application lifecycle events where a host emits them; application
attachment alone never establishes visibility or successful startup.
Available signals depend on the platform: a process kill or closed browser tab may provide no final
notification. An incomplete session is not proof of a crash. Browser queue recovery across reload
remains unsupported.

App-start and supported managed HTTP timing are enabled by root initialization. Browser startup
ends at the first observed visible animation frame; native startup uses the platform boundary
described in your setup guide. These boundaries do not measure application data readiness.
Application-specific context and business events are optional additional data; they do not replace
SDK-owned lifecycle or startup observation.
MAUI `UseAppPortal()` automatically records visible leaf-page visits. Shell navigation timing
is opt-in; Uno Frame and Prism Region navigation require separate observers. Choose one owner
for each navigation path, as described in the [MAUI](https://appportal.io/docs/sdks/dotnet/maui),
[Uno](https://appportal.io/docs/sdks/dotnet/uno) and [Prism](https://appportal.io/docs/sdks/dotnet/prism) guides. For work the SDK cannot
infer, add a custom span:

```csharp
using AppPortal;

using var span = AppPortalSdk.StartSpan("catalog.index", RumKind.Custom);
try
{
    await catalog.RebuildIndexAsync(); // Your application's indexing operation.
}
catch
{
    span.Finish(succeeded: false);
    throw;
}
```

Disposal records success unless the span was already finished. Do not also add a network span
around an automatically measured request. If you supply your own instrumentation, the builder
supports `.WithAutomaticNetworkRum(false)` and `.WithAutomaticAppStartRum(false)`.

## Identify the user

After sign-in, supply the user identifier chosen by your application. `Identify` updates the user
attached to subsequent telemetry; it does not record a sign-in event:

```csharp
using AppPortal;

var portal = AppPortalSdk.Current;
portal.Identify("user-42");

// When the user signs out:
portal.ClearUser();
```

The supplied value goes into `identity.userId` and connects records to the same user in the portal.
The SDK forwards that identifier unchanged; no additional profile fields are required.
Prism apps use their existing `SetUser(userId)` and `ClearUser()` methods through the
[logging adapter](https://appportal.io/docs/sdks/dotnet/prism#send-existing-prism-logs-to-appportal).
Identification does not grant consent or create the verified user binding required by
[Messaging](https://appportal.io/docs/sdks/messaging).

Identity is captured with each record. `ClearUser` removes the identifier and profile from future
records; it does not edit historical or already-queued telemetry. The opening session retains its
launch identity, while later event/log/error/RUM observations associate additional users with that
same session. A user needs a subsequent transmitted observation to appear in those views.
Calls to identify a user while consent is pending are ignored; apply the identifier after the
application has granted consent.

## Add properties that stay in effect

`SetContext` describes the app's current state. It adds a default property to each subsequent
event, log, and handled error until you replace or remove it. It does not send a record or create
a timeline entry by itself. Session and performance records carry their own identity and timing
fields; they do not currently carry these custom context properties.

```csharp
using AppPortal;
using AppPortal.Logging;

var portal = AppPortalSdk.Current;
portal.SetContext("storeId", "west-12");
portal.Info("Catalog refresh started"); // Includes storeId = west-12.

portal.Info("Checking another store",
    new Dictionary<string, string> { ["storeId"] = "east-3" });
portal.Info("Catalog refresh resumed"); // Still includes storeId = west-12.

// When the selected store no longer applies:
portal.SetContext("storeId", null);
```

A method's `properties` argument applies only to that record and wins over context with the same
key. It does not change the saved context. Both end up together in the record's `properties`
object, subject to your `BeforeSend` policy. Previously captured records are not rewritten.
`ClearUser()` clears identity, **not custom context**; remove user-specific context
on sign-out too.

In the portal, open a log's **Structured properties**, an event's **Properties**, or a crash
occurrence's **Occurrence properties** to see these values. There is no separate "context event"
to find in the timeline, and adding a key does not create a global dashboard filter.

### Set the current screen

The navigation observers in the [MAUI](https://appportal.io/docs/sdks/dotnet/maui#observe-native-navigation-rum),
[Uno](https://appportal.io/docs/sdks/dotnet/uno#4-observe-frame-navigation), and [Prism](https://appportal.io/docs/sdks/dotnet/prism)
guides supply screen context. For a custom UI without an observer, call
`AppPortalSdk.Current.SetScreen("checkout")` when the visible screen changes.
This supplies the `screen` property on subsequent events, logs, and errors. The navigation
observer also records the screen change; setting a property alone is not the same as recording
an action.

## Record events and diagnostic logs

**Events** describe outcomes you want to count. **Logs** explain what the app did along the way.
Use stable event names and short log messages with bounded properties:

```csharp
using AppPortal;
using AppPortal.Logging;

var portal = AppPortalSdk.Current;
portal.Info("Checkout opened");
portal.Log(AppPortalLogLevel.Warning, "Using cached catalog", category: "Catalog",
    properties: new Dictionary<string, string> { ["reason"] = "offline" });

// After your checkout API confirms the order:
portal.TrackEvent("checkout.completed",
    new Dictionary<string, string> { ["fulfillment"] = "pickup" });
```

`Debug`, `Info`, `Warn`, and `Error` are convenience methods over `Log`. A log at Error severity
is still a log; use `CaptureException` when you have an exception and need its stack trace.
Existing Prism applications can [forward their logger](https://appportal.io/docs/sdks/dotnet/prism#send-existing-prism-logs-to-appportal)
without rewriting each call. Registering AppPortal alone does not redirect every third-party logger.

Keep credentials, request bodies, names, order details, and free-form user input out of messages
and properties. Log useful milestones rather than every UI callback.

### Context, logs, and breadcrumbs

Use **context** for "which store is selected?" and a **log** for "the refresh started at this
time." A log is its own timestamped record: it appears in **Logs** and the session timeline,
carrying the context that applied when you recorded it.

`AddBreadcrumb` entries stay in memory and are not included in error reports or displayed in
Portal. Use logs to record activity leading up to an error.

## Capture a managed exception and recover

Automatic crash capture does not replace reporting exceptions your app catches. In this example,
`CatalogLoader` receives both the existing app `HttpClient` and the AppPortal client through DI.
A failed refresh is reported as a handled error, and the UI can keep showing its cached catalog:

```csharp
using System.Net.Http;
using AppPortal;
using AppPortal.Logging;

public sealed class CatalogLoader(HttpClient http, IAppPortalClient portal)
{
    public async Task<string?> RefreshAsync(CancellationToken cancellationToken)
    {
        portal.Info("Catalog refresh started");
        try
        {
            var catalog = await http.GetStringAsync("catalog", cancellationToken);
            portal.TrackEvent("catalog.refreshed");
            return catalog;
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
        {
            portal.Info("Catalog refresh canceled.");
            return null; // User cancellation is an expected outcome.
        }
        catch (HttpRequestException error)
        {
            portal.CaptureException(error,
                new Dictionary<string, string> { ["operation"] = "catalog.refresh" });
            portal.Warn("Catalog refresh failed; keeping cached data");
            return null;
        }
    }
}
```

Configure the `HttpClient` base address in your app's existing HTTP registration. Report the
exception once, at the recovery boundary where you have useful context. `operation` is a property
of that one error; previously set context such as `storeId` is included too.

On success, the session has the start log and `catalog.refreshed` event. Cancellation produces
the start and cancellation logs, without an error report. A failed request produces the start
log, a **Handled error** with its stack trace and properties in **Crashes**, and the warning log
explaining the recovery. Open that occurrence's session to read the records in time order.

With the default crash reporting enabled, native startup installs unhandled managed exception and
unobserved task exception hooks. Uno can also attach its optional XAML exception observation;
Android additionally observes uncaught Java exceptions, and Apple observes uncaught Objective-C
exceptions. The reporters do not capture POSIX fatal signals such as `SIGABRT` or `SIGSEGV`, Mach
exceptions, Android NDK crashes, or ANRs. These hooks do not recover the app or mark UI exceptions handled. Handled errors, unobserved task exceptions and automatic
fatal reports derive `wasInForeground` from the SDK's lifecycle observation. An error before the first
activity/window or while the app is backgrounded is not labeled foreground, even if the exception
occurs on the UI thread. Reports retain the occurrence time and foreground state observed when
the error occurred. Prism's `Report` uses the same context. Upload [matching symbols](https://appportal.io/docs/guides/distribution) for
readable stacks in release builds.

A fatal exception during an observed cold or warm start also produces an unsuccessful app-start
timing in the same session. The SDK persists that timing with the crash before returning from the
fatal hook, so both can replay on the next launch when delivery is unavailable. Root initialization
is sufficient; no Uno application-factory wrapper or manual flush is needed. Consent, capture
filters and the automatic app-start setting still apply.

## Follow the session timeline

Run a test flow with consent granted: open a screen, refresh the catalog, simulate a recoverable
failure, then background and resume the app. Every captured record carries the SDK's session ID;
you do not need to copy that ID into event properties.

1. In the Dashboard, select the app, environment, and time range for the test.
2. Open **Sessions** and choose the run to open its **Session story**.
3. Read the **Timeline** alongside lifecycle and active-time context. Events show outcomes, logs
   show operational detail, and available screens, network timings, and errors explain the lead-up.
4. Use **Logs** to search the operation's messages, or **Crashes** to investigate its handled error
   and stack trace. Keep the app, environment, and time scope aligned when moving between views.

See [Investigate an app session](https://appportal.io/docs/guides/investigate-session) for the cross-platform workflow.

For repeatable support or test correlation, the client exposes `portal.SessionId`. Delivery is
batched and retried; records can appear after the app action. See
[reliable delivery](https://appportal.io/docs/concepts/reliable-delivery) if expected records are missing.

## Start a plain managed host

For WPF, Windows Forms, or another managed host without a framework adapter, use .NET 10 and
run this command in the executable project's directory. Version 3.0.384 is available on public NuGet.

```bash
dotnet add package AppPortal.Telemetry --version "3.0.384"
```

[Create an SDK key](https://appportal.io/docs/getting-started/first-event#2-create-an-sdk-key) for the app and
environment you are testing. Start once at the executable's entry point with that credential.

```csharp
using AppPortal;

AppPortalSdk.CreateBuilder("<app-credential>").Start();
```

For a hosted test, copy the marker from [Verify a deliberate test](https://appportal.io/docs/getting-started/verify-first-value#receive-one-recognizable-event).
After granting consent through your app's privacy settings, send one event with that marker:

```csharp
using AppPortal;
using System.Collections.Generic;

AppPortalSdk.TrackEvent("appportal.setup.test", new Dictionary<string, string>
{
    ["setupObservation"] = "<unique-test-marker>"
});
```

Select **Check this test** in the same Dashboard app and environment to see the accepted receipt.

After native/process initialization, register the existing client with an existing DI container:

```csharp
using Microsoft.Extensions.DependencyInjection;

services.AddAppPortal();
```

This registers `AppPortalSdk.Current` as `IAppPortalClient`. Building the provider or resolving the
interface does not initialize or replace telemetry. Existing application/test registrations are
preserved; container disposal does not stop the native owner. Shared libraries use this same client.

## Keep telemetry through temporary outages

Managed .NET desktop and server apps buffer telemetry locally and retry delivery after temporary
network or API outages. Durably buffered records can survive an application restart when the app
uses the same writable persistent storage.

Buffering follows queue capacity, retention and consent limits. Records can expire or be evicted;
revoking consent erases unsent data. Storage failures and abrupt termination can also lose records
that have not reached durable storage. This is not a zero-loss guarantee or a browser-reload guarantee.

## Test your application code

Inject `FakeAppPortalClient` from `AppPortal.TestKit` to assert the events, logs, and errors your
services record. Use a real test app for delivery and lifecycle checks. The SDK owns batching and
retry; ordinary app flows need no flush or shutdown calls.
