Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Aptabase.uplugin
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"FileVersion": 3,
"VersionName": "0.2.0",
"VersionName": "0.3.0",
"EngineVersion": "5.6",
"FriendlyName": "Aptabase",
"Description": "Open Source, Privacy-First and Simple Analytics for Mobile, Desktop and Web Apps",
Expand All @@ -19,4 +19,4 @@
"LoadingPhase": "Default"
}
]
}
}
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Changelog

## 0.3.0

- Add `UAptabaseBlueprintLibrary::TrackError` and the **Track Error** Blueprint node for structured handled and fatal error reports.
- Add opt-in **Enable Crash Reporting** to report fatal errors (assertion failures, `Fatal` logs, crashes routed through the engine's error handler) during active sessions. The error handler writes the report to `Saved/Aptabase/Crashes` and the next session start sends it; on Windows the handler also attempts an immediate send.
- Include capture-time session, timestamp, OS, app version, SDK version, severity, kind, and debug mode; truncate fields to the server limits.
- Send errors individually to `/api/v0/error`, retry network failures and HTTP 408/429/5xx on later flushes, and discard permanent rejections including HTTP 403 quota exhaustion.
- Bound outstanding reports to 25 and deduplicate up to 100 unique errors per session.
- `StartSession()` now returns `true` without starting a new session when one is already active; previously it replaced the session ID and restarted the flush timer.
- Cancel in-flight event requests and unbind their callbacks when the provider is destroyed; guard against responses without a body.
17 changes: 17 additions & 0 deletions Docs/testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Testing error reporting

Install the plugin in a C++ Unreal Engine project and build the Development Editor target. Open **Tools → Test Automation** (or **Session Frontend → Automation**) and run **Aptabase.Errors**.

For a command-line run, substitute your engine executable and project path:

```sh
UnrealEditor-Cmd YourProject.uproject -unattended -NullRHI \
-ExecCmds="Automation RunTests Aptabase.Errors" \
-TestExit="Automation Test Queue Empty" -log
```

The tests cover the JSON contract and field limits, retry status codes, capture-time context across sessions, deduplication, in-flight queue capacity, session limits, concurrent capture, and parsing the engine's error history into a crash report. They do not send data to Aptabase.

For an end-to-end check, configure a local HTTP server as the SH host and start an analytics session in Play-in-Editor. Record a normal event and call **Track Error**. Verify that the event goes to `/api/v0/events` as an array and the error goes to `/api/v0/error` as one JSON object, with `App-Key` and `Content-Type: application/json` headers. Return 202 to accept a report; repeat with 400/403 (no retry), 408/429/500 (retry on the next flush), and a disconnected server. End/start PIE and verify that pending retries retain the old session and that new reports carry the new session.

To exercise crash reporting, enable **Enable Crash Reporting**, start a session, then trigger a fatal error from a packaged or `-game` build rather than Play-in-Editor, since a fatal error terminates the whole editor: for example a Blueprint-callable test function containing `UE_LOG(LogTemp, Fatal, TEXT("Test crash"))` or `check(false)`. Verify that one JSON file appears under `Saved/Aptabase/Crashes` with `kind: "crash"`, `severity: "fatal"`, the engine's description as `errorMessage` and the call stack as `stackTrace`. Launch the game again and start a session: the report must arrive at `/api/v0/error` with the crashed session's `sessionId` and the file must be deleted after a 2xx or 4xx response. Repeat with the server stopped during the second launch to confirm the file survives for a later launch. On Windows the first launch also sends the report immediately with a 3 second timeout, and the file is deleted when that succeeds. Non-fatal `UE_LOG(..., Error, ...)` messages must not produce a report.
56 changes: 55 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,63 @@ A few important notes:
3. You do not need to await for the record event calls, they will run in the background.
4. Only strings and numbers values are allowed on custom properties

## Error Reporting

Error reporting is in beta. Reports appear on the **Errors** page of your Aptabase dashboard.

Start an analytics session using the **Start Session** Blueprint node or your configured provider's `StartSession()` before tracking events or errors. End it with **End Session** / `EndSession()` when your game session ends.

### C++

Add `"Aptabase"` to your game's `Build.cs` dependencies and call the API on the game thread:

```cpp
#include "AptabaseBlueprintLibrary.h"

UAptabaseBlueprintLibrary::TrackError(
TEXT("Could not save the game"), TEXT("SaveError"));

// Supply the original stack trace when available. Fatal means the app cannot recover;
// setting it does not terminate the app.
UAptabaseBlueprintLibrary::TrackError(
TEXT("Required assets are missing"), TEXT("LoadError"), TEXT("LoadAssets\nStartGame"), true);
```

Manual reports have severity `error` and kind `handled`. With `bFatal = true`, they have severity `fatal` and kind `crash`. The message, type, and optional stack are sent with the session ID, capture timestamp, OS, app/SDK versions, and debug/release mode. Empty error types default to `Error`.

### Blueprints

Use **Track Error** under **Analytics → Aptabase**. Set **Error Message** and **Error Type**; expand the advanced pins for **Stack Trace** and **Fatal**. The node uses Aptabase's own provider instance and also works when Aptabase is configured through the Multicast provider.

### Automatic crash reporting

Enable **Project Settings → Analytics → Aptabase → Enable Crash Reporting** before starting the session, or add this to `Config/DefaultAptabase.ini`:

```ini
[/Script/Aptabase.AptabaseSettings]
bEnableCrashReporting=True
```

This is off by default. While enabled, fatal errors that reach the engine's error handler during an active session are reported as `crash`/`fatal`: `check` and `verify` assertion failures, `UE_LOG` messages at `Fatal` verbosity, `LowLevelFatalError`, and unhandled native exceptions or signals on platforms where the engine routes them through its error handler. The report is built from the engine's error state: the heading becomes the error type (`AssertionFailed`, `FatalError`, `UnhandledException`, or the signal name such as `SIGSEGV` for a native crash on Apple and Unix platforms), the description becomes the message and the engine's call stack is included.

Non-fatal `Error` log messages are never reported automatically. Use **Track Error** for errors your game detects itself.

Delivery of crash reports is best effort. The process is terminating, so the error handler writes the report to `Saved/Aptabase/Crashes` and the next session start sends the pending reports, each under the session in which the crash happened. The newest 10 pending reports are kept; a report is deleted once the server accepts or permanently rejects it, so an offline launch keeps it for a later one. On Windows the handler also tries to send the report immediately with a 3 second timeout, because the engine handles the crash on a separate thread while the HTTP thread keeps running; a report delivered this way is not sent again. On macOS, iOS and Linux the engine switches to a crash allocator that suspends every other thread, including the HTTP thread, so crash reports always arrive at the next launch. Nothing is captured when the crash corrupts the process beyond what the engine's handler survives. Unreal's own Crash Reporter remains available and is unaffected.

Errors and crashes that happen before `StartSession()` or after `EndSession()` are not captured. Start the session as early as your game can, for example in your `GameInstance::Init`.

### Delivery

- Manual reports are sent asynchronously, one per request. Capturing an error schedules an immediate send on the game thread; `FlushEvents()` and the normal send timer also flush errors. Crash reports are written to disk from the error handler and queued for sending at the next session start, as described above.
- Failed requests are retained for a later flush on connection errors or HTTP 408, 429, and 5xx. Other responses, including HTTP 403 (monthly quota exhausted), are not retried.
- The queue holds up to 25 outstanding reports, including requests in progress. New reports are dropped when full. Each unique combination of kind, type, message, and stack is reported once per session, up to 100 unique reports.
- Retries retain their original session and system context. Manual reports are stored in memory only and can be lost when the process exits; crash reports are persisted until delivered or permanently rejected. Ending a session initiates a final flush without waiting for delivery.
- Error text can contain application data. Only include information you intend to send to Aptabase.

See [testing instructions](Docs/testing.md) for the Unreal automation suite.

## Preparing for Submission to Apple App Store

When submitting your app to the Apple App Store, you'll need to fill out the `App Privacy` form. You can find all the answers on our [How to fill out the Apple App Privacy when using Aptabase](https://aptabase.com/docs/apple-app-privacy) guide.

For AI/LLM integration instructions, see [llms.txt](./llms.txt)

6 changes: 3 additions & 3 deletions Source/Aptabase/Private/Aptabase.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ void FAptabaseModule::StartupModule()

void FAptabaseModule::ShutdownModule()
{
OnApplicationShutdown();
AnalyticsProvider.Reset();
if (FSlateApplication::IsInitialized())
{
FSlateApplication& Application = FSlateApplication::Get();
Expand All @@ -48,8 +50,6 @@ void FAptabaseModule::OnApplicationShutdown()
{
AnalyticsProvider->EndSession();
}

AnalyticsProvider.Reset();
}

#if WITH_EDITOR
Expand All @@ -62,4 +62,4 @@ void FAptabaseModule::OnEndPIE(bool bIsSimulating)
}
#endif

IMPLEMENT_MODULE(FAptabaseModule, Aptabase);
IMPLEMENT_MODULE(FAptabaseModule, Aptabase);
73 changes: 70 additions & 3 deletions Source/Aptabase/Private/AptabaseAnalyticsProvider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@
#include <Interfaces/IPluginManager.h>
#include <Kismet/GameplayStatics.h>
#include <Kismet/KismetInternationalizationLibrary.h>
#include <Misc/Paths.h>
#include <Serialization/JsonSerializer.h>
#include <TimerManager.h>

#include "AptabaseCrashReporter.h"
#include "AptabaseData.h"
#include "AptabaseErrorDispatcher.h"
#include "AptabaseLog.h"
#include "AptabaseSettings.h"
#include "ExtendedAnalyticsEventAttribute.h"
Expand All @@ -21,6 +24,10 @@ namespace
{
UGameInstance* GetCurrentGameInstance()
{
if (!GEngine)
{
return nullptr;
}
for (const FWorldContext& Context : GEngine->GetWorldContexts())
{
if (Context.WorldType == EWorldType::PIE || Context.WorldType == EWorldType::Game)
Expand All @@ -44,13 +51,40 @@ namespace
}
} // namespace

FAptabaseAnalyticsProvider::FAptabaseAnalyticsProvider() : ErrorDispatcher(MakeShared<FAptabaseErrorDispatcher, ESPMode::ThreadSafe>())
{
}

FAptabaseAnalyticsProvider::~FAptabaseAnalyticsProvider()
{
CrashReporter.Reset();
if (const UGameInstance* GameInstance = GetCurrentGameInstance())
{
GameInstance->GetTimerManager().ClearTimer(BatchEventTimerHandle);
}
for (const FHttpRequestPtr& Request : EventRequests)
{
Request->OnProcessRequestComplete().Unbind();
Request->CancelRequest();
}
}

void FAptabaseAnalyticsProvider::TrackError(const FString& Message, const FString& ErrorType, const FString& StackTrace, bool bFatal)
{
ErrorDispatcher->TrackError(Message, ErrorType, StackTrace, bFatal);
}

void FAptabaseAnalyticsProvider::RecordExtendedEvent(const FString& EventName, const TArray<FExtendedAnalyticsEventAttribute>& Attributes)
{
RecordEventInternal(EventName, Attributes);
}

bool FAptabaseAnalyticsProvider::StartSession(const TArray<FAnalyticsEventAttribute>& Attributes)
{
if (bHasActiveSession)
{
return true;
}
const UGameInstance* GameInstance = GetCurrentGameInstance();
if (!ensure(GameInstance))
{
Expand All @@ -68,11 +102,37 @@ bool FAptabaseAnalyticsProvider::StartSession(const TArray<FAnalyticsEventAttrib
SessionId = FString::Printf(TEXT("%lld%s"), EpochInSeconds, *RandomString);

bHasActiveSession = true;

FAptabaseErrorContext ErrorContext;
ErrorContext.SessionId = SessionId;
ErrorContext.OsName = UGameplayStatics::GetPlatformName();
ErrorContext.OsVersion = FPlatformMisc::GetOSVersion();
ErrorContext.AppVersion = GetDefault<UGeneralProjectSettings>()->ProjectVersion;
const TSharedPtr<IPlugin> Plugin = IPluginManager::Get().FindPlugin(TEXT("Aptabase"));
ErrorContext.SdkVersion = FString::Printf(TEXT("aptabase-unreal@%s"), Plugin.IsValid() ? *Plugin->GetDescriptor().VersionName : TEXT("unknown"));
ErrorContext.bIsDebug = !IsInReleaseMode();
ErrorContext.ApiUrl = Settings->GetApiUrl();
ErrorContext.ApiUrl.RemoveFromEnd(TEXT("/"));
ErrorContext.AppKey = Settings->AppKey;
ErrorDispatcher->StartSession(ErrorContext);
if (Settings->bEnableCrashReporting)
{
// Crashes persisted by earlier runs are sent with the new session, under their own session IDs.
const FString PendingCrashDirectory = FPaths::Combine(FPaths::ProjectSavedDir(), TEXT("Aptabase"), TEXT("Crashes"));
for (FAptabaseErrorReport& PendingReport : FAptabaseCrashReporter::LoadPendingReports(PendingCrashDirectory))
{
ErrorDispatcher->EnqueueReport(MoveTemp(PendingReport));
}
ErrorDispatcher->Flush();
CrashReporter = MakeUnique<FAptabaseCrashReporter>(ErrorContext, PendingCrashDirectory);
}
return true;
}

void FAptabaseAnalyticsProvider::EndSession()
{
CrashReporter.Reset();
ErrorDispatcher->EndSession();
if (BatchEventTimerHandle.IsValid())
{
if (const UGameInstance* GameInstance = GetCurrentGameInstance())
Expand Down Expand Up @@ -116,6 +176,7 @@ void FAptabaseAnalyticsProvider::FlushEvents()
}

BatchedEvents.Empty();
ErrorDispatcher->Flush();
}

void FAptabaseAnalyticsProvider::SetUserID(const FString& InUserID)
Expand Down Expand Up @@ -198,12 +259,18 @@ void FAptabaseAnalyticsProvider::SendEventsNow(const TArray<FAptabaseEventPayloa
HttpRequest->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
HttpRequest->SetURL(RequestUrl);
HttpRequest->OnProcessRequestComplete().BindRaw(this, &FAptabaseAnalyticsProvider::OnEventsRecoded, EventPayloads);
HttpRequest->ProcessRequest();
EventRequests.Add(HttpRequest);
if (!HttpRequest->ProcessRequest())
{
HttpRequest->OnProcessRequestComplete().Unbind();
EventRequests.Remove(HttpRequest);
}
}

void FAptabaseAnalyticsProvider::OnEventsRecoded(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful, TArray<FAptabaseEventPayload> OriginalEvents)
{
if (!bWasSuccessful)
EventRequests.Remove(Request);
if (!bWasSuccessful || !Response.IsValid())
{
UE_LOG(LogAptabase, Error, TEXT("Request to record the event was unsuccessful."));
return;
Expand Down Expand Up @@ -251,7 +318,7 @@ FAnalyticsEventAttribute FAptabaseAnalyticsProvider::GetDefaultEventAttribute(in
{
return DefaultEventAttributes[AttributeIndex];
}

UE_LOG(LogAptabase, Warning, TEXT("Requested default event attribute index %d is out of bounds (count: %d)"), AttributeIndex, DefaultEventAttributes.Num());
return FAnalyticsEventAttribute();
}
9 changes: 9 additions & 0 deletions Source/Aptabase/Private/AptabaseAnalyticsProvider.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@
#include "AptabaseData.h"

struct FExtendedAnalyticsEventAttribute;
class FAptabaseErrorDispatcher;
class FAptabaseCrashReporter;

/**
* Implementation of Aptabase Analytics provider
*/
class FAptabaseAnalyticsProvider final : public IAnalyticsProvider
{
public:
FAptabaseAnalyticsProvider();
virtual ~FAptabaseAnalyticsProvider() override;
void TrackError(const FString& Message, const FString& ErrorType, const FString& StackTrace, bool bFatal);

/**
* Overload for RecordEvent that takes an array of ExtendedAttributes
*/
Expand Down Expand Up @@ -71,4 +77,7 @@ class FAptabaseAnalyticsProvider final : public IAnalyticsProvider
* @brief Default event attributes that will be added to all events
*/
TArray<FAnalyticsEventAttribute> DefaultEventAttributes;
TSharedPtr<FAptabaseErrorDispatcher, ESPMode::ThreadSafe> ErrorDispatcher;
TUniquePtr<FAptabaseCrashReporter> CrashReporter;
TArray<FHttpRequestPtr> EventRequests;
};
19 changes: 19 additions & 0 deletions Source/Aptabase/Private/AptabaseBlueprintLibrary.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include "AptabaseBlueprintLibrary.h"

#include <Modules/ModuleManager.h>

#include "Aptabase.h"
#include "AptabaseAnalyticsProvider.h"

void UAptabaseBlueprintLibrary::TrackError(const FString& ErrorMessage, const FString& ErrorType, const FString& StackTrace, bool bFatal)
{
// The default provider may be a Multicast provider or another SDK. Resolve our
// own module's instance instead of casting an arbitrary IAnalyticsProvider.
if (const FAptabaseModule* Module = FModuleManager::GetModulePtr<FAptabaseModule>(TEXT("Aptabase")))
{
if (Module->AnalyticsProvider.IsValid())
{
StaticCastSharedPtr<FAptabaseAnalyticsProvider>(Module->AnalyticsProvider)->TrackError(ErrorMessage, ErrorType, StackTrace, bFatal);
}
}
}
Loading
Loading