game-programming-patterns icon indicating copy to clipboard operation
game-programming-patterns copied to clipboard

Better Anti-Singleton pattern than logging?

Open greggman opened this issue 9 years ago • 0 comments

TL;DR: Can you come up with a better anti-singleton example than your Log example?

I pointed your chapter on Singletons being mostly useless and after a lengthy discussion it seemed pretty clear your example of the Log singleton doesn't really hold up as a good example.

You mentioned on a big game needed different logs. One friend pointed to having an enum for the logs which is common

Logger.Log("this gets logged to physics.log", PHYSICS);

I pointed out the advantage of using a non-global (non singleton) in this case is that you can't put the wrong ENUM when typing new code. Also if you copy and paste you can't put the wrong enum.

But that got me thinking you could push/pop the current logger

ProcessPhysics() {
   Logger.PushDest(PHYSICS);
   ... process all physics ...
   Logger.PopDest(PHYSICS);
}

Now all the code run by physics can call a global/singleton Log function and it will go to the correct place. This "might" even have the advantage that code the physics engine calls will also go to the physics log. Whether that's good or bad I don't know. I can imagine cases where it's good and cases where it's bad. You could even prefix all log messages with the entire stack of pushes or indent by stack depth. Both very helpful.

Another example that comes to mind is the debug module used in node.js. Effectively you make a log wrapper in each module

var debug = require('debug')('someprefix');

debug is now a function that logs and will prefix every log message by "someprefix" but all logging goes to the same file. You could argue that's often best because a mixed log shows flow where as separate logs that info is lost (unless you have some global log output counter that prefixes each log message so you can later merge them by id).

Off the top of my head one disadvantage to the Push/Pop style is threads but there are such things as threading variables to solve that.

So, is there a better example than Logging?

greggman avatar Jan 20 '16 05:01 greggman