C++ UE Logging made easier

Hello all, I’m getting into C++ and I realized I was adding many logs. The line to print a log is quite long, so I came up with a shorter version.

Original:

UE_LOG(LogDedicatedServer, Warning, TEXT("This is a log"));

My idea was to move this to a common place to be used throughout the whole project.
First we need to add a new macro, you can do it in any header file:

#define LOG(Message) UE_LOG(LogTemp, Warning, TEXT("[%s:%d] - %s"), *FString(__FUNCTION__), *FString::FromInt(__LINE__), *Message)

This will allow to log by using the following line:

LOG("This is a log test");

Now the question is, how to add parameters to it? What if I want to log a constant text with a variable?
The next macro comes in hand:

#define LOG_P1(Message, Param1) LOG(FString::Printf(TEXT(Message), *Param1))

Now, to use this:

LOG_P1("[%s] Trying to load items but not on server", CharacterName);

How the file looks with a method for two parameters:

#define LOG(Message) UE_LOG(LogDedicatedServer, Warning, TEXT("[%s:%d] - %s"), *FString(__FUNCTION__), *FString::FromInt(__LINE__), *Message)
#define LOG_P1(Message, Param1) LOG(FString::Printf(TEXT(Message), *Param1))
#define LOG_P2(Message, Param1, Param2) LOG(FString::Printf(TEXT(Message), *Param1, *Param2))

How to use it:

LOG("There was an error when updating database!");
LOG_P1("[%s] Trying to load items but not on server", CharacterName);
LOG_P2("About to update item [%s] location for [%s] ...", ItemUniqueId, CharacterName);

Hope this helps!

1 Like

you could do

#define LOG(Message, ...) UE_LOG(LogCategory, LogLevel, TEXT(Message), __VA_ARGS__)

then you only need the one for as many args as you need.

Indeed, I thought about that later.

This is great, thank you!

We’ve released Game Logs System (GLS), a plugin that allows you to view logs directly in your game through a dedicated overlay. With GLS, you can instantly access detailed logs and apply flexible filters by class, object, tag, and more, even in shipping builds. It’s compatible across platforms and supports gamepad and touchscreen input for easy use on consoles and mobile devices.

If you’re looking for a way to streamline debugging, GLS is available on the Unreal Fab!