TExcelTAD
Home › Unreal Engine 5 with C++ › Logging & Assertions

Logging & Assertions

When something goes wrong in a running game, the log is usually the first and best evidence you have. Unreal's logging is structured around categories and verbosity levels, so you can turn the noise of one system up without drowning in everyone else's.

UE_LOG and your own category

cpp
// ArenaLog.h
#pragma once
#include "Logging/LogMacros.h"

DECLARE_LOG_CATEGORY_EXTERN(LogArena, Log, All);    // default verbosity Log, compile-time max All

// ArenaLog.cpp
#include "ArenaLog.h"
DEFINE_LOG_CATEGORY(LogArena);
cpp
UE_LOG(LogArena, Log, TEXT("Wave %d started with %d enemies"), WaveIndex, Count);
UE_LOG(LogArena, Warning, TEXT("%s has no weapon"), *GetNameSafe(this));
UE_LOG(LogArena, Error, TEXT("Spawn failed at %s"), *Location.ToString());
UE_LOG(LogArena, Verbose, TEXT("Target score %.2f"), Score);   // hidden unless verbosity is raised
Verbosity Shown by default Use for
Fatal always, then crashes unrecoverable states (prefer checkf)
Error yes, red something failed and the game is now wrong
Warning yes, yellow something unexpected that was handled
Display yes important info shown even in the console
Log yes (to the log file and Output Log) normal tracing
Verbose, VeryVerbose no detail you switch on while debugging

Raise a category's verbosity at runtime with the console command log LogArena Verbose, or at startup with -LogCmds="LogArena Verbose", or permanently in DefaultEngine.ini under [Core.Log]. Logs are written to Saved/Logs/<Project>.log; in a packaged game, to the project's Saved/Logs folder in the user's app-data folder.

Structured logging (#include "Logging/StructuredLog.h", UE 5.2+) uses named or positional fields instead of printf formats, which removes a whole class of format-string bugs:

cpp
UE_LOGFMT(LogArena, Log, "Wave {Wave} started with {Count} enemies", WaveIndex, Count);

For quick visual debugging, print to the screen (development builds only):

cpp
if (GEngine)
{
    GEngine->AddOnScreenDebugMessage(-1, 3.f, FColor::Yellow, FString::Printf(TEXT("HP %.0f"), Health));
}

GetNameSafe(Obj) returns "None" for null, which makes it the safe way to print an object name in a log line.

Assertions: check, verify, ensure

Macro When it fails Compiled into Shipping? Use for
check(Expr) / checkf(Expr, Fmt, …) crashes with the message no (removed) invariants: "this can't happen unless the code is broken"
verify(Expr) crashes the expression still runs in Shipping; the check doesn't when the expression has a side effect
ensure(Expr) / ensureMsgf(…) logs an error with a callstack once, then continues; returns the bool the expression is evaluated; reporting is off recoverable problems you want to know about
checkNoEntry(), unimplemented() crash if reached no impossible switch branches
cpp
void UArenaInventory::Equip(int32 Slot)
{
    check(Slot >= 0);                                         // a caller bug: crash in development
    if (!ensureMsgf(Items.IsValidIndex(Slot), TEXT("Slot %d out of %d"), Slot, Items.Num()))
    {
        return;                                               // report once, then recover gracefully
    }
    ...
}

ensure fires only the first time per call site (per session), so it doesn't flood the log. Attaching a debugger makes both check and ensure break right there. A good default: ensure for gameplay data problems, check for programmer errors that would corrupt state if ignored.

A model of categories, verbosity and ensure-once

cpp · try it yourself
#include <iostream>
#include <map>
#include <set>
#include <string>

enum class Verbosity { Fatal, Error, Warning, Display, Log, Verbose, VeryVerbose };
const char* Names[] = {"Fatal", "Error", "Warning", "Display", "Log", "Verbose", "VeryVerbose"};

std::map<std::string, Verbosity> Categories = {{"LogArena", Verbosity::Log}, {"LogAI", Verbosity::Warning}};

void Log(const std::string& cat, Verbosity v, const std::string& msg) {
    if (v > Categories[cat]) return;                       // filtered out by the category's level
    std::cout << cat << ": " << (v == Verbosity::Log ? "" : std::string(Names[(int)v]) + ": ") << msg << "\n";
}

std::set<int> FiredEnsures;
bool Ensure(bool ok, int callSite, const std::string& what) {
    if (!ok && FiredEnsures.insert(callSite).second)
        std::cout << "LogOutputDevice: Error: Ensure condition failed: " << what << " [callstack]\n";
    return ok;
}

int main() {
    Log("LogArena", Verbosity::Log, "Wave 1 started");
    Log("LogArena", Verbosity::Verbose, "scoring 12 targets");          // hidden
    Log("LogAI", Verbosity::Log, "path found");                         // hidden: LogAI is at Warning
    Log("LogAI", Verbosity::Warning, "no navmesh under Grunt_3");

    std::cout << "> log LogArena Verbose\n";
    Categories["LogArena"] = Verbosity::Verbose;
    Log("LogArena", Verbosity::Verbose, "scoring 12 targets");

    for (int slot : {2, 7, 9}) {                                        // the same bad call site, three times
        if (!Ensure(slot < 5, /*callSite*/ 42, "Items.IsValidIndex(Slot)")) {
            Log("LogArena", Verbosity::Warning, "skipped equip of slot " + std::to_string(slot));
            continue;
        }
        Log("LogArena", Verbosity::Log, "equipped slot " + std::to_string(slot));
    }
}
LogArena: Wave 1 started
LogAI: Warning: no navmesh under Grunt_3
> log LogArena Verbose
LogArena: Verbose: scoring 12 targets
LogArena: equipped slot 2
LogOutputDevice: Error: Ensure condition failed: Items.IsValidIndex(Slot) [callstack]
LogArena: Warning: skipped equip of slot 7
LogArena: Warning: skipped equip of slot 9

Habits that pay off

  • Log state transitions (wave started, ability activated, player died), not every frame. A log line per tick makes the log useless and the game slower.
  • Put identifiers in every line: GetNameSafe(this), the player name, the net role. In multiplayer, prefix with server/client. Two PIE windows write to the same log.
  • Use ensure + early return instead of if (!X) return; for things that "shouldn't" be null. Silent returns hide bugs for months.
  • Remove or demote noisy logs before merging; teammates read the same Output Log.

Test yourself

Which macro still evaluates its expression in Shipping builds?

  1. check
  2. checkf
  3. verify
  4. checkNoEntry

How often does a failing ensure at one call site report?

  1. Every time
  2. Once per session for that call site
  3. Never in development builds
  4. Only when a debugger is attached

How do you see UE_LOG(LogArena, Verbose, ...) lines while the game runs?

  1. They are always shown
  2. Run the console command log LogArena Verbose
  3. Rebuild in Shipping
  4. Use AddOnScreenDebugMessage