Logging and Assertions
Logging and assertions are the first systems an engine needs and the last ones you want to fail. Every other subsystem reports through them, so they must work during startup, during shutdown, from any thread, and while the program is half-crashed.
What an engine logger needs
| Feature | Why |
|---|---|
Levels (Trace, Debug, Info, Warn, Error, Fatal) |
filter noise; ship with only Warn and above |
Channels (Render, Audio, Assets, …) |
turn one subsystem's chatter up without drowning in the rest |
| Sinks | the same message goes to the console, a file, the in-game console, an IDE output window |
| Source location | file and line, so a message leads straight to the code |
| Compile-time stripping | Trace/Debug calls cost nothing in shipping builds, including their argument formatting |
| Thread safety | worker threads log too; lines must not interleave mid-message |
| Crash buffer | the last few hundred lines kept in memory and written to the crash report |
A small logger
This logger has levels, channels with their own minimum level, pluggable sinks, and a macro that captures the line number with C++20's std::source_location and skips formatting when the message is filtered out:
#include <cstdarg>
#include <cstdio>
#include <functional>
#include <mutex>
#include <source_location>
#include <string>
#include <vector>
enum class Level { Trace, Debug, Info, Warn, Error };
enum class Channel { Core, Render, Assets, Count };
const char* levelName[] = {"TRACE", "DEBUG", "INFO ", "WARN ", "ERROR"};
const char* channelName[] = {"core", "render", "assets"};
struct Logger {
using Sink = std::function<void(Level, const std::string&)>;
Level minLevel[int(Channel::Count)] = {Level::Info, Level::Info, Level::Info};
std::vector<Sink> sinks;
std::mutex mutex;
bool enabled(Channel c, Level l) const { return l >= minLevel[int(c)]; }
void write(Channel c, Level l, std::source_location loc, const char* fmt, ...) {
char body[256];
va_list args;
va_start(args, fmt);
std::vsnprintf(body, sizeof body, fmt, args);
va_end(args);
char line[320];
std::snprintf(line, sizeof line, "[%s] %-6s line %u: %s", levelName[int(l)], channelName[int(c)],
unsigned(loc.line()), body);
std::lock_guard lock(mutex); // one whole line at a time
for (auto& sink : sinks) sink(l, line);
}
};
Logger gLog;
// The check happens before the arguments are formatted, so filtered calls are cheap.
#define LOG(ch, lvl, ...) \
do { if (gLog.enabled(Channel::ch, Level::lvl)) \
gLog.write(Channel::ch, Level::lvl, std::source_location::current(), __VA_ARGS__); } while (0)
int main() {
std::vector<std::string> crashBuffer; // a second sink: keep lines in memory
gLog.sinks.push_back([](Level, const std::string& s) { std::printf("%s\n", s.c_str()); });
gLog.sinks.push_back([&](Level l, const std::string& s) { if (l >= Level::Warn) crashBuffer.push_back(s); });
LOG(Core, Info, "engine starting, %d subsystems", 7);
LOG(Render, Debug, "this is filtered out: render is at Info");
gLog.minLevel[int(Channel::Render)] = Level::Debug; // e.g. typed into the dev console
LOG(Render, Debug, "created %d framebuffers", 3);
LOG(Assets, Warn, "texture '%s' missing, using fallback", "rock_albedo");
LOG(Assets, Error, "mesh '%s' has %d invalid indices", "cliff_02", 12);
std::printf("crash buffer holds %zu lines\n", crashBuffer.size());
}[INFO ] core line 48: engine starting, 7 subsystems
[DEBUG] render line 51: created 3 framebuffers
[WARN ] assets line 52: texture 'rock_albedo' missing, using fallback
[ERROR] assets line 53: mesh 'cliff_02' has 12 invalid indices
crash buffer holds 2 lines
The do { ... } while (0) wrapper makes the macro behave like one statement, so if (x) LOG(...); else ... compiles as expected. In a shipping build, define the macro for Trace and Debug as do {} while (0) and those calls disappear completely, arguments included.
Tip: Don't build your own formatting library.
{fmt}(the basis of C++20std::format) andspdlog(a logger built on{fmt}, with sinks, levels and async logging) are the usual choices. The model above usesprintf-style formatting only to stay short.
Assertions: catching bugs where they start
An assertion states something that must be true if the code is correct. When it fails, the bug is close by, instead of three systems later where a corrupt value finally crashes.
Engines rarely use plain assert from <cassert>. It disappears completely when NDEBUG is defined, prints a fixed message, and calls abort() with no way to continue. Engine asserts usually come in several flavors:
| Macro (names vary) | Checked in | Expression evaluated in release? | On failure |
|---|---|---|---|
ASSERT(cond) |
debug and development builds | no | log, break into the debugger |
VERIFY(cond) |
all builds | yes (use it around calls with side effects) | log, break in debug |
ENSURE(cond) |
all builds | yes | log once, continue (for recoverable data errors) |
FATAL(msg) |
all builds | – | log, write a crash report, exit |
Unreal's check, verify and ensure follow exactly this split.
The engine routes failures through a handler, so the editor can show a dialog with Break / Ignore / Ignore always, a test runner can record them, and a shipping build can write a crash report:
#include <cstdio>
#include <functional>
enum class AssertAction { Break, Ignore, IgnoreAlways };
using AssertHandler = std::function<AssertAction(const char* expr, const char* msg, int line)>;
AssertHandler gAssertHandler;
// One static flag per assert site implements "ignore always".
#define ASSERT(cond, msg) \
do { \
static bool ignoreAlways = false; \
if (!(cond) && !ignoreAlways) { \
switch (gAssertHandler(#cond, msg, __LINE__)) { \
case AssertAction::Break: std::puts(" -> would break into debugger"); break; \
case AssertAction::IgnoreAlways: ignoreAlways = true; break; \
case AssertAction::Ignore: break; \
} \
} \
} while (0)
float safeDivide(float a, float b) {
ASSERT(b != 0.0f, "division by zero");
return b != 0.0f ? a / b : 0.0f;
}
int main() {
int failures = 0;
// A test-runner handler: count failures, choose an action, never stop the program.
gAssertHandler = [&](const char* expr, const char* msg, int line) {
failures++;
std::printf("ASSERT FAILED (line %d): %s [%s]\n", line, expr, msg);
return failures == 1 ? AssertAction::Break : AssertAction::IgnoreAlways;
};
for (int i = 0; i < 4; i++) {
float r = safeDivide(10.0f, float(i % 2)); // b is 0 on even i
std::printf("call %d -> %.1f\n", i, r);
}
std::printf("handler was called %d times\n", failures);
}ASSERT FAILED (line 23): b != 0.0f [division by zero]
-> would break into debugger
call 0 -> 0.0
call 1 -> 10.0
ASSERT FAILED (line 23): b != 0.0f [division by zero]
call 2 -> 0.0
call 3 -> 10.0
handler was called 2 times
The assert fires on call 0 (the handler chooses Break), fires again on call 2 (the handler chooses Ignore always), and stays silent afterwards. This is how editors let you continue past a noisy assert without recompiling.
Breaking into the debugger
A real Break action stops in the debugger on the assert line. There is no portable way to do it before C++26's std::breakpoint(), so engines wrap the compiler intrinsics:
#if defined(_MSC_VER)
#define DEBUG_BREAK() __debugbreak()
#elif defined(__clang__)
#define DEBUG_BREAK() __builtin_debugtrap()
#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
#define DEBUG_BREAK() __asm__ volatile("int3")
#else
#include <csignal>
#define DEBUG_BREAK() std::raise(SIGTRAP)
#endifPut the break inside the macro, not inside a helper function, so the debugger stops on the asserting line instead of one frame deeper.
Rules of thumb
- Assert on programmer errors (a null that can't be null, an index out of range, a handle from the wrong pool). Handle data errors (a missing file, a bad asset, a mod with broken values) with logging and fallbacks: missing textures become a bright checkerboard, not a crash.
- Never put side effects inside
ASSERT:ASSERT(file.open())stops opening the file in release builds. That is whatVERIFYis for. - Log once, not every frame. A warning printed 60 times a second hides every other message; keep a "logged already" flag or rate-limit by message.
- Flush the crash buffer from the crash handler, then write it next to the minidump. The last warnings before a crash are often the whole story.
Test yourself
Why does the LOG macro check enabled() before calling write()?
- To make logging thread-safe
- So filtered-out messages skip formatting and their arguments cost almost nothing
- Because write() cannot handle Debug messages
- To capture the source line
What is wrong with ASSERT(loadConfig()) in an engine whose ASSERT is compiled out in release builds?
- Nothing
- loadConfig() is not called at all in release builds
- It asserts twice
- ASSERT cannot call functions
A level designer's file has a typo in a material name. What should the engine do?
- Fire a fatal assert
- Log a warning and use a visible fallback material
- Silently skip the object
- Crash so the designer notices