Quick answer: Subscribe a static method to Application.logMessageReceivedThreaded from a [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)] method, keep only LogType.Exception, Error and Assert, push each distinct error onto a thread-safe queue, and drain that queue in Update with a UnityWebRequest POST. Do not log or touch Unity APIs inside the handler. This catches every exception Unity logs, but not native crashes, which end the process before managed code can react.

Unity does not crash when a script throws. It catches the exception, prints it to the Player.log on the player’s disk, skips the rest of that method, and carries on with the next frame. The player sees a door that will not open or an inventory that stops updating, and you see nothing, because the only record is a file on a machine you will never touch. Application.logMessageReceived is the hook that turns those silent log lines into something you can send to a server. This guide covers what the callback gives you, the three mistakes that make it unreliable, and a complete script you can drop into a project.

What Application.logMessageReceived gives you

Both events use the same delegate, Application.LogCallback:

void OnLog(string condition, string stackTrace, LogType type)

condition is the message text. For an exception it is the type and message joined together, for example NullReferenceException: Object reference not set to an instance of an object. stackTrace is the trace as a multi-line string, one frame per line. type tells you what kind of entry it is:

LogTypeWhere it comes from
ExceptionAn exception Unity caught in one of your callbacks (Update, Start, a coroutine, a UI event), or a call to Debug.LogException
ErrorDebug.LogError, plus errors the engine itself reports
AssertA failed Debug.Assert or Debug.LogAssertion
WarningDebug.LogWarning and engine warnings
LogDebug.Log

For error reporting you want the first three. Warnings and plain logs are useful as context, so many reporters keep the last 50 lines of everything in a ring buffer and attach them to each error they send.

logMessageReceived vs logMessageReceivedThreaded

The two events differ in which messages they deliver and where your handler runs.

Subscribe to one, not both. If you subscribe to both, every main-thread message arrives twice. The threaded event is the better choice for error reporting because it sees everything, but it puts two rules on your handler: it must be thread-safe, and it must not call Unity APIs, almost all of which are main-thread only. In practice the handler should do nothing except filter, build a small object and put it on a ConcurrentQueue.

Subscribe before the first scene loads

A reporter that subscribes in the Start of a component in your main menu misses every error thrown while that scene was loading, which is exactly when broken builds fail. Install it from a static method that Unity calls before any scene object exists:

[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Install()
{
    var go = new GameObject("ErrorReporter");
    DontDestroyOnLoad(go);
    go.AddComponent<ErrorReporter>();
}

This needs no prefab and no scene setup, so it cannot be forgotten in a new scene. Unsubscribe in OnDestroy with -=. A static event keeps a reference to every subscriber, and with domain reload disabled in the editor a stale handler survives into the next play session and reports everything twice.

Why the stackTrace parameter is sometimes empty

There are two different sources for that string. For an exception, Unity passes the exception’s own managed stack trace, which is always there. For Debug.LogError, Debug.LogWarning and Debug.Log, Unity generates a trace at the moment of the call, and whether it does so is a setting. In Project Settings > Player > Other Settings there is a stack trace option per log type with three values: None, ScriptOnly and Full. If Error is set to None, every Debug.LogError arrives with an empty stackTrace. You can also set it from code:

Application.SetStackTraceLogType(LogType.Error, StackTraceLogType.ScriptOnly);
Application.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);

ScriptOnly for errors and None for plain logs is a sensible shipping configuration. Generating a trace for every Debug.Log is measurable overhead in a hot loop.

The quality of the trace also depends on the build. A development build includes file names and line numbers. A release build generally gives you method names without usable line numbers, which is still enough to find the failing method. With IL2CPP, newer editor versions add an IL2CPP Stack Trace Information option in Player Settings that can include file and line at the cost of a larger build. Check what your version offers before promising yourself line numbers in production.

Three ways the handler bites back

  1. Logging from inside the handler. A Debug.Log in the callback raises the event again. So does anything you call that logs on failure. Keep the handler silent, and keep the code that sends reports silent too.
  2. The same exception every frame. A null reference in Update fires 60 times a second on every object that has the script. Without deduplication one bug becomes thousands of requests in a minute and your endpoint starts rate limiting you. Remember what you have already sent this session and cap the total.
  3. Calling Unity from the wrong thread. Application.version, SystemInfo and UnityWebRequest are main-thread APIs. Read the values you need once in Awake and cache them in fields the handler can read safely.

There is a fourth, quieter one. When the player is offline, UnityWebRequest can itself write an error line to the log. That line reaches your handler, which queues a report about the failed report. The seen-set in the script below breaks that loop after one round because the title repeats.

Send Unity exceptions to a server with UnityWebRequest

This is a complete reporter for Unity 2020.3 and later. It posts JSON to a bug-report endpoint. The URL, header and field names are Bugnet’s public submit API, and the structure is the same for any HTTP endpoint you control.

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;

public class ErrorReporter : MonoBehaviour
{
    const string Url = "https://api.bugnet.io/api/bugs/submit";
    const string ApiKey = "sk_live_your_project_key";
    const int MaxReportsPerSession = 20;

    [Serializable]
    class Report
    {
        public string title;
        public string description;
        public string category;
        public string priority;
        public string platform;
        public string game_version;
        public string os_info;
        public string device_info;
        public bool auto_captured = true;
    }

    static readonly ConcurrentQueue<Report> Pending = new ConcurrentQueue<Report>();
    static readonly HashSet<string> Seen = new HashSet<string>();
    static string _platform, _version, _os, _device;

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
    static void Install()
    {
        var go = new GameObject("ErrorReporter");
        DontDestroyOnLoad(go);
        go.AddComponent<ErrorReporter>();
    }

    void Awake()
    {
        // Main-thread values, cached so the handler never calls Unity.
        _platform = Application.platform.ToString();
        _version = Application.version;
        _os = SystemInfo.operatingSystem;
        _device = SystemInfo.deviceModel + ", " + SystemInfo.graphicsDeviceName
                  + ", " + SystemInfo.systemMemorySize + " MB RAM";
        lock (Seen) Seen.Clear();
        Application.logMessageReceivedThreaded += OnLog;
    }

    void OnDestroy()
    {
        Application.logMessageReceivedThreaded -= OnLog;
    }

    // Runs on whichever thread logged. No Unity calls, no Debug.Log.
    static void OnLog(string condition, string stackTrace, LogType type)
    {
        if (type != LogType.Exception && type != LogType.Error && type != LogType.Assert)
            return;

        string title = MakeTitle(condition, stackTrace, type);
        lock (Seen)
        {
            if (Seen.Count >= MaxReportsPerSession || !Seen.Add(title)) return;
        }

        Pending.Enqueue(new Report
        {
            title = title,
            description = condition + "\n\n" + stackTrace,
            category = type == LogType.Error ? "other" : "crash",
            priority = type == LogType.Error ? "medium" : "high",
            platform = _platform,
            game_version = _version,
            os_info = _os,
            device_info = _device
        });
    }

    void Update()
    {
        while (Pending.TryDequeue(out var report))
            StartCoroutine(Send(report));
    }

    IEnumerator Send(Report report)
    {
        byte[] body = Encoding.UTF8.GetBytes(JsonUtility.ToJson(report));
        using (var req = new UnityWebRequest(Url, UnityWebRequest.kHttpVerbPOST))
        {
            req.uploadHandler = new UploadHandlerRaw(body);
            req.downloadHandler = new DownloadHandlerBuffer();
            req.SetRequestHeader("Content-Type", "application/json");
            req.SetRequestHeader("X-API-Key", ApiKey);
            req.timeout = 10;
            yield return req.SendWebRequest();
            // Silent on failure on purpose: logging here re-enters OnLog.
        }
    }

    static string MakeTitle(string condition, string stackTrace, LogType type)
    {
        string head = condition ?? "";
        if (type == LogType.Exception)
        {
            int colon = head.IndexOf(':');
            if (colon > 0) head = head.Substring(0, colon);
        }

        string frame = "";
        if (!string.IsNullOrEmpty(stackTrace))
        {
            int newline = stackTrace.IndexOf('\n');
            frame = (newline > 0 ? stackTrace.Substring(0, newline) : stackTrace).Trim();
            if (frame.StartsWith("at ")) frame = frame.Substring(3);
            // Cut the file path, line number and IL offset: they vary per build.
            int cut = frame.IndexOf(" (at ");
            if (cut < 0) cut = frame.IndexOf(" [0x");
            if (cut < 0) cut = frame.IndexOf(" in ");
            if (cut > 0) frame = frame.Substring(0, cut);
        }

        string title = frame.Length > 0 ? head + " in " + frame : head;
        return title.Length > 200 ? title.Substring(0, 200) : title;
    }
}

The handler only filters, deduplicates under a lock and enqueues. Update runs on the main thread, so that is where the coroutine and the web request start. JsonUtility serializes the public fields of the [Serializable] class, which is why the field names match the JSON keys the server expects. Setting auto_captured tells Bugnet the code filed this report, so the category and priority you chose are kept.

Give every error a stable title

How you name an error decides whether a thousand occurrences show up as one issue with a count or as a thousand separate issues. Bugnet stacks a report onto an existing one when the title matches exactly, and most trackers group on something similar.

The raw condition is a poor title because exception messages often contain data. KeyNotFoundException: The given key 'item_4812' was not present in the dictionary is a different string for every item ID. MakeTitle above keeps the exception type, drops the message, and appends the first stack frame with the file path removed. The result looks like NullReferenceException in PlayerController.Update (), which is the same on every machine and tells you where to look. The full message still goes in the description.

For Debug.LogError the message is yours, so keep the variable parts out of the first sentence or pass them as context in a second log line.

Exceptions that never reach the log callback

Unity logs what it catches. Three kinds of exception are thrown where Unity is not the one catching.

static void Forward(Exception ex)
{
    if (ex == null) return;
    OnLog(ex.GetType().Name + ": " + ex.Message, ex.StackTrace ?? "", LogType.Exception);
}

// In Awake, next to the log subscription:
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
    Forward(e.ExceptionObject as Exception);

System.Threading.Tasks.TaskScheduler.UnobservedTaskException += (sender, e) =>
{
    Forward(e.Exception.GetBaseException());
    e.SetObserved();
};

Both go through the same static handler, so the same filtering and deduplication apply. MakeTitle already copes with the plain .NET trace format these exceptions carry, where frames start with at and end with an IL offset.

What none of this can see: native crashes

Everything above is managed code reacting to managed errors. An access violation inside the engine, a graphics driver, a native plugin or IL2CPP-generated code ends the process immediately. No callback runs and nothing is sent. On desktop Unity’s own crash handler writes a crash folder with a dump and a copy of the log, and the Player.log from that run is still on disk. Where Unity keeps those files is covered separately.

The usual way to learn about these is on the next launch. Write a small marker file when the game starts and delete it in Application.quitting. If the marker is already there at startup, the previous session did not exit cleanly, and you can send a report that says so along with the tail of the previous log. It will not tell you the faulting address, but it tells you how often the game dies without a managed exception, on which hardware and in which version, and that is usually the first thing you need to know.

What Bugnet’s Unity SDK does with this hook

The Bugnet Unity SDK is a single C# file that subscribes to Application.logMessageReceived in Init, twice. One handler keeps a rolling buffer of recent log lines. The other files every Exception, Error and Assert as a bug report with the stack trace, the recent log lines, a screenshot when screenshot capture is on for the project, and the OS, device and game version, once per distinct message per session. A dashboard setting decides whether errors raised inside the editor are filed at all, so play-mode noise stays out. Reports land in a dashboard where identical titles stack with an occurrence count, next to the reports players write through the in-game widget.

If you would rather keep your own reporter, the script above talks to the same submit endpoint the SDK uses. The free plan covers one project and up to 100 bug reports in total, which is enough to find out what your build is really doing on other people’s machines. Setup for both routes is in the SDK docs.

Frequently asked questions

What is the difference between Application.logMessageReceived and logMessageReceivedThreaded?

logMessageReceived is only raised for messages logged on the main thread, and it runs on the main thread. logMessageReceivedThreaded is raised for messages from every thread, on whichever thread logged, so its handler has to be thread-safe and must not call Unity APIs. Subscribe to one of them, not both, or main-thread messages arrive twice.

How do I catch all exceptions in Unity?

Subscribe to Application.logMessageReceivedThreaded and filter for LogType.Exception. Unity catches exceptions thrown from MonoBehaviour callbacks and coroutines and logs them, so they arrive there. Add AppDomain.CurrentDomain.UnhandledException for threads you start yourself and TaskScheduler.UnobservedTaskException for Tasks nobody awaited.

Why is the stackTrace parameter empty in my Unity build?

For Debug.LogError and Debug.Log the trace is generated by Unity according to the Stack Trace setting for that log type in Player Settings, and it is empty when that is set to None. Change it there or call Application.SetStackTraceLogType. Exceptions carry their own managed stack trace, so they are not affected.

Can I send Unity errors to a server from the log callback?

Not directly. UnityWebRequest must be used on the main thread and a request started inside the handler can log and re-enter it. Queue the error in the handler and send it from Update with a coroutine on a DontDestroyOnLoad object.

Does Application.logMessageReceived catch native crashes?

No. An access violation in the engine, a graphics driver or a native plugin kills the process before any managed code runs. Unity writes its own crash folder and Player.log for those, which you can pick up on the next launch.

Subscribe before the first scene loads, never log from inside the handler, and send each distinct error once. Everything else is detail.