- Add #define to your main header file (ProjectName.h), defining LOCTEXT_NAMESPACE as something unique to your codebase:
#define LOCTEXT_NAMESPACE "Chapter11Namespace"
This #define is used by the LOCTEXT() macro, which we use to generate FText objects, but is not seen in output messages.
- Declare your FMessageLog by constructing it somewhere very global. You can use extern in your ProjectName.h file. Consider the following piece of code as an example:
#define LOCTEXT_NAMESPACE "Chapter11Namespace"
#define FTEXT(x) LOCTEXT(x, x)
extern FName LoggerName;
void CreateLog(FName logName);
- Then, create your FMessageLog by defining it in a .cpp file and registering it with MessageLogModule. Be sure to give your logger a clear and unique name on construction. It's the category of your log that will appear to the left of your log messages in Output Log. For example, ProjectName.cpp:
#include "Chapter_11.h"
#include "Modules/ModuleManager.h"
#include "MessageLog/Public/MessageLogModule.h"
#include "MessageLog.h"
// ...
FName LoggerName("MessageLogChapter11");
void CreateLog(FName logName)
{
FMessageLogModule& MessageLogModule = FModuleManager::LoadModuleChecked<FMessageLogModule>("MessageLog");
FMessageLogInitializationOptions InitOptions;
InitOptions.bShowPages = true;
InitOptions.bShowFilters = true;
FText LogListingName = FTEXT("Chapter 11's Log Listing");
MessageLogModule.RegisterLogListing(logName, LogListingName, InitOptions);
}
- Then, head back to somewhere in your code to actually create the log and use it. For example, we can add the following GameModeBase class's BeginPlay method:
void AChapter_11GameModeBase::BeginPlay()
{
// 11-01 - Core/Logging API - Defining a custom log
// category
// Traditional Logging
UE_LOG(LogTemp, Warning, TEXT("Message %d"), 1);
// Our custom log type
UE_LOG(LogCh11, Display, TEXT("A display message, log is working" ) ); // shows in gray
UE_LOG(LogCh11, Warning, TEXT("A warning message"));
UE_LOG(LogCh11, Error, TEXT("An error message "));
// 11-02 - Core/Logging API - FMessageLog to write
// messages to the Message Log
CreateLog(LoggerName);
// Retrieve the Log by using the LoggerName.
FMessageLog logger(LoggerName);
logger.Warning(FTEXT("A warning message from gamemode"));
}
The KEY to LOCTEXT (first argument) must be unique or you will get a previously hashed string back. If you'd like, you can include a #define that repeats the argument to LOCTEXT twice, as we did earlier:
#define FTEXT(x) LOCTEXT(x, x)
#define FTEXT(x) LOCTEXT(x, x)
- Log your messages using the following code:
logger.Info( FTEXT( "Info to log" ) ); logger.Warning( FTEXT( "Warning text to log" ) ); logger.Error( FTEXT( "Error text to log" ) );
This code utilizes the FTEXT() macro we defined earlier. Ensure it is in your codebase.