boltZharp Docs
view_in_arSDKs

Unity

The Zharp package reports a Unity game's C# exceptions with their stacks and the code that ran, crashes, hangs, and the session, scene and player they happened to — on every platform Unity builds for, WebGL included.

info
Zharp for Unity 0.1.0

This SDK is new, and its API may still change before 1.0. Requires Unity 6.0 LTS or 6.3 LTS (Mono or IL2CPP).

Install

In Window → Package Manager → + → Install package from git URL…, paste:

https://github.com/zharp-io/zharp-unity-lib.git#0.1.0

or add it to Packages/manifest.json yourself:

// Packages/manifest.json
{
  "dependencies": {
    "io.zharp.unity": "https://github.com/zharp-io/zharp-unity-lib.git#0.1.0"
  }
}

From OpenUPM instead: openupm add io.zharp.unity, or add the registry:

// Packages/manifest.json
{
  "scopedRegistries": [
    { "name": "OpenUPM", "url": "https://package.openupm.com", "scopes": ["io.zharp"] }
  ],
  "dependencies": { "io.zharp.unity": "0.1.0" }
}

Or let Zharp do it. In the project folder (the one with Assets and ProjectSettings):

npm init zharp@latest

It finds ProjectSettings/ProjectVersion.txt, adds the package to Packages/manifest.json and writes your key. The package, io.zharp.unity, has its own small C# runtime and no DLLs — nothing for IL2CPP's linker to strip — so it works with Mono or IL2CPP on every platform Unity builds for.

Initialize

Open Edit → Project Settings → Zharp and paste your app's key (from its Setup page in Zharp). It's saved in Assets/Zharp/Resources/ZharpSettings.json, which ships with the game:

// Assets/Zharp/Resources/ZharpSettings.json
{ "key": "zpk_…" }

That's all: Zharp starts before the first scene loads, with no code to write. The key is safe to ship in the game: it can only send. Each setting can also come from the environment (ZHARP_KEY, ZHARP_ENVIRONMENT…) in desktop players and the Editor. To start it yourself — with a key fetched at runtime, say — turn autoStart off and call Zharp.Start(options => …).

Logs

Zharp.LogInfo("Checkout opened", new Dictionary<string, object> { ["items"] = 3 });   // also LogDebug, LogWarn, LogError

Each log carries the session, player, device, scene and trace. By default only what you send with Zharp.Log* goes to Zharp. Turn logs on (or set ZHARP_LOGS=true) to also send what the game logs: Debug.Log as info, warnings as warnings, errors as errors.

Logs only

If you only want logs, turn tracing off. Logs, errors, and the user and session they belong to are still sent; no spans are recorded and no trace headers are added to outgoing requests.

// Assets/Zharp/Resources/ZharpSettings.json
{
  "key": "zpk_…",
  "service": "shop-quest",
  "tracing": false
}

The logs show on the Logs page under the service name, and on the app's Logs tab with the user and session of each line. The key comes from an app — see Get a key. To add tracing later, remove the option; nothing else changes.

Errors

Every exception Unity catches and logs — in Update, coroutines, callbacks, async methods — reaches Zharp from Application.logMessageReceivedThreaded, and exceptions that reach AppDomain.UnhandledException on other threads too. The stack goes as Unity wrote it, with the lines around your scripts' frames:

NullReferenceException: Object reference not set to an instance of an object
Shop.Cart.Total () (at Assets/Scripts/Cart.cs:12)
Shop.CheckoutView.Refresh () (at Assets/Scripts/CheckoutView.cs:31)
Shop.CheckoutView.Update () (at Assets/Scripts/CheckoutView.cs:18)
  • Each is sent once: the same error from the same place at most once a minute. An exception in Update happens every frame, and Unity sometimes logs one exception twice.
  • Debug.LogError lines (and warnings) become breadcrumbs on the next exception. Turn logErrors on to report each Debug.LogError as an error of its own.

Report one you handled yourself:

try { Save(); }
catch (Exception e) { Zharp.CaptureException(e, new Dictionary<string, object> { ["slot"] = 2 }); }

Zharp.CaptureError("Save failed: disk full");   // a handled error, with where it was called

Crashes

When the player itself dies, nothing more can run in the game. The crash is sent on the next launch, with that run's session, scene and player:

  • iOS: the build step adds the Zharp iOS SDK to the generated Xcode project, started for native crashes only (signals and Objective-C exceptions), and a Run Script phase that uploads the dSYMs. The iOS SDK needs iOS 15, so the Xcode project's deployment target is raised to 15.0 if it's lower (turn nativeCrashes off to keep yours).
  • Windows: Unity's crash handler writes a crash folder with a minidump; on the next launch the package uploads the newest one to Zharp.
  • Android, macOS and Linux: a run that ended without quitting while in the foreground is sent as UncleanExit. Readable native stacks for these come later (see Not yet).

Hangs

The main thread not getting through a frame for 5 seconds (hangThreshold) is reported once per freeze, as ApplicationNotResponding. A watchdog thread writes it straight to disk, so it's sent even if the player kills the game. Not on WebGL (no threads), nor while the game is in the background or a debugger is attached.

Readable stack traces

C# stacks name the class, method, file and line as they are. Two things keep them that way in release builds:

  • IL2CPP line numbers: the build step sets IL2CPP Stacktrace Information to Method Name, File Name, and Line Number, so release stacks keep their files and lines (the build gets a little larger). Turn il2cppLineNumbers off to leave the setting alone.
  • The code that ran: the build step uploads the game's scripts (Assets/**/*.cs) as a source bundle under the build's GUID, which every error carries as zharp.build_id. Zharp shows the lines around each of the game's frames from the exact build that failed.
  • iOS crashes read as functions and lines once the build's dSYMs are uploaded, which the Xcode project's Run Script does.

Uploads at build time

The build step uploads the source bundle (and, from the Xcode build, the iOS dSYMs) when ZHARP_AUTH_TOKEN is set: a workspace API key with the Build uploads scope (artifacts:write). It's a secret — set it in CI or your shell, never in the project:

export ZHARP_AUTH_TOKEN=zak_…   # and ZHARP_APP_ID, unless applicationId is in the settings

Without it, the build log says what would have been uploaded and the build carries on. A failed upload never fails a build. Turn uploadSources or uploadSymbols off to skip either.

Tracing

Scenes

The active scene is the screen: everything recorded carries it as screen.name, and each scene that becomes active is a screen <name> span.

// A scene load as a span ("scene.load Level2"), until the scene is ready.
yield return Zharp.LoadSceneAsync("Level2");

Zharp.SetScreen("Inventory");   // the screen, when a scene doesn't say it

HTTP

Unity has no global hook for UnityWebRequest, so tracing is opt-in per request: send it through ZharpWebRequest.Send. It becomes a client span with the method, URL, status and headers — secret ones filtered — and carries traceparent, so your API's spans join the same trace.

// UnityWebRequest, traced: yield return it (or await it) as usual.
using var request = UnityWebRequest.Get("https://api.example.com/scores");
yield return ZharpWebRequest.Send(request);

Spans of your own

using (Zharp.StartSpan("load_level"))   // a span; what starts inside is in it
{
    LoadLevel(3);
}

Zharp.SetTag("level", "forest-2");   // an attribute on everything from now on
Zharp.Flush();                       // send what's waiting now

User context

Zharp.SetUser("player-42", "ada@example.com", "Ada");   // enduser.* on everything
Zharp.ClearUser();                                       // sign-out: also starts a new session
  • A session ID on everything: a new session after 30 minutes in the background, and on ClearUser().
  • The device, and a device.id — a random ID created on first launch and kept in Application.persistentDataPath. It isn't a hardware ID.

Options

In Project Settings → Zharp, saved in Assets/Zharp/Resources/ZharpSettings.json. Each can be overridden by an environment variable (desktop players and the Editor), or in code with autoStart off and Zharp.Start(options => …).

SettingEnvironmentDefaultNotes
keyZHARP_KEY—Required: the app's key
environmentZHARP_ENVIRONMENTdevelopment in the Editordeployment.environment.name
releaseZHARP_RELEASEPlayer Settings → Version
serviceZHARP_SERVICEThe Product NameAs Zharp names apps: Shop Quest → shop-quest
logsZHARP_LOGSoffSend Debug.Log lines
logErrorsoffDebug.LogError as errors, not breadcrumbs
tracingZHARP_TRACINGonSpans: scenes, requests, yours
tracesSampleRate1.0Share of traces kept; errors and logs are always sent
detectHangsZHARP_DETECT_HANGSon
hangThreshold5 s
nativeCrashesonThe iOS SDK in the Xcode project; the Windows crash folder upload
il2cppLineNumbersonThe build step sets IL2CPP line numbers
uploadSourcesonThe build step uploads Assets/**/*.cs
uploadSymbolsoniOS dSYMs, from the Xcode build
applicationIdZHARP_APP_ID—The app's ID, for the build step's uploads
enabledZHARP_ENABLEDon
autoStartonOff: call Zharp.Start() yourself
debugZHARP_DEBUGoffPrint what Zharp does
endpointZHARP_ENDPOINTZharpFor a local or self-hosted Zharp

Every batch is written to persistentDataPath/zharp/outbox/ before it's sent and deleted once Zharp has it: what couldn't be sent — no network, a crash, a quit — goes on the next launch. Zharp.Flush() sends now.

WebGL

Exceptions, sessions, scenes, requests and logs work the same. Batches are sent uncompressed (System.IO.Compression isn't there) and the outbox lives in the browser's IndexedDB. There is no hang detection (no threads). The game sends from the player's browser, so your Zharp app must allow the game's origin, like any browser app.

Not yet

  • Android native crashes (IL2CPP and engine signals in libil2cpp.so / libunity.so) arrive with the Zharp Android SDK's NDK support. Until then a crash is an UncleanExit.
  • macOS and Linux native crashes: Unity writes no dump there; they need Zharp's native SDK as a native plugin. Until then a crash is an UncleanExit.
  • Windows symbols: readable frames in Windows minidumps need the game's GameAssembly.pdb uploaded and Unity's UnityPlayer.pdb from Unity's symbol server; until then frames in them are addresses.
  • A Unity Asset Store listing.
info

Unity 2022 LTS and earlier aren't supported: the package targets Unity 6.0 LTS and 6.3 LTS.

Troubleshooting

Nothing arrives

On the app's setup page (Applications → the app → settings → Setup instructions), the verify step shows the first event as soon as it lands, and Send a test event checks the key on its own. If the test event arrives but your app's don't, the SDK isn't starting or isn't reaching Zharp:

  • Is init called, and before the code you expect to see? Without a key, the SDK starts nothing and says so once.
  • Does the service name match? With an app key everything goes to that app whatever it says; with a workspace key, service decides the app — see Keys.
  • Data is sent in batches every few seconds. A process that exits straight away should call flush first.
  • Logs and errors arrive but no traces? Check that tracing isn't turned off — see Logs only.
  • Is the key in Project Settings → Zharp? With debug on, the Console shows what Zharp does.
  • A WebGL build sends from the player's browser: add the game's origin to the key's allowed origins, or leave them empty.

401 or 403

Ingest answers 401 when the key is missing, mistyped, revoked or rolled, and 403 when the request comes from an origin or IP address the key doesn't allow. Neither is retried: the SDK warns once and drops what was refused, and it never throws into your code. Copy the key again from the app's settings.

Allowed origins

A browser sends an Origin header, and when the app has Allowed origins, only those may send with its key. An origin is the scheme, host and port, exactly — https://shop.example.com, not shop.example.com or a URL with a path. Add http://localhost:3000 for local development, or leave the list empty.

Ad blockers

Some browser extensions block requests to monitoring services. If it works in a private window with extensions off, that's the cause — your users with the same extension won't be reported either.