Structure of classes in good Game Engine?

Started by
45 comments, last by Cygon 11 years, 9 months ago

They have to use a different logger implementation for retail builds. It could just swallow/ignore log entries (and probably would ignore/disable a lot of logging channels), or pipe them to the game's console (maybe colouring channels), or a text file inside %appdata%, etc... You don't need to inherit an interface or anything to do this, a simple ifdef to select different implementations is often good enough.


I prefer a single logging object with multiple logging channels, where each channel can be of a different type. i.e. a FileLoggingChannel for writing to file, a ConsoleLoggingChannel for writing to the console, a SocketLoggingChannel for sending the logs over the network to an external logging application/server. Each channel type just implements a simple interface like:


class ILogChannel
{
public:
virtual void open(){}
virtual void close(){}
virtual void log( const LogMessage& msg ) = 0;
};



and is responsible only for outputting the log message object. The main logging object handles adding file, line, function info, process and thread IDs, timestamps, possibly even call stacks when logging exceptions/errors, etc, to the message object. All about flexibility. If you want to use an external debugging tool, the game/application can even detect the presence of the tool when it starts up and add a SocketLoggingChannel if the tool is running, or a FileLoggingChannel if it's not. Then you can pass the same build around to different machines without having to recompile or distribute the debugging tool (or just use a config file).

I would also like to point out that opening/closing files on every log entry as a way of flushing the buffers is a little silly. Unless you're using something like std::fstream that uses it's own internal stream buffer, you usually don't need to worry about a process crash; OS disk buffering is typically done via a system write-through cache that exists outside of the process space, so only a hard system crash/power failure would compromise the buffered data (and opening/closing a file does not force the data from the cache to the device anyway.) Even in cases where there is no system write-through cache, you can typically flush a buffer with much less overhead than open/close on every write.
Advertisement
Interesting discussion to follow as a Java developer. Are the logging conventions in C++ really that diverse? For Java there is almost a de-facto standard for logging, and in all the cases I've seen it used it's simply through a static member in each class, e.g.:


public class StdPlayerCreator implements PlayerCreator {
public static final Logger LOG = Logger.getLogger(StdPlayerCreator.class);
...

LOG.error("Internal error, failed to find a settlement");


The parameter to getLogger() is effectively just a hierarchical label. It allows you to configure the logging output threshold on a class or package hierarchy. (This configuration is in a separate XML.)

Yes the above would break if multiple "runs" which should have distinct logs are run in the same JVM (java process). However that is rare and the logger can be instantiated differently for such use cases.

(Sorry for the tangential comment... ;-) )

That still raises the obvious question: why is your logger an object/class to begin with?

Specifically, client code wants to log a message, not to "Get" a Log instance, worry about Log references, and still have to call Log methods to do something useful. Free functions are clearly the best fitting API for logging; static variables can also be used with functions and classes can be used behind the scenes, so nothing is lost from a technological standpoint.

Omae Wa Mou Shindeiru


Specifically, client code wants to log a message, not to "Get" a Log instance, worry about Log references, and still have to call Log methods to do something useful. Free functions are clearly the best fitting API for logging; static variables can also be used with functions and classes can be used behind the scenes, so nothing is lost from a technological standpoint.


Unless you want to log something other than simple strings. What if you want to log other values as well? You could use a printf-style log function, but then you lose type safety and must spend time generating an appropriate format string, and hope that the type of a variable never changes... with the possibility that your logging will itself cause a crash or bug! Or you would need to generate the string some other way before calling your log function.

Or you could do something like:


Logger::warning(__FILE__,__LINE__) << "foo is out of expected range: " << foo << endlog;



or use a macro to eliminate some of the dirty work, and just do something like this:
WARNING << "foo is out of expected range: " << foo << endlog;

or even (my preference):
cs_warn( "foo is out of expected range: ", foo );

which makes adding logging much more pleasant, while maintaining type safety.

You could also generate a whole crapload of templated free functions to accomplish something similar, but that makes things a little more difficult when you need to mix integral types with user-defined types, and is generally quite a bit less flexible overall.
My opinion:

  • Using globals is always wrong. They create a mess with initialization ordering, threading and dependencies.
  • A free function would open the door for dozens of globals. Enable/Disable logging to OutputDebugString() - you need a global flag. Write log to a file? You need another global flag and a global variable storing the file handle.
  • Singletons, global variables in disguise, rob you of all flexibility (like logging networking related stuff in file 1 and graphics related stuff in file 2) and gets in the way of unit testing.
  • Passing some semi-global application class around is just hugely increasing dependencies since now you don't know which objects a class will look up through the application class (the service locator anti-pattern).


The way you're doing it (constructor injection) is quite alright, though I agree that having to pass your logger everywhere you want to create an instance of class X tends to have a negative impact on usability and adds complexity to the interface.

Some other options:

  • Equip your classes with a SetLogger() method. By default, the logger is NULL, therefore no logging is performed. If you want to log something, you simply assign the logger to the class post construction.
  • Do not add logging to your classes directly, wrap them in a logging wrapper (eg. a LoggedRenderer around your Renderer). Obviously can only log calls and results and with some effort exceptions leaving the renderer.
  • Add a Log event (as in signals/slots) to your class. This is just another variant of the SetLogger() idea, of course.
  • Forfeit logging altogether. I've done this in my code. I'm going all-out with assertions for pedantically checking internal states and exceptions for any usage error. Since the point of logging is to help you find the cause of errors quickly, by not letting any inconsistency, bad return code or missing capability slip under the carpet you remove the need for logging.
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.

That's fine, each style to it's own, but this is still an arbitrary choice by the API designer to use a singleton as a restriction on the end-user developers usage. You could replace the UIApplication singleton by, inside main, making local variables for a window, an event queue, a URL fetcher, etc... and then having the choice weather to make them global variables (e.g. via a singleton) or not, ourselves (i.e. the end-user of the API).


I suppose your right that it's not a requirement that a singleton be used, but at the end of the day, it makes the API easier to use. I'm not saying singletons are the solution to every problem when it comes to needing dependencies throughout your application, but it does make sense from time to time. I am also of the belief that if you are trying so damn hard to not use a particular design pattern that you end up bending over backwards, you should probably take a step back and wonder if you aren't just being a bit evangelical and maybe just maybe that design pattern exists for a reason, and you should stop trying to fight its use in a legitimate use case. I doubt we will ever see eye to eye on this though, so I'm going to gracefully walk away and say, let's agree to disagree smile.png
The main logging object handles adding file, line, function info, process and thread IDs, timestamps, possibly even call stacks when logging exceptions/errors, etc, to the message object
Do you need an object to do that? That's where the free-function comes in for me.
I prefer a single logging object with multiple logging channels, where each channel can be of a different type. i.e. a FileLoggingChannel for writing to file, a ConsoleLoggingChannel for writing to the console, a SocketLoggingChannel for sending the logs over the network to an external logging application/server. Each channel type just implements a simple interface[/quote]I'd prefer to avoid the uneccesary inheritance here and keep your different log back-ends decoupled:class SocketLoggingChannel : NonCopyable
{
public:
SocketLoggingChannel(...);
~SocketLoggingChannel();
void log( const char* msg );
};

class ConsoleLoggingChannel: NonCopyable
{
public:
ConsoleLoggingChannel(...);
~ConsoleLoggingChannel();
void log( const char* msg );
};

cosnt char* FormatLogMessage(const char* fmt, ...);
typedef std::vector<std::function<void(const char*)>> ChannelVec;

#define Log(channels, fmt, ...) do { \
cosnt char* msg = FormatLogMessage(fmt, __VA_ARGS__); \
for (auto &c : channels){ \
c(msg); \
} \
} while(0) //
I am also in the no-need-for-classes camp.
You already have std::cout, std::cerr and std::clog. Why not use them for what they exist?

EDIT: well they are classes... :) Generally I meant don't overengineer something like that
Whether your logger needs to be a separate class or not really depends on if it needs to keep any data. For example a logging system I worked with had the ability to work in combination with the scripting language by capturing all log messages send during the execution of a certain function, making debugging scripts a lot faster as you could visualize where something went wrong. While this did really improve debugging (specially for scripting languages where you can't put breakpoints), in your case I don't think you will need things like that yet. Specially for simple applicatins, simple error output works fine. And if your functions don't need to touch member variables you should make them static, and if your class only has statics they don't need to be in a class.

As for singletons: I have been them being used to death in engines. It's really fun to see the engine being initialized before you even loaded the application because someone is calling the singleton from a static initializer. Even nicer is to clean up the memory on shutdown, you have to explicitly destroy the singleton, only to have somebody still requesting it again, crashing the whole thing to the desktop. But even without these extreme cases, it still is confusing as you don't really know when something is initialized, the flow of your application becomes hidden, which can introduce all kind of hard to debug bugs. Anyway, after having seen this abuse, I kind of decided to avoid them wherever I could. Yeah, you might need to pass some objects around through the constructor more then you want, specially for people with an alergic reaction to constructors. But it does make the flow of your application more clear and helps to reduce bugs because you are forced to initialize things in order or you will not be able to pass a reference to the depending class.
I guess hating on globals is the cool thing to do here. LOL

Standard function call is the way to go. Hell you can even use your Logger class if you want. Except you keep that hidden.

[source lang="cpp"]//basic example yo.
void logMessage(string message) {
static Logger log;

//post log message here using log object.
log.log(message);

}[/source]

This is only really required if Logger keeps any state, such as the file its logging to among other things.

This topic is closed to new replies.

Advertisement