How to declare Log category that can be accessed by all classes (like LogTemp)?

What is the process of declaring a log category that can be accessed with the UE_LOG macro, without having to manually include some file in any class that needs to use this log category?

I have tried including it in the module .h and .cpp, but I get linking errors in some cases, like trying to include the module .h in files of another module. Sometimes things compile and run in-editor, but compiling fails for a packaged build.

Logging is an extremely basic function, and I can’t figure out how to use it without strange issues. And I haven’t found good information on it either, it’s always very basic instructions on making a log category work within one class, with no re-use instructions for a more general category.

I would very much like to be able to use a custom log category without extra include hassle, like LogTemp, which is somehow accessible in any class of any module, no linking errors.

Any help would be appreciated.

This wiki page has all the info.

1 Like

I have also run into the same issue today and have probably found the solution to your issue. Let’s look at the example of LogTemp:

CoreGlobals.h:

CORE_API DECLARE_LOG_CATEGORY_EXTERN(LogTemp, Log, All);

CoreGlobals.cpp:

DEFINE_LOG_CATEGORY(LogTemp);

You actually do include the CoreGlobals in any of your headers as long as you #include "CoreMinimal.h" which in return includes CoreGlobals.h. Thus, you can use LogTemp anywhere.

The key to being able to use your custom log category in other modules but the one where it is defined in, however, seems to be the CORE_API directive right before you declare the log temp category. Without it it is not possible to use the log category in another module (Though it might be possible to redefine DEFINE_LOG_CATEGORY(LogTemp) in your second module, but that should be avoided I feel).

So your declaration could look like:

MyLogCategory.h

MYGAME_API DECLARE_LOG_CATEGORY_EXTERN(LogMyGameLog, Log, All);

MyLogCategory.cpp

DEFINE_LOG_CATEGORY(LogMyGameLog);

Beware, you still need to include the header, in which the category is defined, in the class where you want to use the category.

MyCategoryUserInMyOtherModule.cpp

#include "MyGame/MyLogCategory.h"

AND obviously you need to set up the dependency to the category’s module in the other module where you wanna use it. That happens in the PublicDependencyModuleNames in your MyOtherModule.Build.cs.

PublicDependencyModuleNames.AddRange(new string[] { "Core", "MyGame" });

It is possible to define the category in your module’s class, too, such as:

MyGame.h

MYGAME_API DECLARE_LOG_CATEGORY_EXTERN(LogMyGameLog, Log, All);

MyGame.cpp

DEFINE_LOG_CATEGORY(LogMyGameLog);

But you will still need to #include "MyGame/MyGame.h" and have the dependency set correctly ofc.

4 Likes

Appreciate your greatly helpful reply as this is not noted anywhere.