Bark at the Moon: Better Lua Logging

In this micro-blog, I’ll showcase how we at Third Kind Games implemented better logging in our Lua scripts.

In order to log something to TTY from Lua you’ll typically do that following:

Debug.Log("Output to TTY please!")

Which is OK and will do what it says, however, in order to disable that particular piece of logging, you’ll have to REM it out.

-- Debug.Log("Output to TTY please!")

Again, this is fine and does what it says on the tin.  The problem you’ll reach, however, is when you start having lots of logs throughout your scripts, where you’ll end up having to fish through the scripts looking for ones to REM and un-REM.  This is not scalable.

Here at Third Kind, we do things a bit differently.  This is what our logging looks like:

TKGDebug.Set("MyDebugTTY", false) -- note the second parameter

function mycode:somefunction()
  TKGDebug.Log("MyDebugTTY", "Output to TTY please!");

The second parameter of the “Set” function is a bool that will turn on or off all logs within the script that are associated with the “MyDebugTTY” descriptor.  Much more useful!!

Better Logging

To help you all out, below is the source that you can use in your own projects to improve your logging.  Let us know what you think in the comments.

local luaext	= require"scripts.modules.luaext";


function TKGDebug.Set(debugName, enabled)
    _G.TKGDebug[debugName] = enabled;

function TKGDebug.Log(debugName, ...)
    if _G.TKGDebug[debugName] then 
        if select("#",...) > 1 then
            TKGDebug.Log(debugName, string.format(...))
            if type(...) == "string" then
                message = ...
                message = luaext.tostring( ... )
            Debug.Log("[" .. debugName .. "] " .. message )


Leave a Reply