Easy Logging in Lua Using log.lua

Today I want to give you a brief introduction to log.lua, a nice library which I’ve been using lately on a couple of projects.

Log.lua creates output like so.

Example of log.lua’s output

Not only is the coloring nice, in my opinion, it demonstrates a useful aspect of the library: it’s ability to log messages at different “levels”. For each level of output you see in that image, e.g. “trace” and “warn”, log.lua provides corresponding functions like log.trace() and log.warn(). They accept any number of arguments, concatenate them into a string, and produce output like the above.

However, maybe you don’t want output to go to the console. The library allows you to send all of its output to a file if that’s your preference. The configuration is simple:

-- We assume that we've written
--     local log = require("log")
-- somewhere before this.

log.outfile = "/tmp/log-lua.txt"
log.usecolor = false

It is not mandatory to write log.usecolor = false if you’re sending output to a file, but personally I’ve found it useful to disable colored output in that situation.

The final aspect of log.lua which you can configure is the minimum level of information to log. The levels are, in order of weakest to strongest:

  1. trace
  2. debug
  3. info
  4. warn
  5. error
  6. fatal

Assigning one of these values (as a string) to log.level controls the minimum level of logging information. For example, if you were to use log.level = "warn" then any calls to log.trace(), log.debug(), and log.info() would produce no output. This is quite useful for when you don’t want to see everything, particularly if you make heavy use of the lower-levels, and just want to focus on more serious issues like those reported by log.error() or log.fatal().

And that’s pretty much it! The library also has a log.check() function similar in intent to Lua’s standard assert(), but the project’s README documents it with examples.

If you’re writing an application in Lua and want an easy way to create logs then I recommend you consider the log.lua library. It’s been a useful tool for me particularly for game development involving Lua.


Add Your Thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s