Simple, better Unity logging

Dan Puzey

One of the issues that you can run into when developing with Unity is that logging is quite expensive. It's entirely possible, if you're trying to log a verbose amount of processing for one reason or another, you can end up crippling the framerate of your game. There are performance investigations I've done in Unity that have ended up with the logging being the most expensive portion of the code!

The problem with this is that it's often painful to remove and reinstate logging code repeatedly: logging is useful, so you don't necessarily want to remove the code, but you can't have a performant build with it still in place.

With that in mind, I've just published this Gist on Github. It's a first-pass for something that will reduce the performance impact of logging in game builds, and make it easier to control. Here's the code - read on for the details:

This code makes less logging calls when compiled as a release build, because the Verbose methods are removed at compile time. They simply don't exist in your builds.

This class also integrates string.Format capability into the logging methods' signature.* This brings another speed advantage: if the logging method isn't called, the string.Format isn't evaluated at all. It's surprising how much CPU time you can spend on string manipulation for strings that aren't going to be logged: this code prevents that waste.

The plan going forward is to add code so that the standard Message call is only handled (on release builds) when a command-line parameter is present. This means that, for a typical build, you'd only log warnings and errors. Imagine how much log output - and thus performance - this could be saving...

To go with this, I'd recommend a more advanced console than the one built in to Unity. I use Editor Console Pro, which gives me custom highlighting, filtering and more detailed call stacks. It has the occasional glitch, but the ability to quickly search and filter logs for the things I'm interested in can save so much time that it's easily forgiven then occasional hiccup.

I hope this proves a useful tool - please leave a comment if you find this helpful, or if you have any questions!

* If you're "adding" strings together instead of using string.Format then you really need to change that!